<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var ConcatSource = require("webpack/lib/ConcatSource");
var async = require("async");
var ExtractedModule = require("./ExtractedModule");
var Chunk = require("webpack/lib/Chunk");
var OrderUndefinedError = require("./OrderUndefinedError");
var loaderUtils = require("loader-utils");

var nextId = 0;

function ExtractTextPluginCompilation() {
	this.modulesByIdentifier = {};
}

ExtractTextPlugin.prototype.mergeNonInitialChunks = function(chunk, intoChunk, checkedChunks) {
	if(!intoChunk) {
		checkedChunks = [];
		chunk.chunks.forEach(function(c) {
			if(c.initial) return;
			this.mergeNonInitialChunks(c, chunk, checkedChunks);
		}, this);
	} else if(checkedChunks.indexOf(chunk) < 0) {
		checkedChunks.push(chunk);
		chunk.modules.slice().forEach(function(module) {
			chunk.removeModule(module);
			intoChunk.addModule(module);
			module.addChunk(intoChunk);
		});
		chunk.chunks.forEach(function(c) {
			if(c.initial) return;
			this.mergeNonInitialChunks(c, intoChunk, checkedChunks);
		}, this);
	}
};

ExtractTextPluginCompilation.prototype.addModule = function(identifier, originalModule, source, additionalInformation, sourceMap, prevModules) {
	var m;
	if(!this.modulesByIdentifier[identifier]) {
		m = this.modulesByIdentifier[identifier] = new ExtractedModule(identifier, originalModule, source, sourceMap, additionalInformation, prevModules);
	} else {
		m = this.modulesByIdentifier[identifier];
		m.addPrevModules(prevModules);
		if(originalModule.index2 < m.getOriginalModule().index2) {
			m.setOriginalModule(originalModule);
		}
	}
	return m;
};

ExtractTextPluginCompilation.prototype.addResultToChunk = function(identifier, result, originalModule, extractedChunk) {
	if(!Array.isArray(result)) {
		result = [[identifier, result]];
	}
	var counterMap = {};
	var prevModules = [];
	result.forEach(function(item) {
		var c = counterMap[item[0]];
		var module = this.addModule.call(this, item[0] + (c || ""), originalModule, item[1], item[2], item[3], prevModules.slice());
		extractedChunk.addModule(module);
		module.addChunk(extractedChunk);
		counterMap[item[0]] = (c || 0) + 1;
		prevModules.push(module);
	}, this);
};

ExtractTextPlugin.prototype.renderExtractedChunk = function(chunk) {
	var source = new ConcatSource();
	chunk.modules.forEach(function(module) {
		var moduleSource = module.source();
		source.add(this.applyAdditionalInformation(moduleSource, module.additionalInformation));
	}, this);
	return source;
};

function isInvalidOrder(a, b) {
	var bBeforeA = a.getPrevModules().indexOf(b) >= 0;
	var aBeforeB = b.getPrevModules().indexOf(a) >= 0;
	return aBeforeB && bBeforeA;
}

function getOrder(a, b) {
	var aOrder = a.getOrder();
	var bOrder = b.getOrder();
	if(aOrder < bOrder) return -1;
	if(aOrder > bOrder) return 1;
	var aIndex = a.getOriginalModule().index2;
	var bIndex = b.getOriginalModule().index2;
	if(aIndex < bIndex) return -1;
	if(aIndex > bIndex) return 1;
	var bBeforeA = a.getPrevModules().indexOf(b) >= 0;
	var aBeforeB = b.getPrevModules().indexOf(a) >= 0;
	if(aBeforeB && !bBeforeA) return -1;
	if(!aBeforeB && bBeforeA) return 1;
	var ai = a.identifier();
	var bi = b.identifier();
	if(ai < bi) return -1;
	if(ai > bi) return 1;
	return 0;
}

function ExtractTextPlugin(id, filename, options) {
	if(typeof filename !== "string") {
		options = filename;
		filename = id;
		id = ++nextId;
	}
	if(!options) options = {};
	this.filename = filename;
	this.options = options;
	this.id = id;
}
module.exports = ExtractTextPlugin;

function mergeOptions(a, b) {
	if(!b) return a;
	Object.keys(b).forEach(function(key) {
		a[key] = b[key];
	});
	return a;
}

ExtractTextPlugin.loader = function(options) {
	return require.resolve("./loader") + (options ? "?" + JSON.stringify(options) : "");
};

ExtractTextPlugin.extract = function(before, loader, options) {
	if(typeof loader === "string" || Array.isArray(loader)) {
		if(typeof before === "string") {
			before = before.split("!")
		}
		return [
			ExtractTextPlugin.loader(mergeOptions({omit: before.length, extract: true, remove: true}, options))
		].concat(before, loader).join("!");
	} else {
		options = loader;
		loader = before;
		return [
			ExtractTextPlugin.loader(mergeOptions({remove: true}, options)),
		].concat(loader).join("!");
	}
};

ExtractTextPlugin.prototype.applyAdditionalInformation = function(source, info) {
	if(info) {
		return new ConcatSource(
			"@media " + info[0] + " {",
			source,
			"}"
		);
	}
	return source;
};

ExtractTextPlugin.prototype.loader = function(options) {
	options = JSON.parse(JSON.stringify(options || {}));
	options.id = this.id;
	return ExtractTextPlugin.loader(options);
};

ExtractTextPlugin.prototype.extract = function(before, loader, options) {
	if(typeof loader === "string") {
		return [
			this.loader(mergeOptions({omit: before.split("!").length, extract: true, remove: true}, options)),
			before,
			loader
		].join("!");
	} else {
		options = loader;
		loader = before;
		return [
			this.loader(mergeOptions({remove: true}, options)),
			loader
		].join("!");
	}
};

ExtractTextPlugin.prototype.apply = function(compiler) {
	var options = this.options;
	compiler.plugin("this-compilation", function(compilation) {
		var extractCompilation = new ExtractTextPluginCompilation();
		compilation.plugin("normal-module-loader", function(loaderContext, module) {
			loaderContext[__dirname] = function(content, opt) {
				if(options.disable)
					return false;
				if(!Array.isArray(content) && content !== null)
					throw new Error("Exported value is not a string.");
				module.meta[__dirname] = {
					content: content,
					options: opt || {}
				};
				return options.allChunks || module.meta[__dirname + "/extract"]; // eslint-disable-line no-path-concat
			};
		});
		var filename = this.filename;
		var id = this.id;
		var extractedChunks, entryChunks, initialChunks;
		compilation.plugin("optimize", function() {
			entryChunks = compilation.chunks.filter(function(c) {
				return c.entry;
			});
			initialChunks = compilation.chunks.filter(function(c) {
				return c.initial;
			});
		});
		compilation.plugin("optimize-tree", function(chunks, modules, callback) {
			extractedChunks = chunks.map(function() {
				return new Chunk();
			});
			chunks.forEach(function(chunk, i) {
				var extractedChunk = extractedChunks[i];
				extractedChunk.index = i;
				extractedChunk.originalChunk = chunk;
				extractedChunk.name = chunk.name;
				extractedChunk.entry = chunk.entry;
				extractedChunk.initial = chunk.initial;
				chunk.chunks.forEach(function(c) {
					extractedChunk.addChunk(extractedChunks[chunks.indexOf(c)]);
				});
				chunk.parents.forEach(function(c) {
					extractedChunk.addParent(extractedChunks[chunks.indexOf(c)]);
				});
			});
			entryChunks.forEach(function(chunk) {
				var idx = chunks.indexOf(chunk);
				if(idx < 0) return;
				var extractedChunk = extractedChunks[idx];
				extractedChunk.entry = true;
			});
			initialChunks.forEach(function(chunk) {
				var idx = chunks.indexOf(chunk);
				if(idx < 0) return;
				var extractedChunk = extractedChunks[idx];
				extractedChunk.initial = true;
			});
			async.forEach(chunks, function(chunk, callback) {
				var extractedChunk = extractedChunks[chunks.indexOf(chunk)];
				var shouldExtract = !!(options.allChunks || chunk.initial);
				async.forEach(chunk.modules.slice(), function(module, callback) {
					var meta = module.meta && module.meta[__dirname];
					if(meta && (!meta.options.id || meta.options.id === id)) {
						var wasExtracted = Array.isArray(meta.content);
						if(shouldExtract !== wasExtracted) {
							module.meta[__dirname + "/extract"] = shouldExtract; // eslint-disable-line no-path-concat
							compilation.rebuildModule(module, function(err) {
								if(err) {
									compilation.errors.push(err);
									return callback();
								}
								meta = module.meta[__dirname];
								if(!Array.isArray(meta.content)) {
									err = new Error(module.identifier() + " doesn't export content");
									compilation.errors.push(err);
									return callback();
								}
								if(meta.content)
									extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
								callback();
							});
						} else {
							if(meta.content)
								extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
							callback();
						}
					} else callback();
				}, function(err) {
					if(err) return callback(err);
					callback();
				});
			}, function(err) {
				if(err) return callback(err);
				extractedChunks.forEach(function(extractedChunk) {
					if(extractedChunk.initial)
						this.mergeNonInitialChunks(extractedChunk);
				}, this);
				compilation.applyPlugins("optimize-extracted-chunks", extractedChunks);
				callback();
			}.bind(this));
		}.bind(this));
		compilation.plugin("additional-assets", function(callback) {
			extractedChunks.forEach(function(extractedChunk) {
				if(extractedChunk.modules.length) {
					extractedChunk.modules.sort(function(a, b) {
						if(isInvalidOrder(a, b)) {
							compilation.errors.push(new OrderUndefinedError(a.getOriginalModule()));
							compilation.errors.push(new OrderUndefinedError(b.getOriginalModule()));
						}
						return getOrder(a, b);
					});
					var chunk = extractedChunk.originalChunk;
					var source = this.renderExtractedChunk(extractedChunk);
					var file = compilation.getPath(filename, {
						chunk: chunk
					}).replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function() {
						return loaderUtils.getHashDigest(source.source(), arguments[1], arguments[2], parseInt(arguments[3], 10));
					});
					compilation.assets[file] = source;
					chunk.files.push(file);
				}
			}, this);
			callback();
		}.bind(this));
	}.bind(this));
};
<commit_msg>Make instances also support arrays<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var ConcatSource = require("webpack/lib/ConcatSource");
var async = require("async");
var ExtractedModule = require("./ExtractedModule");
var Chunk = require("webpack/lib/Chunk");
var OrderUndefinedError = require("./OrderUndefinedError");
var loaderUtils = require("loader-utils");

var nextId = 0;

function ExtractTextPluginCompilation() {
	this.modulesByIdentifier = {};
}

ExtractTextPlugin.prototype.mergeNonInitialChunks = function(chunk, intoChunk, checkedChunks) {
	if(!intoChunk) {
		checkedChunks = [];
		chunk.chunks.forEach(function(c) {
			if(c.initial) return;
			this.mergeNonInitialChunks(c, chunk, checkedChunks);
		}, this);
	} else if(checkedChunks.indexOf(chunk) < 0) {
		checkedChunks.push(chunk);
		chunk.modules.slice().forEach(function(module) {
			chunk.removeModule(module);
			intoChunk.addModule(module);
			module.addChunk(intoChunk);
		});
		chunk.chunks.forEach(function(c) {
			if(c.initial) return;
			this.mergeNonInitialChunks(c, intoChunk, checkedChunks);
		}, this);
	}
};

ExtractTextPluginCompilation.prototype.addModule = function(identifier, originalModule, source, additionalInformation, sourceMap, prevModules) {
	var m;
	if(!this.modulesByIdentifier[identifier]) {
		m = this.modulesByIdentifier[identifier] = new ExtractedModule(identifier, originalModule, source, sourceMap, additionalInformation, prevModules);
	} else {
		m = this.modulesByIdentifier[identifier];
		m.addPrevModules(prevModules);
		if(originalModule.index2 < m.getOriginalModule().index2) {
			m.setOriginalModule(originalModule);
		}
	}
	return m;
};

ExtractTextPluginCompilation.prototype.addResultToChunk = function(identifier, result, originalModule, extractedChunk) {
	if(!Array.isArray(result)) {
		result = [[identifier, result]];
	}
	var counterMap = {};
	var prevModules = [];
	result.forEach(function(item) {
		var c = counterMap[item[0]];
		var module = this.addModule.call(this, item[0] + (c || ""), originalModule, item[1], item[2], item[3], prevModules.slice());
		extractedChunk.addModule(module);
		module.addChunk(extractedChunk);
		counterMap[item[0]] = (c || 0) + 1;
		prevModules.push(module);
	}, this);
};

ExtractTextPlugin.prototype.renderExtractedChunk = function(chunk) {
	var source = new ConcatSource();
	chunk.modules.forEach(function(module) {
		var moduleSource = module.source();
		source.add(this.applyAdditionalInformation(moduleSource, module.additionalInformation));
	}, this);
	return source;
};

function isInvalidOrder(a, b) {
	var bBeforeA = a.getPrevModules().indexOf(b) >= 0;
	var aBeforeB = b.getPrevModules().indexOf(a) >= 0;
	return aBeforeB && bBeforeA;
}

function getOrder(a, b) {
	var aOrder = a.getOrder();
	var bOrder = b.getOrder();
	if(aOrder < bOrder) return -1;
	if(aOrder > bOrder) return 1;
	var aIndex = a.getOriginalModule().index2;
	var bIndex = b.getOriginalModule().index2;
	if(aIndex < bIndex) return -1;
	if(aIndex > bIndex) return 1;
	var bBeforeA = a.getPrevModules().indexOf(b) >= 0;
	var aBeforeB = b.getPrevModules().indexOf(a) >= 0;
	if(aBeforeB && !bBeforeA) return -1;
	if(!aBeforeB && bBeforeA) return 1;
	var ai = a.identifier();
	var bi = b.identifier();
	if(ai < bi) return -1;
	if(ai > bi) return 1;
	return 0;
}

function ExtractTextPlugin(id, filename, options) {
	if(typeof filename !== "string") {
		options = filename;
		filename = id;
		id = ++nextId;
	}
	if(!options) options = {};
	this.filename = filename;
	this.options = options;
	this.id = id;
}
module.exports = ExtractTextPlugin;

function mergeOptions(a, b) {
	if(!b) return a;
	Object.keys(b).forEach(function(key) {
		a[key] = b[key];
	});
	return a;
}

ExtractTextPlugin.loader = function(options) {
	return require.resolve("./loader") + (options ? "?" + JSON.stringify(options) : "");
};

ExtractTextPlugin.extract = function(before, loader, options) {
	if(typeof loader === "string" || Array.isArray(loader)) {
		if(typeof before === "string") {
			before = before.split("!")
		}
		return [
			ExtractTextPlugin.loader(mergeOptions({omit: before.length, extract: true, remove: true}, options))
		].concat(before, loader).join("!");
	} else {
		options = loader;
		loader = before;
		return [
			ExtractTextPlugin.loader(mergeOptions({remove: true}, options)),
		].concat(loader).join("!");
	}
};

ExtractTextPlugin.prototype.applyAdditionalInformation = function(source, info) {
	if(info) {
		return new ConcatSource(
			"@media " + info[0] + " {",
			source,
			"}"
		);
	}
	return source;
};

ExtractTextPlugin.prototype.loader = function(options) {
	options = JSON.parse(JSON.stringify(options || {}));
	options.id = this.id;
	return ExtractTextPlugin.loader(options);
};

ExtractTextPlugin.prototype.extract = function(before, loader, options) {
	if(typeof loader === "string" || Array.isArray(loader)) {
		if(typeof before === "string") {
			before = before.split("!")
		}
		return [
			ExtractTextPlugin.loader(mergeOptions({omit: before.length, extract: true, remove: true}, options))
		].concat(before, loader).join("!");
	} else {
		options = loader;
		loader = before;
		return [
			ExtractTextPlugin.loader(mergeOptions({remove: true}, options)),
		].concat(loader).join("!");
	}
};

ExtractTextPlugin.prototype.apply = function(compiler) {
	var options = this.options;
	compiler.plugin("this-compilation", function(compilation) {
		var extractCompilation = new ExtractTextPluginCompilation();
		compilation.plugin("normal-module-loader", function(loaderContext, module) {
			loaderContext[__dirname] = function(content, opt) {
				if(options.disable)
					return false;
				if(!Array.isArray(content) && content !== null)
					throw new Error("Exported value is not a string.");
				module.meta[__dirname] = {
					content: content,
					options: opt || {}
				};
				return options.allChunks || module.meta[__dirname + "/extract"]; // eslint-disable-line no-path-concat
			};
		});
		var filename = this.filename;
		var id = this.id;
		var extractedChunks, entryChunks, initialChunks;
		compilation.plugin("optimize", function() {
			entryChunks = compilation.chunks.filter(function(c) {
				return c.entry;
			});
			initialChunks = compilation.chunks.filter(function(c) {
				return c.initial;
			});
		});
		compilation.plugin("optimize-tree", function(chunks, modules, callback) {
			extractedChunks = chunks.map(function() {
				return new Chunk();
			});
			chunks.forEach(function(chunk, i) {
				var extractedChunk = extractedChunks[i];
				extractedChunk.index = i;
				extractedChunk.originalChunk = chunk;
				extractedChunk.name = chunk.name;
				extractedChunk.entry = chunk.entry;
				extractedChunk.initial = chunk.initial;
				chunk.chunks.forEach(function(c) {
					extractedChunk.addChunk(extractedChunks[chunks.indexOf(c)]);
				});
				chunk.parents.forEach(function(c) {
					extractedChunk.addParent(extractedChunks[chunks.indexOf(c)]);
				});
			});
			entryChunks.forEach(function(chunk) {
				var idx = chunks.indexOf(chunk);
				if(idx < 0) return;
				var extractedChunk = extractedChunks[idx];
				extractedChunk.entry = true;
			});
			initialChunks.forEach(function(chunk) {
				var idx = chunks.indexOf(chunk);
				if(idx < 0) return;
				var extractedChunk = extractedChunks[idx];
				extractedChunk.initial = true;
			});
			async.forEach(chunks, function(chunk, callback) {
				var extractedChunk = extractedChunks[chunks.indexOf(chunk)];
				var shouldExtract = !!(options.allChunks || chunk.initial);
				async.forEach(chunk.modules.slice(), function(module, callback) {
					var meta = module.meta && module.meta[__dirname];
					if(meta && (!meta.options.id || meta.options.id === id)) {
						var wasExtracted = Array.isArray(meta.content);
						if(shouldExtract !== wasExtracted) {
							module.meta[__dirname + "/extract"] = shouldExtract; // eslint-disable-line no-path-concat
							compilation.rebuildModule(module, function(err) {
								if(err) {
									compilation.errors.push(err);
									return callback();
								}
								meta = module.meta[__dirname];
								if(!Array.isArray(meta.content)) {
									err = new Error(module.identifier() + " doesn't export content");
									compilation.errors.push(err);
									return callback();
								}
								if(meta.content)
									extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
								callback();
							});
						} else {
							if(meta.content)
								extractCompilation.addResultToChunk(module.identifier(), meta.content, module, extractedChunk);
							callback();
						}
					} else callback();
				}, function(err) {
					if(err) return callback(err);
					callback();
				});
			}, function(err) {
				if(err) return callback(err);
				extractedChunks.forEach(function(extractedChunk) {
					if(extractedChunk.initial)
						this.mergeNonInitialChunks(extractedChunk);
				}, this);
				compilation.applyPlugins("optimize-extracted-chunks", extractedChunks);
				callback();
			}.bind(this));
		}.bind(this));
		compilation.plugin("additional-assets", function(callback) {
			extractedChunks.forEach(function(extractedChunk) {
				if(extractedChunk.modules.length) {
					extractedChunk.modules.sort(function(a, b) {
						if(isInvalidOrder(a, b)) {
							compilation.errors.push(new OrderUndefinedError(a.getOriginalModule()));
							compilation.errors.push(new OrderUndefinedError(b.getOriginalModule()));
						}
						return getOrder(a, b);
					});
					var chunk = extractedChunk.originalChunk;
					var source = this.renderExtractedChunk(extractedChunk);
					var file = compilation.getPath(filename, {
						chunk: chunk
					}).replace(/\[(?:(\w+):)?contenthash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function() {
						return loaderUtils.getHashDigest(source.source(), arguments[1], arguments[2], parseInt(arguments[3], 10));
					});
					compilation.assets[file] = source;
					chunk.files.push(file);
				}
			}, this);
			callback();
		}.bind(this));
	}.bind(this));
};
<|endoftext|>


<commit_before>var clone = require("./lib/clone.js")
var executeScripts = require("./lib/execute-scripts.js")

var forEachEls = require("./lib/foreach-els.js")

var newUid = require("./lib/uniqueid.js")

var noop = require("./lib/util/noop")

var on = require("./lib/events/on.js")
// var off = require("./lib/events/on.js")
var trigger = require("./lib/events/trigger.js")

var defaultSwitches = require("./lib/switches")

var Pjax = function(options) {
    this.state = {
      numPendingSwitches: 0,
      href: null,
      options: null
    }

    var parseOptions = require("./lib/proto/parse-options.js");
    parseOptions.apply(this,[options])
    this.log("Pjax options", this.options)

    this.maxUid = this.lastUid = newUid()

    this.parseDOM(document)

    on(window, "popstate", function(st) {
      if (st.state) {
        var opt = clone(this.options)
        opt.url = st.state.url
        opt.title = st.state.title
        opt.history = false
        opt.requestOptions = {};
        opt.scrollPos = st.state.scrollPos
        if (st.state.uid < this.lastUid) {
          opt.backward = true
        }
        else {
          opt.forward = true
        }
        this.lastUid = st.state.uid

        // @todo implement history cache here, based on uid
        this.loadUrl(st.state.url, opt)
      }
    }.bind(this))
  }

Pjax.switches = defaultSwitches

Pjax.prototype = {
  log: require("./lib/proto/log.js"),

  getElements: require("./lib/proto/get-elements.js"),

  parseDOM: require("./lib/proto/parse-dom.js"),

  refresh: require("./lib/proto/refresh.js"),

  reload: require("./lib/reload.js"),

  attachLink: require("./lib/proto/attach-link.js"),

  attachForm: require("./lib/proto/attach-form.js"),

  forEachSelectors: function(cb, context, DOMcontext) {
    return require("./lib/foreach-selectors.js").bind(this)(this.options.selectors, cb, context, DOMcontext)
  },

  switchSelectors: function(selectors, fromEl, toEl, options) {
    return require("./lib/switches-selectors.js").bind(this)(this.options.switches, this.options.switchesOptions, selectors, fromEl, toEl, options)
  },

  // too much problem with the code below
  // + it’s too dangerous
  //   switchFallback: function(fromEl, toEl) {
  //     this.switchSelectors(["head", "body"], fromEl, toEl)
  //     // execute script when DOM is like it should be
  //     Pjax.executeScripts(document.querySelector("head"))
  //     Pjax.executeScripts(document.querySelector("body"))
  //   }

  latestChance: function(href) {
    window.location = href
  },

  onSwitch: function() {
    trigger(window, "resize scroll")

    this.state.numPendingSwitches--

    // debounce calls, so we only run this once after all switches are finished.
    if (this.state.numPendingSwitches === 0) {
      this.afterAllSwitches()
    }
  },

  loadContent: function(html, options) {
    var tmpEl = document.implementation.createHTMLDocument("pjax")

    // parse HTML attributes to copy them
    // since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
    var htmlRegex = /<html[^>]+>/gi
    var htmlAttribsRegex = /\s?[a-z:]+(?:\=(?:\'|\")[^\'\">]+(?:\'|\"))*/gi
    var matches = html.match(htmlRegex)
    if (matches && matches.length) {
      matches = matches[0].match(htmlAttribsRegex)
      if (matches.length) {
        matches.shift()
        matches.forEach(function(htmlAttrib) {
          var attr = htmlAttrib.trim().split("=")
          if (attr.length === 1) {
            tmpEl.documentElement.setAttribute(attr[0], true)
          }
          else {
            tmpEl.documentElement.setAttribute(attr[0], attr[1].slice(1, -1))
          }
        })
      }
    }

    tmpEl.documentElement.innerHTML = html
    this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length)

    // Clear out any focused controls before inserting new page contents.
    // we clear focus on non form elements
    if (document.activeElement && !document.activeElement.value) {
      try {
        document.activeElement.blur()
      } catch (e) { }
    }

    // try {
    this.switchSelectors(this.options.selectors, tmpEl, document, options)

    // }
    // catch(e) {
    //   if (this.options.debug) {
    //     this.log("Pjax switch fail: ", e)
    //   }
    //   this.switchFallback(tmpEl, document)
    // }
  },

  abortRequest: require("./lib/abort-request.js"),

  doRequest: require("./lib/send-request.js"),

  loadUrl: function(href, options) {
    this.log("load href", href, options)

    // Abort any previous request
    this.abortRequest(this.request)

    trigger(document, "pjax:send", options);

    // Do the request
    options.requestOptions.timeout = this.options.timeout
    this.request = this.doRequest(href, options.requestOptions, function(html, request) {
      // Fail if unable to load HTML via AJAX
      if (html === false) {
        trigger(document,"pjax:complete pjax:error", options)

        return
      }

      // push scroll position to history
      var currentState = window.history.state || {}
      window.history.replaceState({
          url: currentState.url || window.location.href,
          title: currentState.title || document.title,
          uid: currentState.uid || newUid(),
          scrollPos: [document.documentElement.scrollLeft || document.body.scrollLeft,
            document.documentElement.scrollTop || document.body.scrollTop]
        },
        document.title, window.location)

      // Clear out any focused controls before inserting new page contents.
      document.activeElement.blur()

      var oldHref = href
      if (request.responseURL) {
        if (href !== request.responseURL) {
          href = request.responseURL
        }
      }
      else if (request.getResponseHeader("X-PJAX-URL")) {
        href = request.getResponseHeader("X-PJAX-URL")
      }
      else if (request.getResponseHeader("X-XHR-Redirected-To")) {
        href = request.getResponseHeader("X-XHR-Redirected-To")
      }

      // Add back the hash if it was removed
      var a = document.createElement("a")
      a.href = oldHref
      var oldHash = a.hash
      a.href = href
      if (oldHash && !a.hash) {
        a.hash = oldHash
        href = a.href
      }

      this.state.href = href
      this.state.options = clone(options)

      try {
        this.loadContent(html, options)
      }
      catch (e) {
        if (!this.options.debug) {
          if (console && console.error) {
            console.error("Pjax switch fail: ", e)
          }
          this.latestChance(href)
          return
        }
        else {
          throw e
        }
      }
    }.bind(this))
  },

  afterAllSwitches: function() {
    // FF bug: Won’t autofocus fields that are inserted via JS.
    // This behavior is incorrect. So if theres no current focus, autofocus
    // the last field.
    //
    // http://www.w3.org/html/wg/drafts/html/master/forms.html
    var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop()
    if (autofocusEl && document.activeElement !== autofocusEl) {
      autofocusEl.focus();
    }

    // execute scripts when DOM have been completely updated
    this.options.selectors.forEach(function(selector) {
      forEachEls(document.querySelectorAll(selector), function(el) {
        executeScripts(el)
      })
    })

    var state = this.state

    if (state.options.history) {
      if (!window.history.state) {
        this.lastUid = this.maxUid = newUid()
        window.history.replaceState({
            url: window.location.href,
            title: document.title,
            uid: this.maxUid,
            scrollPos: [0, 0]
          },
          document.title)
      }

      // Update browser history
      this.lastUid = this.maxUid = newUid()

      window.history.pushState({
          url: state.href,
          title: state.options.title,
          uid: this.maxUid,
          scrollPos: [0, 0]
        },
        state.options.title,
        state.href)
    }

    this.forEachSelectors(function(el) {
      this.parseDOM(el)
    }, this)

    // Fire Events
    trigger(document,"pjax:complete pjax:success", state.options)

    if (typeof state.options.analytics === "function") {
      state.options.analytics()
    }

    if (state.options.history) {
      // First parse url and check for hash to override scroll
      var a = document.createElement("a")
      a.href = this.state.href
      if (a.hash) {
        var name = a.hash.slice(1)
        name = decodeURIComponent(name)

        var curtop = 0
        var target = document.getElementById(name) || document.getElementsByName(name)[0]
        if (target) {
          // http://stackoverflow.com/questions/8111094/cross-browser-javascript-function-to-find-actual-position-of-an-element-in-page
          if (target.offsetParent) {
            do {
              curtop += target.offsetTop

              target = target.offsetParent
            } while (target)
          }
        }
        window.scrollTo(0, curtop);
      }
      else if (state.options.scrollTo !== false) {
        // Scroll page to top on new page load
        if (state.options.scrollTo.length > 1) {
          window.scrollTo(state.options.scrollTo[0], state.options.scrollTo[1])
        }
        else {
          window.scrollTo(0, state.options.scrollTo)
        }
      }
    }
    else if (state.options.scrollRestoration && state.options.scrollPos) {
      window.scrollTo(state.options.scrollPos[0], state.options.scrollPos[1])
    }

    this.state = {
      numPendingSwitches: 0,
      href: null,
      options: null
    }
  }
}

Pjax.isSupported = require("./lib/is-supported.js");

// arguably could do `if( require("./lib/is-supported.js")()) {` but that might be a little to simple
if (Pjax.isSupported()) {
  module.exports = Pjax
}
// if there isn’t required browser functions, returning stupid api
else {
  var stupidPjax = noop
  for (var key in Pjax.prototype) {
    if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") {
      stupidPjax[key] = noop
    }
  }

  module.exports = stupidPjax
}
<commit_msg>Opt in to manual scroll restoration in browsers that support it<commit_after>var clone = require("./lib/clone.js")
var executeScripts = require("./lib/execute-scripts.js")

var forEachEls = require("./lib/foreach-els.js")

var newUid = require("./lib/uniqueid.js")

var noop = require("./lib/util/noop")

var on = require("./lib/events/on.js")
// var off = require("./lib/events/on.js")
var trigger = require("./lib/events/trigger.js")

var defaultSwitches = require("./lib/switches")

var Pjax = function(options) {
    this.state = {
      numPendingSwitches: 0,
      href: null,
      options: null
    }

    var parseOptions = require("./lib/proto/parse-options.js");
    parseOptions.apply(this,[options])
    this.log("Pjax options", this.options)

    if (this.options.scrollRestoration && "scrollRestoration" in history) {
      history.scrollRestoration = "manual"
    }

    this.maxUid = this.lastUid = newUid()

    this.parseDOM(document)

    on(window, "popstate", function(st) {
      if (st.state) {
        var opt = clone(this.options)
        opt.url = st.state.url
        opt.title = st.state.title
        opt.history = false
        opt.requestOptions = {};
        opt.scrollPos = st.state.scrollPos
        if (st.state.uid < this.lastUid) {
          opt.backward = true
        }
        else {
          opt.forward = true
        }
        this.lastUid = st.state.uid

        // @todo implement history cache here, based on uid
        this.loadUrl(st.state.url, opt)
      }
    }.bind(this))
  }

Pjax.switches = defaultSwitches

Pjax.prototype = {
  log: require("./lib/proto/log.js"),

  getElements: require("./lib/proto/get-elements.js"),

  parseDOM: require("./lib/proto/parse-dom.js"),

  refresh: require("./lib/proto/refresh.js"),

  reload: require("./lib/reload.js"),

  attachLink: require("./lib/proto/attach-link.js"),

  attachForm: require("./lib/proto/attach-form.js"),

  forEachSelectors: function(cb, context, DOMcontext) {
    return require("./lib/foreach-selectors.js").bind(this)(this.options.selectors, cb, context, DOMcontext)
  },

  switchSelectors: function(selectors, fromEl, toEl, options) {
    return require("./lib/switches-selectors.js").bind(this)(this.options.switches, this.options.switchesOptions, selectors, fromEl, toEl, options)
  },

  // too much problem with the code below
  // + it’s too dangerous
  //   switchFallback: function(fromEl, toEl) {
  //     this.switchSelectors(["head", "body"], fromEl, toEl)
  //     // execute script when DOM is like it should be
  //     Pjax.executeScripts(document.querySelector("head"))
  //     Pjax.executeScripts(document.querySelector("body"))
  //   }

  latestChance: function(href) {
    window.location = href
  },

  onSwitch: function() {
    trigger(window, "resize scroll")

    this.state.numPendingSwitches--

    // debounce calls, so we only run this once after all switches are finished.
    if (this.state.numPendingSwitches === 0) {
      this.afterAllSwitches()
    }
  },

  loadContent: function(html, options) {
    var tmpEl = document.implementation.createHTMLDocument("pjax")

    // parse HTML attributes to copy them
    // since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
    var htmlRegex = /<html[^>]+>/gi
    var htmlAttribsRegex = /\s?[a-z:]+(?:\=(?:\'|\")[^\'\">]+(?:\'|\"))*/gi
    var matches = html.match(htmlRegex)
    if (matches && matches.length) {
      matches = matches[0].match(htmlAttribsRegex)
      if (matches.length) {
        matches.shift()
        matches.forEach(function(htmlAttrib) {
          var attr = htmlAttrib.trim().split("=")
          if (attr.length === 1) {
            tmpEl.documentElement.setAttribute(attr[0], true)
          }
          else {
            tmpEl.documentElement.setAttribute(attr[0], attr[1].slice(1, -1))
          }
        })
      }
    }

    tmpEl.documentElement.innerHTML = html
    this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length)

    // Clear out any focused controls before inserting new page contents.
    // we clear focus on non form elements
    if (document.activeElement && !document.activeElement.value) {
      try {
        document.activeElement.blur()
      } catch (e) { }
    }

    // try {
    this.switchSelectors(this.options.selectors, tmpEl, document, options)

    // }
    // catch(e) {
    //   if (this.options.debug) {
    //     this.log("Pjax switch fail: ", e)
    //   }
    //   this.switchFallback(tmpEl, document)
    // }
  },

  abortRequest: require("./lib/abort-request.js"),

  doRequest: require("./lib/send-request.js"),

  loadUrl: function(href, options) {
    this.log("load href", href, options)

    // Abort any previous request
    this.abortRequest(this.request)

    trigger(document, "pjax:send", options);

    // Do the request
    options.requestOptions.timeout = this.options.timeout
    this.request = this.doRequest(href, options.requestOptions, function(html, request) {
      // Fail if unable to load HTML via AJAX
      if (html === false) {
        trigger(document,"pjax:complete pjax:error", options)

        return
      }

      // push scroll position to history
      var currentState = window.history.state || {}
      window.history.replaceState({
          url: currentState.url || window.location.href,
          title: currentState.title || document.title,
          uid: currentState.uid || newUid(),
          scrollPos: [document.documentElement.scrollLeft || document.body.scrollLeft,
            document.documentElement.scrollTop || document.body.scrollTop]
        },
        document.title, window.location)

      // Clear out any focused controls before inserting new page contents.
      document.activeElement.blur()

      var oldHref = href
      if (request.responseURL) {
        if (href !== request.responseURL) {
          href = request.responseURL
        }
      }
      else if (request.getResponseHeader("X-PJAX-URL")) {
        href = request.getResponseHeader("X-PJAX-URL")
      }
      else if (request.getResponseHeader("X-XHR-Redirected-To")) {
        href = request.getResponseHeader("X-XHR-Redirected-To")
      }

      // Add back the hash if it was removed
      var a = document.createElement("a")
      a.href = oldHref
      var oldHash = a.hash
      a.href = href
      if (oldHash && !a.hash) {
        a.hash = oldHash
        href = a.href
      }

      this.state.href = href
      this.state.options = clone(options)

      try {
        this.loadContent(html, options)
      }
      catch (e) {
        if (!this.options.debug) {
          if (console && console.error) {
            console.error("Pjax switch fail: ", e)
          }
          this.latestChance(href)
          return
        }
        else {
          throw e
        }
      }
    }.bind(this))
  },

  afterAllSwitches: function() {
    // FF bug: Won’t autofocus fields that are inserted via JS.
    // This behavior is incorrect. So if theres no current focus, autofocus
    // the last field.
    //
    // http://www.w3.org/html/wg/drafts/html/master/forms.html
    var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop()
    if (autofocusEl && document.activeElement !== autofocusEl) {
      autofocusEl.focus();
    }

    // execute scripts when DOM have been completely updated
    this.options.selectors.forEach(function(selector) {
      forEachEls(document.querySelectorAll(selector), function(el) {
        executeScripts(el)
      })
    })

    var state = this.state

    if (state.options.history) {
      if (!window.history.state) {
        this.lastUid = this.maxUid = newUid()
        window.history.replaceState({
            url: window.location.href,
            title: document.title,
            uid: this.maxUid,
            scrollPos: [0, 0]
          },
          document.title)
      }

      // Update browser history
      this.lastUid = this.maxUid = newUid()

      window.history.pushState({
          url: state.href,
          title: state.options.title,
          uid: this.maxUid,
          scrollPos: [0, 0]
        },
        state.options.title,
        state.href)
    }

    this.forEachSelectors(function(el) {
      this.parseDOM(el)
    }, this)

    // Fire Events
    trigger(document,"pjax:complete pjax:success", state.options)

    if (typeof state.options.analytics === "function") {
      state.options.analytics()
    }

    if (state.options.history) {
      // First parse url and check for hash to override scroll
      var a = document.createElement("a")
      a.href = this.state.href
      if (a.hash) {
        var name = a.hash.slice(1)
        name = decodeURIComponent(name)

        var curtop = 0
        var target = document.getElementById(name) || document.getElementsByName(name)[0]
        if (target) {
          // http://stackoverflow.com/questions/8111094/cross-browser-javascript-function-to-find-actual-position-of-an-element-in-page
          if (target.offsetParent) {
            do {
              curtop += target.offsetTop

              target = target.offsetParent
            } while (target)
          }
        }
        window.scrollTo(0, curtop);
      }
      else if (state.options.scrollTo !== false) {
        // Scroll page to top on new page load
        if (state.options.scrollTo.length > 1) {
          window.scrollTo(state.options.scrollTo[0], state.options.scrollTo[1])
        }
        else {
          window.scrollTo(0, state.options.scrollTo)
        }
      }
    }
    else if (state.options.scrollRestoration && state.options.scrollPos) {
      window.scrollTo(state.options.scrollPos[0], state.options.scrollPos[1])
    }

    this.state = {
      numPendingSwitches: 0,
      href: null,
      options: null
    }
  }
}

Pjax.isSupported = require("./lib/is-supported.js");

// arguably could do `if( require("./lib/is-supported.js")()) {` but that might be a little to simple
if (Pjax.isSupported()) {
  module.exports = Pjax
}
// if there isn’t required browser functions, returning stupid api
else {
  var stupidPjax = noop
  for (var key in Pjax.prototype) {
    if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") {
      stupidPjax[key] = noop
    }
  }

  module.exports = stupidPjax
}
<|endoftext|>


<commit_before>exports.default = {
  command: 'watch [servers..]',
  describe: 'watch mode',
  builder: yargs => yargs.options({
    port: { alias: 'p' },
    client: { alias: 'c', type: 'boolean' },
    bundle: { alias: 'b', type: 'boolean' }
  }),
  async handler (argv) {
    const servers = argv.servers.length ? argv.servers : ['app']
    const shelljs = require('shelljs')
    const { addonArgs } = require('../lib/helper')
    process.env.WATCH_MODE = true
    if (argv.client) {
      const args = addonArgs()
      servers.forEach(name => {
        shelljs.exec(`webpack-dev-server --config ./app/clients/${name}/webpack \
          -d --history-api-fallback --inline --progress \
          --host 0.0.0.0 ${args}`, {
            maxBuffer: 1024 * 1000
          })
      })
    } else {
      const commands = [`nodemon --harmony --watch app --ignore app/clients -L -e js,es,jsx ./app/index.js -- ${servers.join(' ')}`]
      const names = ['server']
      servers.forEach(name => {
        const server = require(`../servers/${name}`)
        if (server.clients) {
          server.clients.forEach(client => {
            names.push(`client:${client}`)
            commands.push(`"npm start watch ${client} -- -c"`)
          })
        }
      })
      console.log(commands[0])
      shelljs.exec(commands.length > 1
        ? `concurrently -p name -n "${names.join(',')}" ${commands.map(c => `"${c}"`).join(' ')}`
        : commands[0])
    }
  }
}
<commit_msg>improve<commit_after>exports.default = {
  command: 'watch [servers..]',
  describe: 'watch mode',
  builder: yargs => yargs.options({
    port: { alias: 'p' },
    client: { alias: 'c', type: 'boolean' },
    bundle: { alias: 'b', type: 'boolean' }
  }),
  async handler (argv) {
    const servers = argv.servers.length ? argv.servers : ['app']
    const shelljs = require('shelljs')
    const { addonArgs } = require('../lib/helper')
    process.env.WATCH_MODE = true
    if (argv.client) {
      const args = addonArgs()
      servers.forEach(name => {
        shelljs.exec(`webpack-dev-server --config ./app/clients/${name}/webpack \
          -d --history-api-fallback --inline --progress \
          --host 0.0.0.0 ${args}`, {
            maxBuffer: 1024 * 1000
          })
      })
    } else {
      const commands = [`nodemon --harmony --watch app --ignore app/clients -L -e js,es,jsx ./app/index.js -- ${servers.join(' ')}`]
      const names = ['server']
      servers.forEach(name => {
        const server = require(`../servers/${name}`)
        if (server.clients) {
          server.clients.forEach(client => {
            names.push(`client:${client}`)
            commands.push(`npm start watch ${client} -- -c`)
          })
        }
      })
      shelljs.exec(commands.length > 1
        ? `concurrently -p name -n "${names.join(',')}" ${commands.map(c => `"${c}"`).join(' ')}`
        : commands[0])
    }
  }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
  PixelRatio,
  StatusBar,
  Text,
  View,
  Platform
} from 'react-native';

import NavbarButton from './NavbarButton';
import styles from './styles';

const ButtonShape = {
  title: PropTypes.string.isRequired,
  style: PropTypes.any,
  handler: PropTypes.func,
};

const TitleShape = {
  title: PropTypes.string.isRequired,
  tintColor: PropTypes.string,
};

const StatusBarShape = {
  style: PropTypes.oneOf(['light-content', 'default', ]),
  hidden: PropTypes.bool,
  tintColor: PropTypes.string,
  animated: PropTypes.bool, // affects `style` and `hidden`
  hideAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ]),
  showAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ])
};

function customizeStatusBar(data) {
  if (Platform.OS === 'ios') {
    const animated = (data.animated || NavigationBar.defaultProps.statusBar.animated)
    if (data.style) {
      StatusBar.setBarStyle(data.style, animated);
    }
    if (data.hidden !== undefined) {
      let showHideTransition = 'none';
      if (animated) {
        showHideTransition = data.hidden ?
          (data.hideAnimation || NavigationBar.defaultProps.statusBar.hideAnimation) :
          (data.showAnimation || NavigationBar.defaultProps.statusBar.showAnimation);
      }
      StatusBar.setHidden(data.hidden, showHideTransition);
    }
  }
}

class NavigationBar extends Component {
  componentDidMount() {
    customizeStatusBar(this.props.statusBar);
  }

  componentWillReceiveProps(props) {
    customizeStatusBar(this.props.statusBar);
  }

  getButtonElement(data = {}, style) {
    return (
      <View style={styles.navBarButtonContainer}>
        {(!!data.props) ? data : (
          <NavbarButton
            title={data.title}
            style={[data.style, style, ]}
            tintColor={data.tintColor}
            handler={data.handler}/>
        )}
      </View>
    );
  }

  getTitleElement(data) {
    if (!!data.props) {
      return <View style={styles.customTitle}>{data}</View>;
    }

    const colorStyle = data.tintColor ? { color: data.tintColor, } : null;

    return (
      <View style={styles.navBarTitleContainer}>
        <Text
          style={[styles.navBarTitleText, colorStyle, ]}>
          {data.title}
        </Text>
      </View>
    );
  }

  render() {
    const customTintColor = this.props.tintColor ?
      { backgroundColor: this.props.tintColor } : null;

    const customStatusBarTintColor = this.props.statusBar.tintColor ?
      { backgroundColor: this.props.statusBar.tintColor } : null;

    let statusBar = null;

    if (Platform.OS === 'ios') {
      statusBar = !this.props.statusBar.hidden ?
        <View style={[styles.statusBar, customStatusBarTintColor ]} /> : null;
    }

    return (
      <View style={[styles.navBarContainer, customTintColor, ]}>
        {statusBar}
        <View style={[styles.navBar, this.props.style, ]}>
          {this.getTitleElement(this.props.title)}
          {this.getButtonElement(this.props.leftButton, { marginLeft: 8, })}
          {this.getButtonElement(this.props.rightButton, { marginRight: 8, })}
        </View>
      </View>
    );
  }

  static propTypes = {
    tintColor: PropTypes.string,
    statusBar: PropTypes.shape(StatusBarShape),
    leftButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    rightButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    title: PropTypes.oneOfType([
      PropTypes.shape(TitleShape),
      PropTypes.element,
    ]),
  };

  static defaultProps = {
    statusBar: {
      style: 'default',
      hidden: false,
      animated: false,
      hideAnimation: 'slide',
      showAnimation: 'slide',
    },
    title: {
      title: '',
    },
  };
}
module.exports = NavigationBar;
<commit_msg>Style change of status bar was lagging<commit_after>import React, { Component, PropTypes } from 'react';
import {
  PixelRatio,
  StatusBar,
  Text,
  View,
  Platform
} from 'react-native';

import NavbarButton from './NavbarButton';
import styles from './styles';

const ButtonShape = {
  title: PropTypes.string.isRequired,
  style: PropTypes.any,
  handler: PropTypes.func,
};

const TitleShape = {
  title: PropTypes.string.isRequired,
  tintColor: PropTypes.string,
};

const StatusBarShape = {
  style: PropTypes.oneOf(['light-content', 'default', ]),
  hidden: PropTypes.bool,
  tintColor: PropTypes.string,
  animated: PropTypes.bool, // affects `style` and `hidden`
  hideAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ]),
  showAnimation: PropTypes.oneOf(['fade', 'slide', 'none', ])
};

function customizeStatusBar(data) {
  if (Platform.OS === 'ios') {
    const animated = (data.animated || NavigationBar.defaultProps.statusBar.animated)
    if (data.style) {
      StatusBar.setBarStyle(data.style, animated);
    }
    if (data.hidden !== undefined) {
      let showHideTransition = 'none';
      if (animated) {
        showHideTransition = data.hidden ?
          (data.hideAnimation || NavigationBar.defaultProps.statusBar.hideAnimation) :
          (data.showAnimation || NavigationBar.defaultProps.statusBar.showAnimation);
      }
      StatusBar.setHidden(data.hidden, showHideTransition);
    }
  }
}

class NavigationBar extends Component {
  componentDidMount() {
    customizeStatusBar(this.props.statusBar);
  }

  componentWillReceiveProps(props) {
    customizeStatusBar(props.statusBar);
  }

  getButtonElement(data = {}, style) {
    return (
      <View style={styles.navBarButtonContainer}>
        {(!!data.props) ? data : (
          <NavbarButton
            title={data.title}
            style={[data.style, style, ]}
            tintColor={data.tintColor}
            handler={data.handler}/>
        )}
      </View>
    );
  }

  getTitleElement(data) {
    if (!!data.props) {
      return <View style={styles.customTitle}>{data}</View>;
    }

    const colorStyle = data.tintColor ? { color: data.tintColor, } : null;

    return (
      <View style={styles.navBarTitleContainer}>
        <Text
          style={[styles.navBarTitleText, colorStyle, ]}>
          {data.title}
        </Text>
      </View>
    );
  }

  render() {
    const customTintColor = this.props.tintColor ?
      { backgroundColor: this.props.tintColor } : null;

    const customStatusBarTintColor = this.props.statusBar.tintColor ?
      { backgroundColor: this.props.statusBar.tintColor } : null;

    let statusBar = null;

    if (Platform.OS === 'ios') {
      statusBar = !this.props.statusBar.hidden ?
        <View style={[styles.statusBar, customStatusBarTintColor ]} /> : null;
    }

    return (
      <View style={[styles.navBarContainer, customTintColor, ]}>
        {statusBar}
        <View style={[styles.navBar, this.props.style, ]}>
          {this.getTitleElement(this.props.title)}
          {this.getButtonElement(this.props.leftButton, { marginLeft: 8, })}
          {this.getButtonElement(this.props.rightButton, { marginRight: 8, })}
        </View>
      </View>
    );
  }

  static propTypes = {
    tintColor: PropTypes.string,
    statusBar: PropTypes.shape(StatusBarShape),
    leftButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    rightButton: PropTypes.oneOfType([
      PropTypes.shape(ButtonShape),
      PropTypes.element,
    ]),
    title: PropTypes.oneOfType([
      PropTypes.shape(TitleShape),
      PropTypes.element,
    ]),
  };

  static defaultProps = {
    statusBar: {
      style: 'default',
      hidden: false,
      animated: false,
      hideAnimation: 'slide',
      showAnimation: 'slide',
    },
    title: {
      title: '',
    },
  };
}
module.exports = NavigationBar;
<|endoftext|>


<commit_before>import React from 'react';
import { browserHistory } from 'react-router';
import { PageHeader } from 'react-bootstrap';
import axios from 'axios';
import querystring from 'querystring';
import job from '../models/jobModel'

class App extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      currentUser: {},
      searchResults: []
    }
  }

  componentDidMount () {
    // check for user - if there is one, they'll go to the react router user path
    if (this.state.currentUser._id) {
      const path = `/home/${this.state.currentUser._id}`;
      browserHistory.push(path);
    } else {
      // if no user, get it
      axios.get('http://localhost:3000/login')
        .then((res) => {
          this.setState({
            currentUser: res.data
          });
          const path = `/home/${this.state.currentUser._id}`;
          browserHistory.push(path);
        })
        .catch(err => {
          browserHistory.push('/login')
        });
    }
  }

  render() {
    return (

        <PageHeader bsClass="page-header hunt">Hunt</PageHeader>

          {this.renderChildrenWithProps()}

    )
  }

  //search for jobs via the 3P API calls
  searchForJobs(searchDetails) {

    // searchNewJobs returns a promise that resolves into an array of job objects
    job.searchNewJobs(searchDetails)
      .then(res => {
        this.setState({
          searchResults: res
        })
      })
  }

  //add job to interested
  //TODO: way to make one function that adds a job either to interested or to inProgress
  addJobToInterested(jobData) {
    let description = jobData.description.substr(0,700) + '...';
    axios.post(`http://localhost:3000/users/${this.state.currentUser._id}/jobs?q=interested`, querystring.stringify({
          api: jobData.api,
          apiSpecificId: jobData.apiSpecificId,
          title: jobData.title,
          company: jobData.company,
          location: jobData.location,
          link: jobData.link,
          description: description
      })
    )
    .then(res => {
      let userId = this.state.currentUser._id
      let updateUser = Object.assign({}, this.state.currentUser);
      //assuming these return the entire array
      updateUser.interested = res.data.interested;
      updateUser.jobContent = res.data.jobContent;
      axios.get(`http://localhost:3000/users/${userId}`)
        .then(res => {
          this.setState({
            currentUser: updateUser
          })
        })
    })
  }

  //add a job to inProgress
  addJobToInProgress(jobData) {
    //jobData comes from the props of the JobListItem
    axios.put(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${jobData.jobId}/inProgress`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser.interested = res.data.interested;
      updateUser.inProgress = res.data.inProgress;
      updateUser.complete = res.data.complete;
      this.setState({
        currentUser: updateUser
      })
    })
  }

  //add a job to complete
  addJobToComplete(jobData) {
    //jobData comes from the props of the JobListItem
    axios.put(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${jobData.jobId}/complete`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser.interested = res.data.interested;
      updateUser.inProgress = res.data.inProgress;
      updateUser.complete = res.data.complete;
      this.setState({
        currentUser: updateUser
      })
    })
  }

  //remove a job from any list
  removeJob(jobData) {
    let list = jobData.currentList;
    axios.delete(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${jobData.jobId}/${jobData.currentList}`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser[list] = res.data[list];
      this.setState({
        currentUser: updateUser
      })
    })
  }

  //TODO: do we need this?
  updateUserEnteredJob(jobData) {
    axios.put(`http://localhost:3000/jobs/${jobData._id}`)
  }

  //update job content
  updateJobContent(content) {
    axios.put(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${content.job_id}/content`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser.jobContent = res.data.jobContent;
      this.setState({
        currentUser: updateUser
      })
    })
  }

  renderChildrenWithProps () {
    // add props to all the children of app
    return React.Children.map(this.props.children, (child) => {
      switch (child.type.name) {
        case "Home" :
          // home needs . . .
          return React.cloneElement(child, {
            userName: this.state.currentUser.name,
            //in case we want the google pic
            userPhoto: this.state.currentUser.image,
            //potentially for search result stuff
            interested: this.state.currentUser.interested,
            searchForJobs: this.searchForJobs.bind(this),
            addJobToInterested: this.addJobToInterested.bind(this),
            searchResults: this.state.searchResults
          });
          break;
        case "Dashboard" :
          // dashboard needs . . .
          return React.cloneElement(child, {
            //duh
            interested: this.state.currentUser.interested,
            inProgress: this.state.currentUser.inProgress,
            complete: this.state.currentUser.complete,
            jobContent: this.state.currentUser.jobContent,
            addJobToInterested: this.addJobToInterested.bind(this),
            addJobToInProgress: this.addJobToInProgress.bind(this),
            addJobToComplete: this.addJobToComplete.bind(this),
            removeJob: this.removeJob.bind(this)
          });
          break;
        case "EditProfile" :
          // editprofile needs . . .
          return React.cloneElement(child, {
            currentUser: this.state.currentUser,
          });
          break;
        case "Connect" :
          // connect needs . . .
          return React.cloneElement(child, {
            userName: this.state.currentUser.name,
            userEmail: this.state.currentUser.email,
            userTech: this.state.currentUser.tech || '',
            userLocation: this.state.currentUser.location || '',
          });
          break;
        default :
          return child;
      }
    });
  }

}

module.exports = App;
<commit_msg>fixes error where adding a job did not correctly update the App state with the new info<commit_after>import React from 'react';
import { browserHistory } from 'react-router';
import { PageHeader } from 'react-bootstrap';
import axios from 'axios';
import querystring from 'querystring';
import job from '../models/jobModel'

class App extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      currentUser: {},
      searchResults: []
    }
  }

  componentDidMount () {
    // check for user - if there is one, they'll go to the react router user path
    if (this.state.currentUser._id) {
      const path = `/home/${this.state.currentUser._id}`;
      browserHistory.push(path);
    } else {
      // if no user, get it
      axios.get('http://localhost:3000/login')
        .then((res) => {
          this.setState({
            currentUser: res.data
          });
          const path = `/home/${this.state.currentUser._id}`;
          browserHistory.push(path);
        })
        .catch(err => {
          browserHistory.push('/login')
        });
    }
  }

  render() {
    return (

        <PageHeader bsClass="page-header hunt">Hunt</PageHeader>

          {this.renderChildrenWithProps()}

    )
  }

  //search for jobs via the 3P API calls
  searchForJobs(searchDetails) {

    // searchNewJobs returns a promise that resolves into an array of job objects
    job.searchNewJobs(searchDetails)
      .then(res => {
        this.setState({
          searchResults: res
        })
      })
  }

  //add job to interested
  //TODO: way to make one function that adds a job either to interested or to inProgress
  addJobToInterested(jobData) {
    // let description = jobData.description.substr(0,700) + '...';
    axios.post(`http://localhost:3000/users/${this.state.currentUser._id}/jobs?q=interested`, querystring.stringify({
          api: jobData.api,
          apiSpecificId: jobData.apiSpecificId,
          title: jobData.title,
          company: jobData.company,
          location: jobData.location,
          link: jobData.link,
          description: jobData.description
      })
    )
    .then(res => {
      let userId = this.state.currentUser._id
      axios.get(`http://localhost:3000/users/${userId}`)
        .then(res => {
          let updateUser = Object.assign({}, this.state.currentUser);
          //assuming these return the entire array
          updateUser.interested = res.data.interested;
          updateUser.jobContent = res.data.jobContent;
          console.log('update user:', updateUser)
          this.setState({
            currentUser: updateUser
          })
        })
    })
  }

  //add a job to inProgress
  addJobToInProgress(jobData) {
    //jobData comes from the props of the JobListItem
    axios.put(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${jobData.jobId}/inProgress`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser.interested = res.data.interested;
      updateUser.inProgress = res.data.inProgress;
      updateUser.complete = res.data.complete;
      this.setState({
        currentUser: updateUser
      })
    })
  }

  //add a job to complete
  addJobToComplete(jobData) {
    //jobData comes from the props of the JobListItem
    axios.put(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${jobData.jobId}/complete`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser.interested = res.data.interested;
      updateUser.inProgress = res.data.inProgress;
      updateUser.complete = res.data.complete;
      this.setState({
        currentUser: updateUser
      })
    })
  }

  //remove a job from any list
  removeJob(jobData) {
    let list = jobData.currentList;
    axios.delete(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${jobData.jobId}/${jobData.currentList}`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser[list] = res.data[list];
      this.setState({
        currentUser: updateUser
      })
    })
  }

  //TODO: do we need this?
  updateUserEnteredJob(jobData) {
    axios.put(`http://localhost:3000/jobs/${jobData._id}`)
  }

  //update job content
  updateJobContent(content) {
    axios.put(`http://localhost:3000/users/${this.state.currentUser._id}/jobs/${content.job_id}/content`)
    .then(res => {
      let updateUser = Object.assign({}, this.state.currentUser);
      updateUser.jobContent = res.data.jobContent;
      this.setState({
        currentUser: updateUser
      })
    })
  }

  renderChildrenWithProps () {
    // add props to all the children of app
    return React.Children.map(this.props.children, (child) => {
      switch (child.type.name) {
        case "Home" :
          // home needs . . .
          return React.cloneElement(child, {
            userName: this.state.currentUser.name,
            //in case we want the google pic
            userPhoto: this.state.currentUser.image,
            //potentially for search result stuff
            interested: this.state.currentUser.interested,
            searchForJobs: this.searchForJobs.bind(this),
            addJobToInterested: this.addJobToInterested.bind(this),
            searchResults: this.state.searchResults
          });
          break;
        case "Dashboard" :
          // dashboard needs . . .
          return React.cloneElement(child, {
            //duh
            interested: this.state.currentUser.interested,
            inProgress: this.state.currentUser.inProgress,
            complete: this.state.currentUser.complete,
            jobContent: this.state.currentUser.jobContent,
            addJobToInterested: this.addJobToInterested.bind(this),
            addJobToInProgress: this.addJobToInProgress.bind(this),
            addJobToComplete: this.addJobToComplete.bind(this),
            removeJob: this.removeJob.bind(this)
          });
          break;
        case "EditProfile" :
          // editprofile needs . . .
          return React.cloneElement(child, {
            currentUser: this.state.currentUser,
          });
          break;
        case "Connect" :
          // connect needs . . .
          return React.cloneElement(child, {
            userName: this.state.currentUser.name,
            userEmail: this.state.currentUser.email,
            userTech: this.state.currentUser.tech || '',
            userLocation: this.state.currentUser.location || '',
          });
          break;
        default :
          return child;
      }
    });
  }

}

module.exports = App;
<|endoftext|>


<commit_before>/*!
 * keygrip
 * Copyright(c) 2011-2014 Jed Schmidt
 * MIT Licensed
 */

var crypto = require("crypto")

function Keygrip(keys, algorithm, encoding) {
  if (!algorithm) algorithm = "sha1";
  if (!encoding) encoding = "base64";
  if (!(this instanceof Keygrip)) return new Keygrip(keys, algorithm, encoding)

  if (!keys || !(0 in keys)) {
    throw new Error("Keys must be provided.")
  }

  function sign(data, key) {
    return crypto
      .createHmac(algorithm, key)
      .update(data).digest(encoding)
      .replace(/\/|\+|=/g, function(x) {
        return ({ "/": "_", "+": "-", "=": "" })[x]
      })
  }

  this.sign = function(data){ return sign(data, keys[0]) }

  this.verify = function(data, digest) {
    return this.index(data, digest) > -1
  }

  this.index = function(data, digest) {
    for (var i = 0, l = keys.length; i < l; i++) {
      if (constantTimeCompare(digest, sign(data, keys[i]))) return i
    }

    return -1
  }
}

Keygrip.sign = Keygrip.verify = Keygrip.index = function() {
  throw new Error("Usage: require('keygrip')(<array-of-keys>)")
}

//http://codahale.com/a-lesson-in-timing-attacks/
var constantTimeCompare = function(val1, val2){
    if(val1 == null && val2 != null){
        return false;
    } else if(val2 == null && val1 != null){
        return false;
    } else if(val1 == null && val2 == null){
        return true;
    }

    if(val1.length !== val2.length){
        return false;
    }

    var matches = 1;

    for(var i = 0; i < val1.length; i++){
        matches &= (val1.charAt(i) === val2.charAt(i) ? 1 : 0); //Don't short circuit
    }

    return matches === 1;
};

module.exports = Keygrip
<commit_msg>perf: improve comparison speed<commit_after>/*!
 * keygrip
 * Copyright(c) 2011-2014 Jed Schmidt
 * MIT Licensed
 */

var crypto = require("crypto")

function Keygrip(keys, algorithm, encoding) {
  if (!algorithm) algorithm = "sha1";
  if (!encoding) encoding = "base64";
  if (!(this instanceof Keygrip)) return new Keygrip(keys, algorithm, encoding)

  if (!keys || !(0 in keys)) {
    throw new Error("Keys must be provided.")
  }

  function sign(data, key) {
    return crypto
      .createHmac(algorithm, key)
      .update(data).digest(encoding)
      .replace(/\/|\+|=/g, function(x) {
        return ({ "/": "_", "+": "-", "=": "" })[x]
      })
  }

  this.sign = function(data){ return sign(data, keys[0]) }

  this.verify = function(data, digest) {
    return this.index(data, digest) > -1
  }

  this.index = function(data, digest) {
    for (var i = 0, l = keys.length; i < l; i++) {
      if (constantTimeCompare(digest, sign(data, keys[i]))) return i
    }

    return -1
  }
}

Keygrip.sign = Keygrip.verify = Keygrip.index = function() {
  throw new Error("Usage: require('keygrip')(<array-of-keys>)")
}

//http://codahale.com/a-lesson-in-timing-attacks/
var constantTimeCompare = function(val1, val2){
    if(val1 == null && val2 != null){
        return false;
    } else if(val2 == null && val1 != null){
        return false;
    } else if(val1 == null && val2 == null){
        return true;
    }

    if(val1.length !== val2.length){
        return false;
    }

    var result = 0;

    for(var i = 0; i < val1.length; i++){
        result |= val1.charCodeAt(i) ^ val2.charCodeAt(i); //Don't short circuit
    }

    return result === 0;
};

module.exports = Keygrip
<|endoftext|>


<commit_before>'use strict'

const Trailpack = require('trailpack')
const _ = require('lodash')

module.exports = class CronTrailpack extends Trailpack {

  configure() {
    const configAnnotations = this.app.config.annotations
    if (configAnnotations) {
      if (!configAnnotations.customAnnotations) {
        configAnnotations.customAnnotations = {}
      }
      else {
        configAnnotations.customAnnotations = _.extend(configAnnotations.customAnnotations, require('./annotations'))
      }

    }
  }

  /**
   * Wait Trails ready event to launch jobs
   */
  initialize() {
    this.app.on('trails:ready', () => {
      this.app.services.CronService.init()
    })
    return Promise.resolve()
  }

  constructor(app) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }
}

<commit_msg>Add Cron annotations<commit_after>'use strict'

const Trailpack = require('trailpack')
const _ = require('lodash')

module.exports = class CronTrailpack extends Trailpack {

  configure() {
    const configAnnotations = this.app.config.annotations
    if (configAnnotations) {
      if (!configAnnotations.customAnnotations) {
        configAnnotations.customAnnotations = {}
      }

      configAnnotations.customAnnotations = _.extend(configAnnotations.customAnnotations, require('./annotations'))

    }
  }

  /**
   * Wait Trails ready event to launch jobs
   */
  initialize() {
    this.app.on('trails:ready', () => {
      this.app.services.CronService.init()
    })
    return Promise.resolve()
  }

  constructor(app) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }
}

<|endoftext|>


<commit_before>'use strict';

angular.module('baikalApp.controllers', ['ngRoute'])

.controller('HeaderCtrl', ['$scope', '$translate', '$routeParams', function($scope, $translate, $routeParams) {
	if ($translate.use() == 'ru') {
    	$scope.other_lang = 'en';
    } else {
    	$scope.other_lang = 'ru';
    }
	$scope.languageChange = function () {
	    $translate.use($scope.other_lang);
	    if ($scope.other_lang == 'ru') {
	    	$scope.other_lang = 'en';
	    } else {
	    	$scope.other_lang = 'ru';
	    }
	};
}])

.controller('MusicCtrl', ['$scope', 'Music', function($scope, Music) {
	$scope.music = Music;
	$scope.music_state = Music.state;
	$scope.music_current = Music.current;
	$scope.$watchCollection(function() { return [Music.state, Music.current]; }, function (newVal, oldVal) {
		if(newVal) {
			$scope.music_state = newVal[0];
			$scope.music_current = newVal[1];
		}
	});
	$scope.logState = function() {
		console.log(Music.state);
		Music.state = "test";
	}
}])

.controller('PostlistCtrl', ['$scope', '$routeParams', '$translate', 'Post', 'Category', function($scope, $routeParams, $translate, Post, Category) {
	$scope.categories = Category.get(function(categories) {
		$scope.category = categories[$routeParams.category+'_'+$translate.use()];
	});
	Post.query({pid: $routeParams.category, cid: $routeParams.category}, function(posts) {
		for (var i = posts.length - 1; i >= 0; i--) {
			if (!posts[i].link) {
				posts[i].link = "#/post/"+$routeParams.category+"/"+posts[i].id;
			}
		};
		$scope.posts = posts;
	});
}])

.controller('PostviewCtrl', ['$scope', '$routeParams', 'Post', function($scope, $routeParams, Post) {
	$scope.post = Post.get({pid: $routeParams.pid, cid: $routeParams.cid});
}])

.controller('ContactsCtrl', ['$scope', 'Post', '$translate', function($scope, Post, $translate) {

}])

.controller('LeagueCtrl', ['$scope', 'Post', function($scope, Post) {
  $scope.post = Post.get({pid: "league", cid: "league"});
}])

.controller('RecordsCtrl', ['$scope', '$routeParams', 'Media', function($scope, $routeParams, Media) {
	$scope.medias = Media.query({pid: "records"});
	$scope.title = "RECORDS";
}])

.controller('VolunteersCtrl', ['$scope', 'Post', function($scope, Post) {
  $scope.post = Post.get({pid: "volunteers", cid: "volunteers"});
}]);<commit_msg>music<commit_after>'use strict';

angular.module('baikalApp.controllers', ['ngRoute'])

.controller('HeaderCtrl', ['$scope', '$translate', '$routeParams', function($scope, $translate, $routeParams) {
	if ($translate.use() == 'ru') {
    	$scope.other_lang = 'en';
    } else {
    	$scope.other_lang = 'ru';
    }
	$scope.languageChange = function () {
	    $translate.use($scope.other_lang);
	    if ($scope.other_lang == 'ru') {
	    	$scope.other_lang = 'en';
	    } else {
	    	$scope.other_lang = 'ru';
	    }
	};
}])

.controller('MusicCtrl', ['$scope', 'Music', function($scope, Music) {
	$scope.music = Music;
	$scope.music_state = Music.state;
	$scope.music_current = Music.current;
	$scope.$watchCollection(function() { return [Music.state, Music.current]; }, function (newVal, oldVal) {
		console.log(newVal);
		if(newVal) {
			$scope.music_state = newVal[0];
			$scope.music_current = newVal[1];
		}
	});
	$scope.logState = function() {
		console.log(Music.state);
		Music.state = "test";
	}
}])

.controller('PostlistCtrl', ['$scope', '$routeParams', '$translate', 'Post', 'Category', function($scope, $routeParams, $translate, Post, Category) {
	$scope.categories = Category.get(function(categories) {
		$scope.category = categories[$routeParams.category+'_'+$translate.use()];
	});
	Post.query({pid: $routeParams.category, cid: $routeParams.category}, function(posts) {
		for (var i = posts.length - 1; i >= 0; i--) {
			if (!posts[i].link) {
				posts[i].link = "#/post/"+$routeParams.category+"/"+posts[i].id;
			}
		};
		$scope.posts = posts;
	});
}])

.controller('PostviewCtrl', ['$scope', '$routeParams', 'Post', function($scope, $routeParams, Post) {
	$scope.post = Post.get({pid: $routeParams.pid, cid: $routeParams.cid});
}])

.controller('ContactsCtrl', ['$scope', 'Post', '$translate', function($scope, Post, $translate) {

}])

.controller('LeagueCtrl', ['$scope', 'Post', function($scope, Post) {
  $scope.post = Post.get({pid: "league", cid: "league"});
}])

.controller('RecordsCtrl', ['$scope', '$routeParams', 'Media', function($scope, $routeParams, Media) {
	$scope.medias = Media.query({pid: "records"});
	$scope.title = "RECORDS";
}])

.controller('VolunteersCtrl', ['$scope', 'Post', function($scope, Post) {
  $scope.post = Post.get({pid: "volunteers", cid: "volunteers"});
}]);<|endoftext|>


<commit_before>var Blocks = require('aligned-block-file')
var createFrame = require('./frame/recoverable')
var Cache = require('hashlru')
var inject = require('./inject')
function id (e) { return e }
function isNumber(n) { return 'number' == typeof n && !isNaN(n) }

module.exports = function (file, opts) {
  if (!opts) opts = {}
  //file, blocks, frame, codec
  if (typeof opts !== 'object')
    opts = legacy.apply(null, arguments)

  var blockSize = opts.blockSize || 1024*16
  var codec = opts.codec || {encode: id, decode: id}
  var flags = opts.flags || 'a+'
  var cache = opts.cache || Cache(1024)
  var offsetCodec = opts.offsetCodec || 32

  var blocks = Blocks(file, blockSize, flags, cache)
  var frame = createFrame(blocks, blockSize, offsetCodec)
  return inject(blocks, frame, codec, file)
}

var warned = false
var msg = 'flumelog-offset: blockSize and codec params moved into an object. https://github.com/flumedb/flumelog-offset'
function legacy (file, blockSize, codec) {
  console.log(arguments)
  if (!warned) warned = true, console.warn(msg)
  if (!isNumber(blockSize)) codec = blockSize, blockSize = undefined
  return {blockSize: blockSize, codec: codec}
}

<commit_msg>remove logging<commit_after>var Blocks = require('aligned-block-file')
var createFrame = require('./frame/recoverable')
var Cache = require('hashlru')
var inject = require('./inject')
function id (e) { return e }
function isNumber(n) { return 'number' == typeof n && !isNaN(n) }

module.exports = function (file, opts) {
  if (!opts) opts = {}
  //file, blocks, frame, codec
  if (typeof opts !== 'object')
    opts = legacy.apply(null, arguments)

  var blockSize = opts.blockSize || 1024*16
  var codec = opts.codec || {encode: id, decode: id}
  var flags = opts.flags || 'a+'
  var cache = opts.cache || Cache(1024)
  var offsetCodec = opts.offsetCodec || 32

  var blocks = Blocks(file, blockSize, flags, cache)
  var frame = createFrame(blocks, blockSize, offsetCodec)
  return inject(blocks, frame, codec, file)
}

var warned = false
var msg = 'flumelog-offset: blockSize and codec params moved into an object. https://github.com/flumedb/flumelog-offset'
function legacy (file, blockSize, codec) {
  if (!warned) warned = true, console.warn(msg)
  if (!isNumber(blockSize)) codec = blockSize, blockSize = undefined
  return {blockSize: blockSize, codec: codec}
}

<|endoftext|>


<commit_before>'use strict';

var Just = require('just');
var Promise = require('promise');

exports.name = 'just';
exports.inputFormats = ['just'];
exports.outputFormat = 'html';

exports.renderAsync = function (str, options, locals) {
  // Prepare the options array.
  options = options || {};
  options['root'] = { page: str };

  // Construct the template.
  var template = new Just(options);

  // Build the Promise to render the template.
  var promise = new Promise(function (resolve, reject) {
    template.render('page', locals, function (err, output) {
      if (err) {
        reject(err);
      }
      else {
        resolve(output);
      }
    });
  });

  return promise;
};
<commit_msg>cleanup, no need of use `else`<commit_after>'use strict';

var Just = require('just');
var Promise = require('promise');

exports.name = 'just';
exports.inputFormats = ['just'];
exports.outputFormat = 'html';

exports.renderAsync = function (str, options, locals) {
  // Prepare the options array.
  options = options || {};
  options['root'] = { page: str };

  // Construct the template.
  var template = new Just(options);

  // Build the Promise to render the template.
  return new Promise(function (resolve, reject) {
    template.render('page', locals, function (err, output) {
      if (err) {
        return reject(err);
      }
      resolve(output);
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var phonecatControllers = angular.module('phonecatControllers', []);

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
  function($scope, Phone) {
    $scope.phones = Phone.query();
    $scope.orderProp = 'age';
  }]);

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
  function($scope, $routeParams, Phone) {
    $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
      $scope.mainImageUrl = phone.images[0];
    });

    $scope.setImage = function(imageUrl) {
      $scope.mainImageUrl = imageUrl;
    }

     $scope.master = {};

    $scope.update = function(user) {
      $scope.master = angular.copy(user);
      console.log("hi it saved, I think");
      console.log($scope.master);
    };

    $scope.reset = function() {
       $scope.user = angular.copy($scope.master);
    };

    $scope.reset();
  }]);

//var formController = angular.module('form', []);

// phonecatControllers.controller('formController', ['$scope',
//   function($scope) {
//     $scope.master = {};

//     $scope.update = function(user) {
//       $scope.master = angular.copy(user);
//     };

//     $scope.reset = function() {
//        $scope.user = angular.copy($scope.master);
//     };

//     $scope.reset();
//   }]);

// <script>
//   angular.module('formExample', [])
//     .controller('ExampleController', ['$scope', function($scope) {
//       $scope.master = {};

//       $scope.update = function(user) {
//         $scope.master = angular.copy(user);
//       };

//       $scope.reset = function() {
//         $scope.user = angular.copy($scope.master);
//       };

//       $scope.reset();
//     }]);
// </script>
<commit_msg>Contacts is now stored when you go back to the page<commit_after>'use strict';

/* Controllers */

var phonecatControllers = angular.module('phonecatControllers', []);

phonecatControllers.controller('PhoneListCtrl', ['$scope', 'Phone',
  function($scope, Phone) {
    $scope.phones = Phone.query();
    $scope.orderProp = 'age';
  }]);

var globallyStored = {};

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', 'Phone',
  function($scope, $routeParams, Phone) {
    $scope.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone) {
      $scope.mainImageUrl = phone.images[0];
      globallyStored[$routeParams.phoneId] = globallyStored[$routeParams.phoneId] || phone;
      $scope.user = globallyStored[$routeParams.phoneId].user;
    });

    $scope.setImage = function(imageUrl) {
      $scope.mainImageUrl = imageUrl;
    }

     $scope.master = {};

    $scope.update = function(user) {
      // $scope.master = angular.copy(user);
      globallyStored[$routeParams.phoneId].user = angular.copy(user);
      // console.log($scope.master);
    };

    $scope.reset = function() {
       $scope.user = angular.copy($scope.master);
    };

    $scope.reset();
  }]);

//var formController = angular.module('form', []);

// phonecatControllers.controller('formController', ['$scope',
//   function($scope) {
//     $scope.master = {};

//     $scope.update = function(user) {
//       $scope.master = angular.copy(user);
//     };

//     $scope.reset = function() {
//        $scope.user = angular.copy($scope.master);
//     };

//     $scope.reset();
//   }]);

// <script>
//   angular.module('formExample', [])
//     .controller('ExampleController', ['$scope', function($scope) {
//       $scope.master = {};

//       $scope.update = function(user) {
//         $scope.master = angular.copy(user);
//       };

//       $scope.reset = function() {
//         $scope.user = angular.copy($scope.master);
//       };

//       $scope.reset();
//     }]);
// </script>
<|endoftext|>