code stringlengths 2 1.05M |
|---|
/**
@license
* @pnp/sp v1.0.5-0 - pnp - provides a fluent api for working with SharePoint REST
* MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE)
* Copyright (c) 2018 Microsoft
* docs: https://pnp.github.io/pnpjs/
* source: https:github.com/pnp/pnpjs
* bugs: https://github.com/pnp/pnpjs/issues
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tslib'), require('@pnp/logging'), require('@pnp/common'), require('@pnp/odata')) :
typeof define === 'function' && define.amd ? define(['exports', 'tslib', '@pnp/logging', '@pnp/common', '@pnp/odata'], factory) :
(factory((global.pnp = global.pnp || {}, global.pnp.sp = {}),global.tslib_1,global.pnp.logging,global.pnp.common,global.pnp.odata));
}(this, (function (exports,tslib_1,logging,common,odata) { 'use strict';
function extractWebUrl(candidateUrl) {
if (candidateUrl === null) {
return "";
}
var index = candidateUrl.indexOf("_api/");
if (index > -1) {
return candidateUrl.substr(0, index);
}
// if all else fails just give them what they gave us back
return candidateUrl;
}
var SPBatchParseException = /** @class */ (function (_super) {
tslib_1.__extends(SPBatchParseException, _super);
function SPBatchParseException(msg) {
var _this = _super.call(this, msg) || this;
_this.name = "BatchParseException";
logging.Logger.error(_this);
return _this;
}
return SPBatchParseException;
}(Error));
var SPODataIdException = /** @class */ (function (_super) {
tslib_1.__extends(SPODataIdException, _super);
function SPODataIdException(data, msg) {
if (msg === void 0) { msg = "Could not extract odata id in object, you may be using nometadata. Object data logged to logger."; }
var _this = _super.call(this, msg) || this;
_this.data = data;
_this.name = "ODataIdException";
logging.Logger.error(_this);
return _this;
}
return SPODataIdException;
}(Error));
var MaxCommentLengthException = /** @class */ (function (_super) {
tslib_1.__extends(MaxCommentLengthException, _super);
function MaxCommentLengthException(msg) {
if (msg === void 0) { msg = "The maximum comment length is 1023 characters."; }
var _this = _super.call(this, msg) || this;
_this.name = "MaxCommentLengthException";
logging.Logger.error(_this);
return _this;
}
return MaxCommentLengthException;
}(Error));
var NotSupportedInBatchException = /** @class */ (function (_super) {
tslib_1.__extends(NotSupportedInBatchException, _super);
function NotSupportedInBatchException(operation) {
if (operation === void 0) { operation = "This operation"; }
var _this = _super.call(this, operation + " is not supported as part of a batch.") || this;
_this.name = "NotSupportedInBatchException";
logging.Logger.error(_this);
return _this;
}
return NotSupportedInBatchException;
}(Error));
var APIUrlException = /** @class */ (function (_super) {
tslib_1.__extends(APIUrlException, _super);
function APIUrlException(msg) {
if (msg === void 0) { msg = "Unable to determine API url."; }
var _this = _super.call(this, msg) || this;
_this.name = "APIUrlException";
logging.Logger.error(_this);
return _this;
}
return APIUrlException;
}(Error));
function spExtractODataId(candidate) {
if (candidate.hasOwnProperty("odata.id")) {
return candidate["odata.id"];
}
else if (candidate.hasOwnProperty("__metadata") && candidate.__metadata.hasOwnProperty("id")) {
return candidate.__metadata.id;
}
else {
throw new SPODataIdException(candidate);
}
}
var SPODataEntityParserImpl = /** @class */ (function (_super) {
tslib_1.__extends(SPODataEntityParserImpl, _super);
function SPODataEntityParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.hydrate = function (d) {
var o = new _this.factory(spGetEntityUrl(d), null);
return common.extend(o, d);
};
return _this;
}
SPODataEntityParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
var o = new _this.factory(spGetEntityUrl(d), null);
return common.extend(o, d);
});
};
return SPODataEntityParserImpl;
}(odata.ODataParserBase));
var SPODataEntityArrayParserImpl = /** @class */ (function (_super) {
tslib_1.__extends(SPODataEntityArrayParserImpl, _super);
function SPODataEntityArrayParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
_this.hydrate = function (d) {
return d.map(function (v) {
var o = new _this.factory(spGetEntityUrl(v), null);
return common.extend(o, v);
});
};
return _this;
}
SPODataEntityArrayParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
return d.map(function (v) {
var o = new _this.factory(spGetEntityUrl(v), null);
return common.extend(o, v);
});
});
};
return SPODataEntityArrayParserImpl;
}(odata.ODataParserBase));
function spGetEntityUrl(entity) {
if (entity.hasOwnProperty("odata.metadata") && entity.hasOwnProperty("odata.editLink")) {
// we are dealign with minimal metadata (default)
return common.combinePaths(extractWebUrl(entity["odata.metadata"]), "_api", entity["odata.editLink"]);
}
else if (entity.hasOwnProperty("__metadata")) {
// we are dealing with verbose, which has an absolute uri
return entity.__metadata.uri;
}
else {
// we are likely dealing with nometadata, so don't error but we won't be able to
// chain off these objects
logging.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", 2 /* Warning */);
return "";
}
}
function spODataEntity(factory) {
return new SPODataEntityParserImpl(factory);
}
function spODataEntityArray(factory) {
return new SPODataEntityArrayParserImpl(factory);
}
function setup(config) {
common.RuntimeConfig.extend(config);
}
var SPRuntimeConfigImpl = /** @class */ (function () {
function SPRuntimeConfigImpl() {
}
Object.defineProperty(SPRuntimeConfigImpl.prototype, "headers", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== null && typeof spPart !== "undefined" && typeof spPart.headers !== "undefined") {
return spPart.headers;
}
return {};
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRuntimeConfigImpl.prototype, "baseUrl", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
if (spPart !== null && typeof spPart.baseUrl !== "undefined") {
return spPart.baseUrl;
}
if (common.RuntimeConfig.spfxContext !== null) {
return common.RuntimeConfig.spfxContext.pageContext.web.absoluteUrl;
}
return null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRuntimeConfigImpl.prototype, "fetchClientFactory", {
get: function () {
var spPart = common.RuntimeConfig.get("sp");
// use a configured factory firt
if (spPart !== null && typeof spPart.fetchClientFactory !== "undefined") {
return spPart.fetchClientFactory;
}
else {
return function () { return new common.FetchClient(); };
}
},
enumerable: true,
configurable: true
});
return SPRuntimeConfigImpl;
}());
var SPRuntimeConfig = new SPRuntimeConfigImpl();
var CachedDigest = /** @class */ (function () {
function CachedDigest() {
}
return CachedDigest;
}());
// allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper.
var digests = new common.Dictionary();
var DigestCache = /** @class */ (function () {
function DigestCache(_httpClient, _digests) {
if (_digests === void 0) { _digests = digests; }
this._httpClient = _httpClient;
this._digests = _digests;
}
DigestCache.prototype.getDigest = function (webUrl) {
var _this = this;
var cachedDigest = this._digests.get(webUrl);
if (cachedDigest !== null) {
var now = new Date();
if (now < cachedDigest.expiration) {
return Promise.resolve(cachedDigest.value);
}
}
var url = common.combinePaths(webUrl, "/_api/contextinfo");
var headers = {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose;charset=utf-8",
};
return this._httpClient.fetchRaw(url, {
cache: "no-cache",
credentials: "same-origin",
headers: common.extend(headers, SPRuntimeConfig.headers, true),
method: "POST",
}).then(function (response) {
var parser = new odata.ODataDefaultParser();
return parser.parse(response).then(function (d) { return d.GetContextWebInformation; });
}).then(function (data) {
var newCachedDigest = new CachedDigest();
newCachedDigest.value = data.FormDigestValue;
var seconds = data.FormDigestTimeoutSeconds;
var expiration = new Date();
expiration.setTime(expiration.getTime() + 1000 * seconds);
newCachedDigest.expiration = expiration;
_this._digests.add(webUrl, newCachedDigest);
return newCachedDigest.value;
});
};
DigestCache.prototype.clear = function () {
this._digests.clear();
};
return DigestCache;
}());
var SPHttpClient = /** @class */ (function () {
function SPHttpClient() {
this._impl = SPRuntimeConfig.fetchClientFactory();
this._digestCache = new DigestCache(this);
}
SPHttpClient.prototype.fetch = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
var opts = common.extend(options, { cache: "no-cache", credentials: "same-origin" }, true);
var headers = new Headers();
// first we add the global headers so they can be overwritten by any passed in locally to this call
common.mergeHeaders(headers, SPRuntimeConfig.headers);
// second we add the local options so we can overwrite the globals
common.mergeHeaders(headers, options.headers);
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:@pnp-$$Version$$");
}
if (!headers.has("User-Agent")) {
// this marks the requests for understanding by the service
headers.append("User-Agent", "NONISV|SharePointPnP|PnPCoreJS/$$Version$$");
}
opts = common.extend(opts, { headers: headers });
if (opts.method && opts.method.toUpperCase() !== "GET") {
// if we have either a request digest or an authorization header we don't need a digest
if (!headers.has("X-RequestDigest") && !headers.has("Authorization")) {
var index = url.indexOf("_api/");
if (index < 0) {
throw new APIUrlException();
}
var webUrl = url.substr(0, index);
return this._digestCache.getDigest(webUrl)
.then(function (digest) {
headers.append("X-RequestDigest", digest);
return _this.fetchRaw(url, opts);
});
}
}
return this.fetchRaw(url, opts);
};
SPHttpClient.prototype.fetchRaw = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
// here we need to normalize the headers
var rawHeaders = new Headers();
common.mergeHeaders(rawHeaders, options.headers);
options = common.extend(options, { headers: rawHeaders });
var retry = function (ctx) {
_this._impl.fetch(url, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) {
// Check if request was throttled - http status code 429
// Check if request failed due to server unavailable - http status code 503
if (response.status !== 429 && response.status !== 503) {
ctx.reject(response);
}
// grab our current delay
var delay = ctx.delay;
// Increment our counters.
ctx.delay *= 2;
ctx.attempts++;
// If we have exceeded the retry count, reject.
if (ctx.retryCount <= ctx.attempts) {
ctx.reject(response);
}
// Set our retry timeout for {delay} milliseconds.
setTimeout(common.getCtxCallback(_this, retry, ctx), delay);
});
};
return new Promise(function (resolve, reject) {
var retryContext = {
attempts: 0,
delay: 100,
reject: reject,
resolve: resolve,
retryCount: 7,
};
retry.call(_this, retryContext);
});
};
SPHttpClient.prototype.get = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "GET" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.post = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "POST" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.patch = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "PATCH" });
return this.fetch(url, opts);
};
SPHttpClient.prototype.delete = function (url, options) {
if (options === void 0) { options = {}; }
var opts = common.extend(options, { method: "DELETE" });
return this.fetch(url, opts);
};
return SPHttpClient;
}());
/**
* Ensures that a given url is absolute for the current web based on context
*
* @param candidateUrl The url to make absolute
*
*/
function toAbsoluteUrl(candidateUrl) {
return new Promise(function (resolve) {
if (common.isUrlAbsolute(candidateUrl)) {
// if we are already absolute, then just return the url
return resolve(candidateUrl);
}
if (SPRuntimeConfig.baseUrl !== null) {
// base url specified either with baseUrl of spfxContext config property
return resolve(common.combinePaths(SPRuntimeConfig.baseUrl, candidateUrl));
}
if (typeof global._spPageContextInfo !== "undefined") {
// operating in classic pages
if (global._spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) {
return resolve(common.combinePaths(global._spPageContextInfo.webAbsoluteUrl, candidateUrl));
}
else if (global._spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) {
return resolve(common.combinePaths(global._spPageContextInfo.webServerRelativeUrl, candidateUrl));
}
}
// does window.location exist and have a certain path part in it?
if (typeof global.location !== "undefined") {
var baseUrl_1 = global.location.toString().toLowerCase();
["/_layouts/", "/siteassets/"].forEach(function (s) {
var index = baseUrl_1.indexOf(s);
if (index > 0) {
return resolve(common.combinePaths(baseUrl_1.substr(0, index), candidateUrl));
}
});
}
return resolve(candidateUrl);
});
}
/**
* SharePointQueryable Base Class
*
*/
var SharePointQueryable = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryable, _super);
/**
* Creates a new instance of the SharePointQueryable class
*
* @constructor
* @param baseUrl A string or SharePointQueryable that should form the base part of the url
*
*/
function SharePointQueryable(baseUrl, path) {
var _this = _super.call(this) || this;
if (typeof baseUrl === "string") {
// we need to do some extra parsing to get the parent url correct if we are
// being created from just a string.
var urlStr = baseUrl;
if (common.isUrlAbsolute(urlStr) || urlStr.lastIndexOf("/") < 0) {
_this._parentUrl = urlStr;
_this._url = common.combinePaths(urlStr, path);
}
else if (urlStr.lastIndexOf("/") > urlStr.lastIndexOf("(")) {
// .../items(19)/fields
var index = urlStr.lastIndexOf("/");
_this._parentUrl = urlStr.slice(0, index);
path = common.combinePaths(urlStr.slice(index), path);
_this._url = common.combinePaths(_this._parentUrl, path);
}
else {
// .../items(19)
var index = urlStr.lastIndexOf("(");
_this._parentUrl = urlStr.slice(0, index);
_this._url = common.combinePaths(urlStr, path);
}
}
else {
var q = baseUrl;
_this.extend(q, path);
var target = q._query.get("@target");
if (target !== null) {
_this._query.add("@target", target);
}
}
return _this;
}
/**
* Creates a new instance of the supplied factory and extends this into that new instance
*
* @param factory constructor for the new SharePointQueryable
*/
SharePointQueryable.prototype.as = function (factory) {
var o = new factory(this._url, null);
return common.extend(o, this, true);
};
/**
* Gets the full url with query information
*
*/
SharePointQueryable.prototype.toUrlAndQuery = function () {
var aliasedParams = new common.Dictionary();
var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) {
logging.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, 0 /* Verbose */);
aliasedParams.add(labelName, "'" + value + "'");
return labelName;
});
// inlude our explicitly set query string params
aliasedParams.merge(this._query);
if (aliasedParams.count > 0) {
url += "?" + aliasedParams.getKeys().map(function (key) { return key + "=" + aliasedParams.get(key); }).join("&");
}
return url;
};
/**
* Gets a parent for this instance as specified
*
* @param factory The contructor for the class to create
*/
SharePointQueryable.prototype.getParent = function (factory, baseUrl, path, batch) {
if (baseUrl === void 0) { baseUrl = this.parentUrl; }
var parent = new factory(baseUrl, path);
parent.configure(this._options);
var target = this.query.get("@target");
if (target !== null) {
parent.query.add("@target", target);
}
if (typeof batch !== "undefined") {
parent = parent.inBatch(batch);
}
return parent;
};
/**
* Clones this SharePointQueryable into a new SharePointQueryable instance of T
* @param factory Constructor used to create the new instance
* @param additionalPath Any additional path to include in the clone
* @param includeBatch If true this instance's batch will be added to the cloned instance
*/
SharePointQueryable.prototype.clone = function (factory, additionalPath, includeBatch) {
if (includeBatch === void 0) { includeBatch = true; }
var clone = new factory(this, additionalPath);
clone.configure(this._options);
var target = this.query.get("@target");
if (target !== null) {
clone.query.add("@target", target);
}
if (includeBatch && this.hasBatch) {
clone = clone.inBatch(this.batch);
}
return clone;
};
/**
* Converts the current instance to a request context
*
* @param verb The request verb
* @param options The set of supplied request options
* @param parser The supplied ODataParser instance
* @param pipeline Optional request processing pipeline
*/
SharePointQueryable.prototype.toRequestContext = function (verb, options, parser, pipeline) {
var _this = this;
if (options === void 0) { options = {}; }
var dependencyDispose = this.hasBatch ? this.addBatchDependency() : function () { return; };
return toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) {
common.mergeOptions(options, _this._options);
// build our request context
var context = {
batch: _this.batch,
batchDependency: dependencyDispose,
cachingOptions: _this._cachingOptions,
clientFactory: function () { return new SPHttpClient(); },
isBatched: _this.hasBatch,
isCached: _this._useCaching,
options: options,
parser: parser,
pipeline: pipeline,
requestAbsoluteUrl: url,
requestId: common.getGUID(),
verb: verb,
};
return context;
});
};
return SharePointQueryable;
}(odata.ODataQueryable));
/**
* Represents a REST collection which can be filtered, paged, and selected
*
*/
var SharePointQueryableCollection = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableCollection, _super);
function SharePointQueryableCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported)
*
* @param filter The string representing the filter query
*/
SharePointQueryableCollection.prototype.filter = function (filter) {
this._query.add("$filter", filter);
return this;
};
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
SharePointQueryableCollection.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this._query.add("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
SharePointQueryableCollection.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this._query.add("$expand", expands.join(","));
}
return this;
};
/**
* Orders based on the supplied fields
*
* @param orderby The name of the field on which to sort
* @param ascending If false DESC is appended, otherwise ASC (default)
*/
SharePointQueryableCollection.prototype.orderBy = function (orderBy, ascending) {
var _this = this;
if (ascending === void 0) { ascending = true; }
var query = this._query.getKeys().filter(function (k) { return k === "$orderby"; }).map(function (k) { return _this._query.get(k); });
query.push(orderBy + " " + (ascending ? "asc" : "desc"));
this._query.add("$orderby", query.join(","));
return this;
};
/**
* Skips the specified number of items
*
* @param skip The number of items to skip
*/
SharePointQueryableCollection.prototype.skip = function (skip) {
this._query.add("$skip", skip.toString());
return this;
};
/**
* Limits the query to only return the specified number of items
*
* @param top The query row limit
*/
SharePointQueryableCollection.prototype.top = function (top) {
this._query.add("$top", top.toString());
return this;
};
return SharePointQueryableCollection;
}(SharePointQueryable));
/**
* Represents an instance that can be selected
*
*/
var SharePointQueryableInstance = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableInstance, _super);
function SharePointQueryableInstance() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
SharePointQueryableInstance.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this._query.add("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
SharePointQueryableInstance.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this._query.add("$expand", expands.join(","));
}
return this;
};
return SharePointQueryableInstance;
}(SharePointQueryable));
/**
* Describes a collection of all site collection users
*
*/
var SiteUsers = /** @class */ (function (_super) {
tslib_1.__extends(SiteUsers, _super);
/**
* Creates a new instance of the SiteUsers class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this user collection
*/
function SiteUsers(baseUrl, path) {
if (path === void 0) { path = "siteusers"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a user from the collection by email
*
* @param email The email address of the user to retrieve
*/
SiteUsers.prototype.getByEmail = function (email) {
return new SiteUser(this, "getByEmail('" + email + "')");
};
/**
* Gets a user from the collection by id
*
* @param id The id of the user to retrieve
*/
SiteUsers.prototype.getById = function (id) {
return new SiteUser(this, "getById(" + id + ")");
};
/**
* Gets a user from the collection by login name
*
* @param loginName The login name of the user to retrieve
*/
SiteUsers.prototype.getByLoginName = function (loginName) {
var su = new SiteUser(this);
su.concat("(@v)");
su.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return su;
};
/**
* Removes a user from the collection by id
*
* @param id The id of the user to remove
*/
SiteUsers.prototype.removeById = function (id) {
return this.clone(SiteUsers, "removeById(" + id + ")").postCore();
};
/**
* Removes a user from the collection by login name
*
* @param loginName The login name of the user to remove
*/
SiteUsers.prototype.removeByLoginName = function (loginName) {
var o = this.clone(SiteUsers, "removeByLoginName(@v)");
o.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return o.postCore();
};
/**
* Adds a user to a group
*
* @param loginName The login name of the user to add to the group
*
*/
SiteUsers.prototype.add = function (loginName) {
var _this = this;
return this.clone(SiteUsers, null).postCore({
body: JSON.stringify({ "__metadata": { "type": "SP.User" }, LoginName: loginName }),
}).then(function () { return _this.getByLoginName(loginName); });
};
return SiteUsers;
}(SharePointQueryableCollection));
/**
* Describes a single user
*
*/
var SiteUser = /** @class */ (function (_super) {
tslib_1.__extends(SiteUser, _super);
function SiteUser() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SiteUser.prototype, "groups", {
/**
* Gets the groups for this user
*
*/
get: function () {
return new SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
/**
* Updates this user instance with the supplied properties
*
* @param properties A plain object of property names and values to update for the user
*/
SiteUser.prototype.update = function (properties) {
var _this = this;
var postBody = common.extend({ "__metadata": { "type": "SP.User" } }, properties);
return this.postCore({
body: JSON.stringify(postBody),
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
user: _this,
};
});
};
/**
* Delete this user
*
*/
SiteUser.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return SiteUser;
}(SharePointQueryableInstance));
/**
* Represents the current user
*/
var CurrentUser = /** @class */ (function (_super) {
tslib_1.__extends(CurrentUser, _super);
function CurrentUser(baseUrl, path) {
if (path === void 0) { path = "currentuser"; }
return _super.call(this, baseUrl, path) || this;
}
return CurrentUser;
}(SharePointQueryableInstance));
/**
* Principal Type enum
*
*/
var PrincipalType;
(function (PrincipalType) {
PrincipalType[PrincipalType["None"] = 0] = "None";
PrincipalType[PrincipalType["User"] = 1] = "User";
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
PrincipalType[PrincipalType["All"] = 15] = "All";
})(PrincipalType || (PrincipalType = {}));
/**
* Describes a collection of site groups
*
*/
var SiteGroups = /** @class */ (function (_super) {
tslib_1.__extends(SiteGroups, _super);
/**
* Creates a new instance of the SiteGroups class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this group collection
*/
function SiteGroups(baseUrl, path) {
if (path === void 0) { path = "sitegroups"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Adds a new group to the site collection
*
* @param props The group properties object of property names and values to be set for the group
*/
SiteGroups.prototype.add = function (properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({ "__metadata": { "type": "SP.Group" } }, properties));
return this.postCore({ body: postBody }).then(function (data) {
return {
data: data,
group: _this.getById(data.Id),
};
});
};
/**
* Gets a group from the collection by name
*
* @param groupName The name of the group to retrieve
*/
SiteGroups.prototype.getByName = function (groupName) {
return new SiteGroup(this, "getByName('" + groupName + "')");
};
/**
* Gets a group from the collection by id
*
* @param id The id of the group to retrieve
*/
SiteGroups.prototype.getById = function (id) {
var sg = new SiteGroup(this);
sg.concat("(" + id + ")");
return sg;
};
/**
* Removes the group with the specified member id from the collection
*
* @param id The id of the group to remove
*/
SiteGroups.prototype.removeById = function (id) {
return this.clone(SiteGroups, "removeById('" + id + "')").postCore();
};
/**
* Removes the cross-site group with the specified name from the collection
*
* @param loginName The name of the group to remove
*/
SiteGroups.prototype.removeByLoginName = function (loginName) {
return this.clone(SiteGroups, "removeByLoginName('" + loginName + "')").postCore();
};
return SiteGroups;
}(SharePointQueryableCollection));
/**
* Describes a single group
*
*/
var SiteGroup = /** @class */ (function (_super) {
tslib_1.__extends(SiteGroup, _super);
function SiteGroup() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SiteGroup.prototype, "users", {
/**
* Gets the users for this group
*
*/
get: function () {
return new SiteUsers(this, "users");
},
enumerable: true,
configurable: true
});
/**
* Updates this group instance with the supplied properties
*
* @param properties A GroupWriteableProperties object of property names and values to update for the group
*/
/* tslint:disable no-string-literal */
SiteGroup.prototype.update = function (properties) {
var _this = this;
var postBody = common.extend({ "__metadata": { "type": "SP.Group" } }, properties);
return this.postCore({
body: JSON.stringify(postBody),
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retGroup = _this;
if (properties.hasOwnProperty("Title")) {
retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + properties["Title"] + "')");
}
return {
data: data,
group: retGroup,
};
});
};
return SiteGroup;
}(SharePointQueryableInstance));
/**
* Describes a set of role assignments for the current scope
*
*/
var RoleAssignments = /** @class */ (function (_super) {
tslib_1.__extends(RoleAssignments, _super);
/**
* Creates a new instance of the RoleAssignments class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this role assignments collection
*/
function RoleAssignments(baseUrl, path) {
if (path === void 0) { path = "roleassignments"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Adds a new role assignment with the specified principal and role definitions to the collection
*
* @param principalId The id of the user or group to assign permissions to
* @param roleDefId The id of the role definition that defines the permissions to assign
*
*/
RoleAssignments.prototype.add = function (principalId, roleDefId) {
return this.clone(RoleAssignments, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")").postCore();
};
/**
* Removes the role assignment with the specified principal and role definition from the collection
*
* @param principalId The id of the user or group in the role assignment
* @param roleDefId The id of the role definition in the role assignment
*
*/
RoleAssignments.prototype.remove = function (principalId, roleDefId) {
return this.clone(RoleAssignments, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")").postCore();
};
/**
* Gets the role assignment associated with the specified principal id from the collection.
*
* @param id The id of the role assignment
*/
RoleAssignments.prototype.getById = function (id) {
var ra = new RoleAssignment(this);
ra.concat("(" + id + ")");
return ra;
};
return RoleAssignments;
}(SharePointQueryableCollection));
/**
* Describes a role assignment
*
*/
var RoleAssignment = /** @class */ (function (_super) {
tslib_1.__extends(RoleAssignment, _super);
function RoleAssignment() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(RoleAssignment.prototype, "groups", {
/**
* Gets the groups that directly belong to the access control list (ACL) for this securable object
*
*/
get: function () {
return new SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RoleAssignment.prototype, "bindings", {
/**
* Gets the role definition bindings for this role assignment
*
*/
get: function () {
return new RoleDefinitionBindings(this);
},
enumerable: true,
configurable: true
});
/**
* Deletes this role assignment
*
*/
RoleAssignment.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return RoleAssignment;
}(SharePointQueryableInstance));
/**
* Describes a collection of role definitions
*
*/
var RoleDefinitions = /** @class */ (function (_super) {
tslib_1.__extends(RoleDefinitions, _super);
/**
* Creates a new instance of the RoleDefinitions class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this role definitions collection
*
*/
function RoleDefinitions(baseUrl, path) {
if (path === void 0) { path = "roledefinitions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets the role definition with the specified id from the collection
*
* @param id The id of the role definition
*
*/
RoleDefinitions.prototype.getById = function (id) {
return new RoleDefinition(this, "getById(" + id + ")");
};
/**
* Gets the role definition with the specified name
*
* @param name The name of the role definition
*
*/
RoleDefinitions.prototype.getByName = function (name) {
return new RoleDefinition(this, "getbyname('" + name + "')");
};
/**
* Gets the role definition with the specified role type
*
* @param roleTypeKind The roletypekind of the role definition (None=0, Guest=1, Reader=2, Contributor=3, WebDesigner=4, Administrator=5, Editor=6, System=7)
*
*/
RoleDefinitions.prototype.getByType = function (roleTypeKind) {
return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")");
};
/**
* Creates a role definition
*
* @param name The new role definition's name
* @param description The new role definition's description
* @param order The order in which the role definition appears
* @param basePermissions The permissions mask for this role definition
*
*/
RoleDefinitions.prototype.add = function (name, description, order, basePermissions) {
var _this = this;
var postBody = JSON.stringify({
BasePermissions: common.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions),
Description: description,
Name: name,
Order: order,
__metadata: { "type": "SP.RoleDefinition" },
});
return this.postCore({ body: postBody }).then(function (data) {
return {
data: data,
definition: _this.getById(data.Id),
};
});
};
return RoleDefinitions;
}(SharePointQueryableCollection));
/**
* Describes a role definition
*
*/
var RoleDefinition = /** @class */ (function (_super) {
tslib_1.__extends(RoleDefinition, _super);
function RoleDefinition() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Updates this role definition with the supplied properties
*
* @param properties A plain object hash of values to update for the role definition
*/
/* tslint:disable no-string-literal */
RoleDefinition.prototype.update = function (properties) {
var _this = this;
if (typeof properties.hasOwnProperty("BasePermissions") !== "undefined") {
properties["BasePermissions"] = common.extend({ __metadata: { type: "SP.BasePermissions" } }, properties["BasePermissions"]);
}
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": "SP.RoleDefinition" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retDef = _this;
if (properties.hasOwnProperty("Name")) {
var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, "");
retDef = parent_1.getByName(properties["Name"]);
}
return {
data: data,
definition: retDef,
};
});
};
/* tslint:enable */
/**
* Deletes this role definition
*
*/
RoleDefinition.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return RoleDefinition;
}(SharePointQueryableInstance));
/**
* Describes the role definitons bound to a role assignment object
*
*/
var RoleDefinitionBindings = /** @class */ (function (_super) {
tslib_1.__extends(RoleDefinitionBindings, _super);
/**
* Creates a new instance of the RoleDefinitionBindings class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this role definition bindings collection
*/
function RoleDefinitionBindings(baseUrl, path) {
if (path === void 0) { path = "roledefinitionbindings"; }
return _super.call(this, baseUrl, path) || this;
}
return RoleDefinitionBindings;
}(SharePointQueryableCollection));
/**
* Determines the display mode of the given control or view
*/
(function (ControlMode) {
ControlMode[ControlMode["Display"] = 1] = "Display";
ControlMode[ControlMode["Edit"] = 2] = "Edit";
ControlMode[ControlMode["New"] = 3] = "New";
})(exports.ControlMode || (exports.ControlMode = {}));
(function (FieldTypes) {
FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid";
FieldTypes[FieldTypes["Integer"] = 1] = "Integer";
FieldTypes[FieldTypes["Text"] = 2] = "Text";
FieldTypes[FieldTypes["Note"] = 3] = "Note";
FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime";
FieldTypes[FieldTypes["Counter"] = 5] = "Counter";
FieldTypes[FieldTypes["Choice"] = 6] = "Choice";
FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup";
FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean";
FieldTypes[FieldTypes["Number"] = 9] = "Number";
FieldTypes[FieldTypes["Currency"] = 10] = "Currency";
FieldTypes[FieldTypes["URL"] = 11] = "URL";
FieldTypes[FieldTypes["Computed"] = 12] = "Computed";
FieldTypes[FieldTypes["Threading"] = 13] = "Threading";
FieldTypes[FieldTypes["Guid"] = 14] = "Guid";
FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice";
FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice";
FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated";
FieldTypes[FieldTypes["File"] = 18] = "File";
FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments";
FieldTypes[FieldTypes["User"] = 20] = "User";
FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence";
FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink";
FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat";
FieldTypes[FieldTypes["Error"] = 24] = "Error";
FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId";
FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator";
FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex";
FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus";
FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent";
FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType";
})(exports.FieldTypes || (exports.FieldTypes = {}));
(function (DateTimeFieldFormatType) {
DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly";
DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime";
})(exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {}));
(function (AddFieldOptions) {
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection
*/
AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue";
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection.
*/
AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType";
/**
* Specify that a new field must not be added to any other content type
*/
AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType";
/**
* Specify that a new field that is added to the specified list must also be added to all content types in the site collection
*/
AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes";
/**
* Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations
*/
AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint";
/**
* Specify that a new field that is added to the specified list must also be added to the default list view
*/
AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView";
/**
* Specify to confirm that no other field has the same display name
*/
AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName";
})(exports.AddFieldOptions || (exports.AddFieldOptions = {}));
(function (CalendarType) {
CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian";
CalendarType[CalendarType["Japan"] = 3] = "Japan";
CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan";
CalendarType[CalendarType["Korea"] = 5] = "Korea";
CalendarType[CalendarType["Hijri"] = 6] = "Hijri";
CalendarType[CalendarType["Thai"] = 7] = "Thai";
CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew";
CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench";
CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic";
CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish";
CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench";
CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar";
CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar";
CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra";
CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura";
})(exports.CalendarType || (exports.CalendarType = {}));
(function (UrlFieldFormatType) {
UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink";
UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image";
})(exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {}));
(function (PermissionKind) {
/**
* Has no permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask";
/**
* View items in lists, documents in document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems";
/**
* Add items to lists, documents to document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems";
/**
* Edit items in lists, edit documents in document libraries, edit Web discussion comments
* in documents, and customize Web Part Pages in document libraries.
*/
PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems";
/**
* Delete items from a list, documents from a document library, and Web discussion
* comments in documents.
*/
PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems";
/**
* Approve a minor version of a list item or document.
*/
PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems";
/**
* View the source of documents with server-side file handlers.
*/
PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems";
/**
* View past versions of a list item or document.
*/
PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions";
/**
* Delete past versions of a list item or document.
*/
PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions";
/**
* Discard or check in a document which is checked out to another user.
*/
PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout";
/**
* Create, change, and delete personal views of lists.
*/
PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews";
/**
* Create and delete lists, add or remove columns in a list, and add or remove public views of a list.
*/
PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists";
/**
* View forms, views, and application pages, and enumerate lists.
*/
PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages";
/**
* Make content of a list or document library retrieveable for anonymous users through SharePoint search.
* The list permissions in the site do not change.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList";
/**
* Allow users to open a Site, list, or folder to access items inside that container.
*/
PermissionKind[PermissionKind["Open"] = 17] = "Open";
/**
* View pages in a Site.
*/
PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages";
/**
* Add, change, or delete HTML pages or Web Part Pages, and edit the Site using
* a Windows SharePoint Services compatible editor.
*/
PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages";
/**
* Apply a theme or borders to the entire Site.
*/
PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder";
/**
* Apply a style sheet (.css file) to the Site.
*/
PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets";
/**
* View reports on Site usage.
*/
PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData";
/**
* Create a Site using Self-Service Site Creation.
*/
PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite";
/**
* Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
*/
PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs";
/**
* Create a group of users that can be used anywhere within the site collection.
*/
PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups";
/**
* Create and change permission levels on the Site and assign permissions to users
* and groups.
*/
PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions";
/**
* Enumerate files and folders in a Site using Microsoft Office SharePoint Designer
* and WebDAV interfaces.
*/
PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories";
/**
* View information about users of the Site.
*/
PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo";
/**
* Add or remove personal Web Parts on a Web Part Page.
*/
PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts";
/**
* Update Web Parts to display personalized information.
*/
PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts";
/**
* Grant the ability to perform all administration tasks for the Site as well as
* manage content, activate, deactivate, or edit properties of Site scoped Features
* through the object model or through the user interface (UI). When granted on the
* root Site of a Site Collection, activate, deactivate, or edit properties of
* site collection scoped Features through the object model. To browse to the Site
* Collection Features page and activate or deactivate Site Collection scoped Features
* through the UI, you must be a Site Collection administrator.
*/
PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb";
/**
* Content of lists and document libraries in the Web site will be retrieveable for anonymous users through
* SharePoint search if the list or document library has AnonymousSearchAccessList set.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists";
/**
* Use features that launch client applications. Otherwise, users must work on documents
* locally and upload changes.
*/
PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration";
/**
* Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site.
*/
PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs";
/**
* Manage alerts for all users of the Site.
*/
PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts";
/**
* Create e-mail alerts.
*/
PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts";
/**
* Allows a user to change his or her user information, such as adding a picture.
*/
PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo";
/**
* Enumerate permissions on Site, list, folder, document, or list item.
*/
PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions";
/**
* Has all permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask";
})(exports.PermissionKind || (exports.PermissionKind = {}));
(function (RoleType) {
RoleType[RoleType["None"] = 0] = "None";
RoleType[RoleType["Guest"] = 1] = "Guest";
RoleType[RoleType["Reader"] = 2] = "Reader";
RoleType[RoleType["Contributor"] = 3] = "Contributor";
RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner";
RoleType[RoleType["Administrator"] = 5] = "Administrator";
})(exports.RoleType || (exports.RoleType = {}));
(function (PageType) {
PageType[PageType["Invalid"] = -1] = "Invalid";
PageType[PageType["DefaultView"] = 0] = "DefaultView";
PageType[PageType["NormalView"] = 1] = "NormalView";
PageType[PageType["DialogView"] = 2] = "DialogView";
PageType[PageType["View"] = 3] = "View";
PageType[PageType["DisplayForm"] = 4] = "DisplayForm";
PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog";
PageType[PageType["EditForm"] = 6] = "EditForm";
PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog";
PageType[PageType["NewForm"] = 8] = "NewForm";
PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog";
PageType[PageType["SolutionForm"] = 10] = "SolutionForm";
PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS";
})(exports.PageType || (exports.PageType = {}));
(function (SharingLinkKind) {
/**
* Uninitialized link
*/
SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized";
/**
* Direct link to the object being shared
*/
SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct";
/**
* Organization-shareable link to the object being shared with view permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView";
/**
* Organization-shareable link to the object being shared with edit permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit";
/**
* View only anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView";
/**
* Read/Write anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit";
/**
* Flexible sharing Link where properties can change without affecting link URL
*/
SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible";
})(exports.SharingLinkKind || (exports.SharingLinkKind = {}));
(function (SharingRole) {
SharingRole[SharingRole["None"] = 0] = "None";
SharingRole[SharingRole["View"] = 1] = "View";
SharingRole[SharingRole["Edit"] = 2] = "Edit";
SharingRole[SharingRole["Owner"] = 3] = "Owner";
})(exports.SharingRole || (exports.SharingRole = {}));
(function (SharingOperationStatusCode) {
/**
* The share operation completed without errors.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully";
/**
* The share operation completed and generated requests for access.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued";
/**
* The share operation failed as there were no resolved users.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers";
/**
* The share operation failed due to insufficient permissions.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied";
/**
* The share operation failed when attempting a cross site share, which is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported";
/**
* The sharing operation failed due to an unknown error.
*/
SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError";
/**
* The text you typed is too long. Please shorten it.
*/
SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong";
/**
* The maximum number of unique scopes in the list has been exceeded.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded";
/**
* The share operation failed because a sharing capability is disabled in the site.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled";
/**
* The specified object for the share operation is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported";
/**
* A SharePoint group cannot contain another SharePoint group.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported";
})(exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {}));
(function (SPSharedObjectType) {
SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown";
SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File";
SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder";
SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item";
SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List";
SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web";
SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max";
})(exports.SPSharedObjectType || (exports.SPSharedObjectType = {}));
(function (SharingDomainRestrictionMode) {
SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList";
})(exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {}));
(function (RenderListDataOptions) {
RenderListDataOptions[RenderListDataOptions["None"] = 0] = "None";
RenderListDataOptions[RenderListDataOptions["ContextInfo"] = 1] = "ContextInfo";
RenderListDataOptions[RenderListDataOptions["ListData"] = 2] = "ListData";
RenderListDataOptions[RenderListDataOptions["ListSchema"] = 4] = "ListSchema";
RenderListDataOptions[RenderListDataOptions["MenuView"] = 8] = "MenuView";
RenderListDataOptions[RenderListDataOptions["ListContentType"] = 16] = "ListContentType";
RenderListDataOptions[RenderListDataOptions["FileSystemItemId"] = 32] = "FileSystemItemId";
RenderListDataOptions[RenderListDataOptions["ClientFormSchema"] = 64] = "ClientFormSchema";
RenderListDataOptions[RenderListDataOptions["QuickLaunch"] = 128] = "QuickLaunch";
RenderListDataOptions[RenderListDataOptions["Spotlight"] = 256] = "Spotlight";
RenderListDataOptions[RenderListDataOptions["Visualization"] = 512] = "Visualization";
RenderListDataOptions[RenderListDataOptions["ViewMetadata"] = 1024] = "ViewMetadata";
RenderListDataOptions[RenderListDataOptions["DisableAutoHyperlink"] = 2048] = "DisableAutoHyperlink";
RenderListDataOptions[RenderListDataOptions["EnableMediaTAUrls"] = 4096] = "EnableMediaTAUrls";
RenderListDataOptions[RenderListDataOptions["ParentInfo"] = 8192] = "ParentInfo";
RenderListDataOptions[RenderListDataOptions["PageContextInfo"] = 16384] = "PageContextInfo";
RenderListDataOptions[RenderListDataOptions["ClientSideComponentManifest"] = 32768] = "ClientSideComponentManifest";
})(exports.RenderListDataOptions || (exports.RenderListDataOptions = {}));
(function (FieldUserSelectionMode) {
FieldUserSelectionMode[FieldUserSelectionMode["PeopleAndGroups"] = 1] = "PeopleAndGroups";
FieldUserSelectionMode[FieldUserSelectionMode["PeopleOnly"] = 0] = "PeopleOnly";
})(exports.FieldUserSelectionMode || (exports.FieldUserSelectionMode = {}));
(function (ChoiceFieldFormatType) {
ChoiceFieldFormatType[ChoiceFieldFormatType["Dropdown"] = 0] = "Dropdown";
ChoiceFieldFormatType[ChoiceFieldFormatType["RadioButtons"] = 1] = "RadioButtons";
})(exports.ChoiceFieldFormatType || (exports.ChoiceFieldFormatType = {}));
var SharePointQueryableSecurable = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableSecurable, _super);
function SharePointQueryableSecurable() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SharePointQueryableSecurable.prototype, "roleAssignments", {
/**
* Gets the set of role assignments for this item
*
*/
get: function () {
return new RoleAssignments(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SharePointQueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", {
/**
* Gets the closest securable up the security hierarchy whose permissions are applied to this list item
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FirstUniqueAncestorSecurableObject");
},
enumerable: true,
configurable: true
});
/**
* Gets the effective permissions for the user supplied
*
* @param loginName The claims username for the user (ex: i:0#.f|membership|user@domain.com)
*/
SharePointQueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) {
var q = this.clone(SharePointQueryable, "getUserEffectivePermissions(@user)");
q.query.add("@user", "'" + encodeURIComponent(loginName) + "'");
return q.get().then(function (r) {
// handle verbose mode
return r.hasOwnProperty("GetUserEffectivePermissions") ? r.GetUserEffectivePermissions : r;
});
};
/**
* Gets the effective permissions for the current user
*/
SharePointQueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () {
var _this = this;
// remove need to reference Web here, which created a circular build issue
var w = new SharePointQueryableInstance("_api/web", "currentuser");
return w.select("LoginName").get().then(function (user) {
return _this.getUserEffectivePermissions(user.LoginName);
});
};
/**
* Breaks the security inheritance at this level optinally copying permissions and clearing subscopes
*
* @param copyRoleAssignments If true the permissions are copied from the current parent scope
* @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object
*/
SharePointQueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) {
if (copyRoleAssignments === void 0) { copyRoleAssignments = false; }
if (clearSubscopes === void 0) { clearSubscopes = false; }
return this.clone(SharePointQueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")").postCore();
};
/**
* Removes the local role assignments so that it re-inherit role assignments from the parent object.
*
*/
SharePointQueryableSecurable.prototype.resetRoleInheritance = function () {
return this.clone(SharePointQueryableSecurable, "resetroleinheritance").postCore();
};
/**
* Determines if a given user has the appropriate permissions
*
* @param loginName The user to check
* @param permission The permission being checked
*/
SharePointQueryableSecurable.prototype.userHasPermissions = function (loginName, permission) {
var _this = this;
return this.getUserEffectivePermissions(loginName).then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Determines if the current user has the requested permissions
*
* @param permission The permission we wish to check
*/
SharePointQueryableSecurable.prototype.currentUserHasPermissions = function (permission) {
var _this = this;
return this.getCurrentUserEffectivePermissions().then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Taken from sp.js, checks the supplied permissions against the mask
*
* @param value The security principal's permissions on the given object
* @param perm The permission checked against the value
*/
/* tslint:disable:no-bitwise */
SharePointQueryableSecurable.prototype.hasPermissions = function (value, perm) {
if (!perm) {
return true;
}
if (perm === exports.PermissionKind.FullMask) {
return (value.High & 32767) === 32767 && value.Low === 65535;
}
perm = perm - 1;
var num = 1;
if (perm >= 0 && perm < 32) {
num = num << perm;
return 0 !== (value.Low & num);
}
else if (perm >= 32 && perm < 64) {
num = num << perm - 32;
return 0 !== (value.High & num);
}
return false;
};
return SharePointQueryableSecurable;
}(SharePointQueryableInstance));
/**
* Internal helper class used to augment classes to include sharing functionality
*/
var SharePointQueryableShareable = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableShareable, _super);
function SharePointQueryableShareable() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a sharing link for the supplied
*
* @param kind The kind of link to share
* @param expiration The optional expiration for this link
*/
SharePointQueryableShareable.prototype.getShareLink = function (kind, expiration) {
if (expiration === void 0) { expiration = null; }
// date needs to be an ISO string or null
var expString = expiration !== null ? expiration.toISOString() : null;
// clone using the factory and send the request
return this.clone(SharePointQueryableShareable, "shareLink").postCore({
body: JSON.stringify({
request: {
createLink: true,
emailData: null,
settings: {
expiration: expString,
linkKind: kind,
},
},
}),
});
};
/**
* Shares this instance with the supplied users
*
* @param loginNames Resolved login names to share
* @param role The role
* @param requireSignin True to require the user is authenticated, otherwise false
* @param propagateAcl True to apply this share to all children
* @param emailData If supplied an email will be sent with the indicated properties
*/
SharePointQueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) {
var _this = this;
if (requireSignin === void 0) { requireSignin = false; }
if (propagateAcl === void 0) { propagateAcl = false; }
// handle the multiple input types
if (!Array.isArray(loginNames)) {
loginNames = [loginNames];
}
var userStr = JSON.stringify(loginNames.map(function (login) { return { Key: login }; }));
var roleFilter = role === exports.SharingRole.Edit ? exports.RoleType.Contributor : exports.RoleType.Reader;
// start by looking up the role definition id we need to set the roleValue
// remove need to reference Web here, which created a circular build issue
var w = new SharePointQueryableCollection("_api/web", "roledefinitions");
return w.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (!Array.isArray(def) || def.length < 1) {
throw new Error("Could not locate a role defintion with RoleTypeKind " + roleFilter);
}
var postBody = {
includeAnonymousLinkInEmail: requireSignin,
peoplePickerInput: userStr,
propagateAcl: propagateAcl,
roleValue: "role:" + def[0].Id,
useSimplifiedRoles: true,
};
if (typeof emailData !== "undefined") {
postBody = common.extend(postBody, {
emailBody: emailData.body,
emailSubject: typeof emailData.subject !== "undefined" ? emailData.subject : "",
sendEmail: true,
});
}
return _this.clone(SharePointQueryableShareable, "shareObject").postCore({
body: JSON.stringify(postBody),
});
});
};
/**
* Shares an object based on the supplied options
*
* @param options The set of options to send to the ShareObject method
* @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method
*/
SharePointQueryableShareable.prototype.shareObject = function (options, bypass) {
var _this = this;
if (bypass === void 0) { bypass = false; }
if (bypass) {
// if the bypass flag is set send the supplied parameters directly to the service
return this.sendShareObjectRequest(options);
}
// extend our options with some defaults
options = common.extend(options, {
group: null,
includeAnonymousLinkInEmail: false,
propagateAcl: false,
useSimplifiedRoles: true,
}, true);
return this.getRoleValue(options.role, options.group).then(function (roleValue) {
// handle the multiple input types
if (!Array.isArray(options.loginNames)) {
options.loginNames = [options.loginNames];
}
var userStr = JSON.stringify(options.loginNames.map(function (login) { return { Key: login }; }));
var postBody = {
peoplePickerInput: userStr,
roleValue: roleValue,
url: options.url,
};
if (typeof options.emailData !== "undefined" && options.emailData !== null) {
postBody = common.extend(postBody, {
emailBody: options.emailData.body,
emailSubject: typeof options.emailData.subject !== "undefined" ? options.emailData.subject : "Shared with you.",
sendEmail: true,
});
}
return _this.sendShareObjectRequest(postBody);
});
};
/**
* Calls the web's UnshareObject method
*
* @param url The url of the object to unshare
*/
SharePointQueryableShareable.prototype.unshareObjectWeb = function (url) {
return this.clone(SharePointQueryableShareable, "unshareObject").postCore({
body: JSON.stringify({
url: url,
}),
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
SharePointQueryableShareable.prototype.checkPermissions = function (recipients) {
return this.clone(SharePointQueryableShareable, "checkPermissions").postCore({
body: JSON.stringify({
recipients: recipients,
}),
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
*/
SharePointQueryableShareable.prototype.getSharingInformation = function (request) {
if (request === void 0) { request = null; }
return this.clone(SharePointQueryableShareable, "getSharingInformation").postCore({
body: JSON.stringify({
request: request,
}),
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
SharePointQueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, "getObjectSharingSettings").postCore({
body: JSON.stringify({
useSimplifiedRoles: useSimplifiedRoles,
}),
});
};
/**
* Unshares this object
*/
SharePointQueryableShareable.prototype.unshareObject = function () {
return this.clone(SharePointQueryableShareable, "unshareObject").postCore();
};
/**
* Deletes a link by type
*
* @param kind Deletes a sharing link by the kind of link
*/
SharePointQueryableShareable.prototype.deleteLinkByKind = function (kind) {
return this.clone(SharePointQueryableShareable, "deleteLinkByKind").postCore({
body: JSON.stringify({ linkKind: kind }),
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
SharePointQueryableShareable.prototype.unshareLink = function (kind, shareId) {
if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; }
return this.clone(SharePointQueryableShareable, "unshareLink").postCore({
body: JSON.stringify({ linkKind: kind, shareId: shareId }),
});
};
/**
* Calculates the roleValue string used in the sharing query
*
* @param role The Sharing Role
* @param group The Group type
*/
SharePointQueryableShareable.prototype.getRoleValue = function (role, group) {
// we will give group precedence, because we had to make a choice
if (typeof group !== "undefined" && group !== null) {
switch (group) {
case exports.RoleType.Contributor:
// remove need to reference Web here, which created a circular build issue
var memberGroup = new SharePointQueryableInstance("_api/web", "associatedmembergroup");
return memberGroup.select("Id").get().then(function (g) { return "group: " + g.Id; });
case exports.RoleType.Reader:
case exports.RoleType.Guest:
// remove need to reference Web here, which created a circular build issue
var visitorGroup = new SharePointQueryableInstance("_api/web", "associatedvisitorgroup");
return visitorGroup.select("Id").get().then(function (g) { return "group: " + g.Id; });
default:
throw new Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported");
}
}
else {
var roleFilter = role === exports.SharingRole.Edit ? exports.RoleType.Contributor : exports.RoleType.Reader;
// remove need to reference Web here, which created a circular build issue
var roleDefs = new SharePointQueryableCollection("_api/web", "roledefinitions");
return roleDefs.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (def.length < 1) {
throw new Error("Could not locate associated role definition for supplied role. Edit and View are supported");
}
return "role: " + def[0].Id;
});
}
};
SharePointQueryableShareable.prototype.getShareObjectWeb = function (candidate) {
return Promise.resolve(new SharePointQueryableInstance(extractWebUrl(candidate), "/_api/SP.Web.ShareObject"));
};
SharePointQueryableShareable.prototype.sendShareObjectRequest = function (options) {
return this.getShareObjectWeb(this.toUrl()).then(function (web) {
return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(SharePointQueryableShareable).postCore({
body: JSON.stringify(options),
});
});
};
return SharePointQueryableShareable;
}(SharePointQueryable));
var SharePointQueryableShareableWeb = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableShareableWeb, _super);
function SharePointQueryableShareableWeb() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this web with the supplied users
* @param loginNames The resolved login names to share
* @param role The role to share this web
* @param emailData Optional email data
*/
SharePointQueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) {
var _this = this;
if (role === void 0) { role = exports.SharingRole.View; }
var dependency = this.addBatchDependency();
// remove need to reference Web here, which created a circular build issue
var web = new SharePointQueryableInstance(extractWebUrl(this.toUrl()), "/_api/web/url");
return web.get().then(function (url) {
dependency();
return _this.shareObject(common.combinePaths(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData);
});
};
/**
* Provides direct access to the static web.ShareObject method
*
* @param url The url to share
* @param loginNames Resolved loginnames string[] of a single login name string
* @param roleValue Role value
* @param emailData Optional email data
* @param groupId Optional group id
* @param propagateAcl
* @param includeAnonymousLinkInEmail
* @param useSimplifiedRoles
*/
SharePointQueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) {
if (propagateAcl === void 0) { propagateAcl = false; }
if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; }
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, null).shareObject({
emailData: emailData,
group: group,
includeAnonymousLinkInEmail: includeAnonymousLinkInEmail,
loginNames: loginNames,
propagateAcl: propagateAcl,
role: role,
url: url,
useSimplifiedRoles: useSimplifiedRoles,
});
};
/**
* Supplies a method to pass any set of arguments to ShareObject
*
* @param options The set of options to send to ShareObject
*/
SharePointQueryableShareableWeb.prototype.shareObjectRaw = function (options) {
return this.clone(SharePointQueryableShareable, null).shareObject(options, true);
};
/**
* Unshares the object
*
* @param url The url of the object to stop sharing
*/
SharePointQueryableShareableWeb.prototype.unshareObject = function (url) {
return this.clone(SharePointQueryableShareable, null).unshareObjectWeb(url);
};
return SharePointQueryableShareableWeb;
}(SharePointQueryableSecurable));
var SharePointQueryableShareableItem = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableShareableItem, _super);
function SharePointQueryableShareableItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing for this item
*
* @param kind The type of link to share
* @param expiration The optional expiration date
*/
SharePointQueryableShareableItem.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = exports.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
return this.clone(SharePointQueryableShareable, null).getShareLink(kind, expiration);
};
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
return this.clone(SharePointQueryableShareable, null).shareWith(loginNames, role, requireSignin, false, emailData);
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
SharePointQueryableShareableItem.prototype.checkSharingPermissions = function (recipients) {
return this.clone(SharePointQueryableShareable, null).checkPermissions(recipients);
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
*/
SharePointQueryableShareableItem.prototype.getSharingInformation = function (request) {
if (request === void 0) { request = null; }
return this.clone(SharePointQueryableShareable, null).getSharingInformation(request);
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
SharePointQueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(SharePointQueryableShareable, null).getObjectSharingSettings(useSimplifiedRoles);
};
/**
* Unshare this item
*/
SharePointQueryableShareableItem.prototype.unshare = function () {
return this.clone(SharePointQueryableShareable, null).unshareObject();
};
/**
* Deletes a sharing link by kind
*
* @param kind Deletes a sharing link by the kind of link
*/
SharePointQueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) {
return this.clone(SharePointQueryableShareable, null).deleteLinkByKind(kind);
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
SharePointQueryableShareableItem.prototype.unshareLink = function (kind, shareId) {
return this.clone(SharePointQueryableShareable, null).unshareLink(kind, shareId);
};
return SharePointQueryableShareableItem;
}(SharePointQueryableSecurable));
var FileFolderShared = /** @class */ (function (_super) {
tslib_1.__extends(FileFolderShared, _super);
function FileFolderShared() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing
*
* @param kind The kind of link to get
* @param expiration Optional, an expiration for this link
*/
FileFolderShared.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = exports.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getShareLink(kind, expiration);
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
FileFolderShared.prototype.checkSharingPermissions = function (recipients) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.checkPermissions(recipients);
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
*/
FileFolderShared.prototype.getSharingInformation = function (request) {
if (request === void 0) { request = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getSharingInformation(request);
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getObjectSharingSettings(useSimplifiedRoles);
});
};
/**
* Unshare this item
*/
FileFolderShared.prototype.unshare = function () {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareObject();
});
};
/**
* Deletes a sharing link by the kind of link
*
* @param kind The kind of link to be deleted.
*/
FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.deleteLinkByKind(kind);
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId The share id to delete
*/
FileFolderShared.prototype.unshareLink = function (kind, shareId) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareLink(kind, shareId);
});
};
/**
* For files and folders we need to use the associated item end point
*/
FileFolderShared.prototype.getShareable = function () {
var _this = this;
// sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally
return this.clone(SharePointQueryableShareableFile, "listItemAllFields", false).select("odata.editlink").get().then(function (d) {
var shareable = new SharePointQueryableShareable(spGetEntityUrl(d));
// we need to handle batching
if (_this.hasBatch) {
shareable = shareable.inBatch(_this.batch);
}
return shareable;
});
};
return FileFolderShared;
}(SharePointQueryableInstance));
var SharePointQueryableShareableFile = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableShareableFile, _super);
function SharePointQueryableShareableFile() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, false, emailData);
});
};
return SharePointQueryableShareableFile;
}(FileFolderShared));
var SharePointQueryableShareableFolder = /** @class */ (function (_super) {
tslib_1.__extends(SharePointQueryableShareableFolder, _super);
function SharePointQueryableShareableFolder() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
SharePointQueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) {
if (role === void 0) { role = exports.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = false; }
if (shareEverything === void 0) { shareEverything = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData);
});
};
return SharePointQueryableShareableFolder;
}(FileFolderShared));
var LimitedWebPartManager = /** @class */ (function (_super) {
tslib_1.__extends(LimitedWebPartManager, _super);
function LimitedWebPartManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(LimitedWebPartManager.prototype, "webparts", {
/**
* Gets the set of web part definitions contained by this web part manager
*
*/
get: function () {
return new WebPartDefinitions(this, "webparts");
},
enumerable: true,
configurable: true
});
/**
* Exports a webpart definition
*
* @param id the GUID id of the definition to export
*/
LimitedWebPartManager.prototype.export = function (id) {
return this.clone(LimitedWebPartManager, "ExportWebPart").postCore({
body: JSON.stringify({ webPartId: id }),
});
};
/**
* Imports a webpart
*
* @param xml webpart definition which must be valid XML in the .dwp or .webpart format
*/
LimitedWebPartManager.prototype.import = function (xml) {
return this.clone(LimitedWebPartManager, "ImportWebPart").postCore({
body: JSON.stringify({ webPartXml: xml }),
});
};
return LimitedWebPartManager;
}(SharePointQueryable));
var WebPartDefinitions = /** @class */ (function (_super) {
tslib_1.__extends(WebPartDefinitions, _super);
function WebPartDefinitions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a web part definition from the collection by id
*
* @param id The storage ID of the SPWebPartDefinition to retrieve
*/
WebPartDefinitions.prototype.getById = function (id) {
return new WebPartDefinition(this, "getbyid('" + id + "')");
};
/**
* Gets a web part definition from the collection by storage id
*
* @param id The WebPart.ID of the SPWebPartDefinition to retrieve
*/
WebPartDefinitions.prototype.getByControlId = function (id) {
return new WebPartDefinition(this, "getByControlId('" + id + "')");
};
return WebPartDefinitions;
}(SharePointQueryableCollection));
var WebPartDefinition = /** @class */ (function (_super) {
tslib_1.__extends(WebPartDefinition, _super);
function WebPartDefinition() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(WebPartDefinition.prototype, "webpart", {
/**
* Gets the webpart information associated with this definition
*/
get: function () {
return new WebPart(this);
},
enumerable: true,
configurable: true
});
/**
* Saves changes to the Web Part made using other properties and methods on the SPWebPartDefinition object
*/
WebPartDefinition.prototype.saveChanges = function () {
return this.clone(WebPartDefinition, "SaveWebPartChanges").postCore();
};
/**
* Moves the Web Part to a different location on a Web Part Page
*
* @param zoneId The ID of the Web Part Zone to which to move the Web Part
* @param zoneIndex A Web Part zone index that specifies the position at which the Web Part is to be moved within the destination Web Part zone
*/
WebPartDefinition.prototype.moveTo = function (zoneId, zoneIndex) {
return this.clone(WebPartDefinition, "MoveWebPartTo(zoneID='" + zoneId + "', zoneIndex=" + zoneIndex + ")").postCore();
};
/**
* Closes the Web Part. If the Web Part is already closed, this method does nothing
*/
WebPartDefinition.prototype.close = function () {
return this.clone(WebPartDefinition, "CloseWebPart").postCore();
};
/**
* Opens the Web Part. If the Web Part is already closed, this method does nothing
*/
WebPartDefinition.prototype.open = function () {
return this.clone(WebPartDefinition, "OpenWebPart").postCore();
};
/**
* Removes a webpart from a page, all settings will be lost
*/
WebPartDefinition.prototype.delete = function () {
return this.clone(WebPartDefinition, "DeleteWebPart").postCore();
};
return WebPartDefinition;
}(SharePointQueryableInstance));
var WebPart = /** @class */ (function (_super) {
tslib_1.__extends(WebPart, _super);
/**
* Creates a new instance of the WebPart class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
* @param path Optional, if supplied will be appended to the supplied baseUrl
*/
function WebPart(baseUrl, path) {
if (path === void 0) { path = "webpart"; }
return _super.call(this, baseUrl, path) || this;
}
return WebPart;
}(SharePointQueryableInstance));
/**
* Describes a collection of Folder objects
*
*/
var Folders = /** @class */ (function (_super) {
tslib_1.__extends(Folders, _super);
/**
* Creates a new instance of the Folders class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Folders(baseUrl, path) {
if (path === void 0) { path = "folders"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a folder by folder name
*
*/
Folders.prototype.getByName = function (name) {
var f = new Folder(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new folder to the current folder (relative) or any folder (absolute)
*
* @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute.
* @returns The new Folder and the raw response.
*/
Folders.prototype.add = function (url) {
var _this = this;
return this.clone(Folders, "add('" + url + "')").postCore().then(function (response) {
return {
data: response,
folder: _this.getByName(url),
};
});
};
return Folders;
}(SharePointQueryableCollection));
/**
* Describes a single Folder instance
*
*/
var Folder = /** @class */ (function (_super) {
tslib_1.__extends(Folder, _super);
function Folder() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Folder.prototype, "contentTypeOrder", {
/**
* Specifies the sequence in which content types are displayed.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "contentTypeOrder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "files", {
/**
* Gets this folder's files
*
*/
get: function () {
return new Files(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "folders", {
/**
* Gets this folder's sub folders
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "listItemAllFields", {
/**
* Gets this folder's list item field values
*
*/
get: function () {
return new SharePointQueryableCollection(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "parentFolder", {
/**
* Gets the parent folder, if available
*
*/
get: function () {
return new Folder(this, "parentFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "properties", {
/**
* Gets this folder's properties
*
*/
get: function () {
return new SharePointQueryableInstance(this, "properties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "serverRelativeUrl", {
/**
* Gets this folder's server relative url
*
*/
get: function () {
return new SharePointQueryable(this, "serverRelativeUrl");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", {
/**
* Gets a value that specifies the content type order.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "uniqueContentTypeOrder");
},
enumerable: true,
configurable: true
});
Folder.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": "SP.Folder" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
folder: _this,
};
});
};
/**
* Delete this folder
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Folder.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(Folder, null).postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Folder.prototype.recycle = function () {
return this.clone(Folder, "recycle").postCore();
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
Folder.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return common.extend(new Item(spGetEntityUrl(d)), d);
});
};
return Folder;
}(SharePointQueryableShareableFolder));
/**
* Describes a collection of content types
*
*/
var ContentTypes = /** @class */ (function (_super) {
tslib_1.__extends(ContentTypes, _super);
/**
* Creates a new instance of the ContentTypes class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this content types collection
*/
function ContentTypes(baseUrl, path) {
if (path === void 0) { path = "contenttypes"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a ContentType by content type id
*/
ContentTypes.prototype.getById = function (id) {
var ct = new ContentType(this);
ct.concat("('" + id + "')");
return ct;
};
/**
* Adds an existing contenttype to a content type collection
*
* @param contentTypeId in the following format, for example: 0x010102
*/
ContentTypes.prototype.addAvailableContentType = function (contentTypeId) {
var _this = this;
var postBody = JSON.stringify({
"contentTypeId": contentTypeId,
});
return this.clone(ContentTypes, "addAvailableContentType").postCore({ body: postBody }).then(function (data) {
return {
contentType: _this.getById(data.id),
data: data,
};
});
};
/**
* Adds a new content type to the collection
*
* @param id The desired content type id for the new content type (also determines the parent content type)
* @param name The name of the content type
* @param description The description of the content type
* @param group The group in which to add the content type
* @param additionalSettings Any additional settings to provide when creating the content type
*
*/
ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (group === void 0) { group = "Custom Content Types"; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = JSON.stringify(common.extend({
"Description": description,
"Group": group,
"Id": { "StringValue": id },
"Name": name,
"__metadata": { "type": "SP.ContentType" },
}, additionalSettings));
return this.postCore({ body: postBody }).then(function (data) {
return { contentType: _this.getById(data.id), data: data };
});
};
return ContentTypes;
}(SharePointQueryableCollection));
/**
* Describes a single ContentType instance
*
*/
var ContentType = /** @class */ (function (_super) {
tslib_1.__extends(ContentType, _super);
function ContentType() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(ContentType.prototype, "fieldLinks", {
/**
* Gets the column (also known as field) references in the content type.
*/
get: function () {
return new FieldLinks(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "fields", {
/**
* Gets a value that specifies the collection of fields for the content type.
*/
get: function () {
return new SharePointQueryableCollection(this, "fields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "parent", {
/**
* Gets the parent content type of the content type.
*/
get: function () {
return new ContentType(this, "parent");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "workflowAssociations", {
/**
* Gets a value that specifies the collection of workflow associations for the content type.
*/
get: function () {
return new SharePointQueryableCollection(this, "workflowAssociations");
},
enumerable: true,
configurable: true
});
/**
* Delete this content type
*/
ContentType.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return ContentType;
}(SharePointQueryableInstance));
/**
* Represents a collection of field link instances
*/
var FieldLinks = /** @class */ (function (_super) {
tslib_1.__extends(FieldLinks, _super);
/**
* Creates a new instance of the ContentType class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this content type instance
*/
function FieldLinks(baseUrl, path) {
if (path === void 0) { path = "fieldlinks"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a FieldLink by GUID id
*
* @param id The GUID id of the field link
*/
FieldLinks.prototype.getById = function (id) {
var fl = new FieldLink(this);
fl.concat("(guid'" + id + "')");
return fl;
};
return FieldLinks;
}(SharePointQueryableCollection));
/**
* Represents a field link instance
*/
var FieldLink = /** @class */ (function (_super) {
tslib_1.__extends(FieldLink, _super);
function FieldLink() {
return _super !== null && _super.apply(this, arguments) || this;
}
return FieldLink;
}(SharePointQueryableInstance));
/**
* Describes a collection of Item objects
*
*/
var AttachmentFiles = /** @class */ (function (_super) {
tslib_1.__extends(AttachmentFiles, _super);
/**
* Creates a new instance of the AttachmentFiles class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this attachments collection
*/
function AttachmentFiles(baseUrl, path) {
if (path === void 0) { path = "AttachmentFiles"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a Attachment File by filename
*
* @param name The name of the file, including extension.
*/
AttachmentFiles.prototype.getByName = function (name) {
var f = new AttachmentFile(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new attachment to the collection. Not supported for batching.
*
* @param name The name of the file, including extension.
* @param content The Base64 file content.
*/
AttachmentFiles.prototype.add = function (name, content) {
var _this = this;
return this.clone(AttachmentFiles, "add(FileName='" + name + "')", false).postCore({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(name),
};
});
};
/**
* Adds multiple new attachment to the collection. Not supported for batching.
*
* @files name The collection of files to add
*/
AttachmentFiles.prototype.addMultiple = function (files) {
var _this = this;
// add the files in series so we don't get update conflicts
return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles, "add(FileName='" + file.name + "')", false).postCore({
body: file.content,
}); }); }, Promise.resolve());
};
/**
* Delete multiple attachments from the collection. Not supported for batching.
*
* @files name The collection of files to delete
*/
AttachmentFiles.prototype.deleteMultiple = function () {
var _this = this;
var files = [];
for (var _i = 0; _i < arguments.length; _i++) {
files[_i] = arguments[_i];
}
return files.reduce(function (chain, file) { return chain.then(function () { return _this.getByName(file).delete(); }); }, Promise.resolve());
};
return AttachmentFiles;
}(SharePointQueryableCollection));
/**
* Describes a single attachment file instance
*
*/
var AttachmentFile = /** @class */ (function (_super) {
tslib_1.__extends(AttachmentFile, _super);
function AttachmentFile() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets the contents of the file as text
*
*/
AttachmentFile.prototype.getText = function () {
return this.getParsed(new odata.TextParser());
};
/**
* Gets the contents of the file as a blob, does not work in Node.js
*
*/
AttachmentFile.prototype.getBlob = function () {
return this.getParsed(new odata.BlobParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getBuffer = function () {
return this.getParsed(new odata.BufferParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getJSON = function () {
return this.getParsed(new odata.JSONParser());
};
/**
* Sets the content of a file. Not supported for batching
*
* @param content The value to set for the file contents
*/
AttachmentFile.prototype.setContent = function (content) {
var _this = this;
return this.clone(AttachmentFile, "$value", false).postCore({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new AttachmentFile(_this); });
};
/**
* Delete this attachment file
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
AttachmentFile.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
AttachmentFile.prototype.getParsed = function (parser) {
return this.clone(AttachmentFile, "$value", false).get(parser);
};
return AttachmentFile;
}(SharePointQueryableInstance));
/**
* Describes the views available in the current context
*
*/
var Views = /** @class */ (function (_super) {
tslib_1.__extends(Views, _super);
/**
* Creates a new instance of the Views class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Views(baseUrl, path) {
if (path === void 0) { path = "views"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a view by guid id
*
* @param id The GUID id of the view
*/
Views.prototype.getById = function (id) {
var v = new View(this);
v.concat("('" + id + "')");
return v;
};
/**
* Gets a view by title (case-sensitive)
*
* @param title The case-sensitive title of the view
*/
Views.prototype.getByTitle = function (title) {
return new View(this, "getByTitle('" + title + "')");
};
/**
* Adds a new view to the collection
*
* @param title The new views's title
* @param personalView True if this is a personal view, otherwise false, default = false
* @param additionalSettings Will be passed as part of the view creation body
*/
Views.prototype.add = function (title, personalView, additionalSettings) {
var _this = this;
if (personalView === void 0) { personalView = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = JSON.stringify(common.extend({
"PersonalView": personalView,
"Title": title,
"__metadata": { "type": "SP.View" },
}, additionalSettings));
return this.clone(Views, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
view: _this.getById(data.Id),
};
});
};
return Views;
}(SharePointQueryableCollection));
/**
* Describes a single View instance
*
*/
var View = /** @class */ (function (_super) {
tslib_1.__extends(View, _super);
function View() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(View.prototype, "fields", {
get: function () {
return new ViewFields(this);
},
enumerable: true,
configurable: true
});
/**
* Updates this view intance with the supplied properties
*
* @param properties A plain object hash of values to update for the view
*/
View.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": "SP.View" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
view: _this,
};
});
};
/**
* Delete this view
*
*/
View.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Returns the list view as HTML.
*
*/
View.prototype.renderAsHtml = function () {
return this.clone(SharePointQueryable, "renderashtml").get();
};
return View;
}(SharePointQueryableInstance));
var ViewFields = /** @class */ (function (_super) {
tslib_1.__extends(ViewFields, _super);
function ViewFields(baseUrl, path) {
if (path === void 0) { path = "viewfields"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a value that specifies the XML schema that represents the collection.
*/
ViewFields.prototype.getSchemaXml = function () {
return this.clone(SharePointQueryable, "schemaxml").get();
};
/**
* Adds the field with the specified field internal name or display name to the collection.
*
* @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add.
*/
ViewFields.prototype.add = function (fieldTitleOrInternalName) {
return this.clone(ViewFields, "addviewfield('" + fieldTitleOrInternalName + "')").postCore();
};
/**
* Moves the field with the specified field internal name to the specified position in the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to move.
* @param index The zero-based index of the new position for the field.
*/
ViewFields.prototype.move = function (fieldInternalName, index) {
return this.clone(ViewFields, "moveviewfieldto").postCore({
body: JSON.stringify({ "field": fieldInternalName, "index": index }),
});
};
/**
* Removes all the fields from the collection.
*/
ViewFields.prototype.removeAll = function () {
return this.clone(ViewFields, "removeallviewfields").postCore();
};
/**
* Removes the field with the specified field internal name from the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to remove from the view.
*/
ViewFields.prototype.remove = function (fieldInternalName) {
return this.clone(ViewFields, "removeviewfield('" + fieldInternalName + "')").postCore();
};
return ViewFields;
}(SharePointQueryableCollection));
/**
* Describes a collection of Field objects
*
*/
var Fields = /** @class */ (function (_super) {
tslib_1.__extends(Fields, _super);
/**
* Creates a new instance of the Fields class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Fields(baseUrl, path) {
if (path === void 0) { path = "fields"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a field from the collection by title
*
* @param title The case-sensitive title of the field
*/
Fields.prototype.getByTitle = function (title) {
return new Field(this, "getByTitle('" + title + "')");
};
/**
* Gets a field from the collection by using internal name or title
*
* @param name The case-sensitive internal name or title of the field
*/
Fields.prototype.getByInternalNameOrTitle = function (name) {
return new Field(this, "getByInternalNameOrTitle('" + name + "')");
};
/**
* Gets a list from the collection by guid id
*
* @param title The Id of the list
*/
Fields.prototype.getById = function (id) {
var f = new Field(this);
f.concat("('" + id + "')");
return f;
};
/**
* Creates a field based on the specified schema
*/
Fields.prototype.createFieldAsXml = function (xml) {
var _this = this;
var info;
if (typeof xml === "string") {
info = { SchemaXml: xml };
}
else {
info = xml;
}
var postBody = JSON.stringify({
"parameters": common.extend({
"__metadata": {
"type": "SP.XmlSchemaFieldCreationInformation",
},
}, info),
});
return this.clone(Fields, "createfieldasxml").postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new field to the collection
*
* @param title The new field's title
* @param fieldType The new field's type (ex: SP.FieldText)
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.add = function (title, fieldType, properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({
"Title": title,
"__metadata": { "type": fieldType },
}, properties));
return this.clone(Fields, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldText to the collection
*
* @param title The field title
* @param maxLength The maximum number of characters allowed in the value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addText = function (title, maxLength, properties) {
if (maxLength === void 0) { maxLength = 255; }
var props = {
FieldTypeKind: 2,
MaxLength: maxLength,
};
return this.add(title, "SP.FieldText", common.extend(props, properties));
};
/**
* Adds a new SP.FieldCalculated to the collection
*
* @param title The field title.
* @param formula The formula for the field.
* @param dateFormat The date and time format that is displayed in the field.
* @param outputType Specifies the output format for the field. Represents a FieldType value.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) {
if (outputType === void 0) { outputType = exports.FieldTypes.Text; }
var props = {
DateFormat: dateFormat,
FieldTypeKind: 17,
Formula: formula,
OutputType: outputType,
};
return this.add(title, "SP.FieldCalculated", common.extend(props, properties));
};
/**
* Adds a new SP.FieldDateTime to the collection
*
* @param title The field title
* @param displayFormat The format of the date and time that is displayed in the field.
* @param calendarType Specifies the calendar type of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) {
if (displayFormat === void 0) { displayFormat = exports.DateTimeFieldFormatType.DateOnly; }
if (calendarType === void 0) { calendarType = exports.CalendarType.Gregorian; }
if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; }
var props = {
DateTimeCalendarType: calendarType,
DisplayFormat: displayFormat,
FieldTypeKind: 4,
FriendlyDisplayFormat: friendlyDisplayFormat,
};
return this.add(title, "SP.FieldDateTime", common.extend(props, properties));
};
/**
* Adds a new SP.FieldNumber to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addNumber = function (title, minValue, maxValue, properties) {
var props = { FieldTypeKind: 9 };
if (typeof minValue !== "undefined") {
props = common.extend({ MinimumValue: minValue }, props);
}
if (typeof maxValue !== "undefined") {
props = common.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldNumber", common.extend(props, properties));
};
/**
* Adds a new SP.FieldCurrency to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) {
if (currencyLocalId === void 0) { currencyLocalId = 1033; }
var props = {
CurrencyLocaleId: currencyLocalId,
FieldTypeKind: 10,
};
if (typeof minValue !== "undefined") {
props = common.extend({ MinimumValue: minValue }, props);
}
if (typeof maxValue !== "undefined") {
props = common.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldCurrency", common.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiLineText to the collection
*
* @param title The field title
* @param numberOfLines Specifies the number of lines of text to display for the field.
* @param richText Specifies whether the field supports rich formatting.
* @param restrictedMode Specifies whether the field supports a subset of rich formatting.
* @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms.
* @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*
*/
Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) {
if (numberOfLines === void 0) { numberOfLines = 6; }
if (richText === void 0) { richText = true; }
if (restrictedMode === void 0) { restrictedMode = false; }
if (appendOnly === void 0) { appendOnly = false; }
if (allowHyperlink === void 0) { allowHyperlink = true; }
var props = {
AllowHyperlink: allowHyperlink,
AppendOnly: appendOnly,
FieldTypeKind: 3,
NumberOfLines: numberOfLines,
RestrictedMode: restrictedMode,
RichText: richText,
};
return this.add(title, "SP.FieldMultiLineText", common.extend(props, properties));
};
/**
* Adds a new SP.FieldUrl to the collection
*
* @param title The field title
*/
Fields.prototype.addUrl = function (title, displayFormat, properties) {
if (displayFormat === void 0) { displayFormat = exports.UrlFieldFormatType.Hyperlink; }
var props = {
DisplayFormat: displayFormat,
FieldTypeKind: 11,
};
return this.add(title, "SP.FieldUrl", common.extend(props, properties));
};
/** Adds a user field to the colleciton
*
* @param title The new field's title
* @param selectionMode The selection mode of the field
* @param selectionGroup Value that specifies the identifier of the SharePoint group whose members can be selected as values of the field
* @param properties
*/
Fields.prototype.addUser = function (title, selectionMode, properties) {
var props = {
FieldTypeKind: 20,
SelectionMode: selectionMode,
};
return this.add(title, "SP.FieldUser", common.extend(props, properties));
};
/**
* Adds a SP.FieldLookup to the collection
*
* @param title The new field's title
* @param lookupListId The guid id of the list where the source of the lookup is found
* @param lookupFieldName The internal name of the field in the source list
* @param properties Set of additional properties to set on the new field
*/
Fields.prototype.addLookup = function (title, lookupListId, lookupFieldName, properties) {
var _this = this;
var postBody = JSON.stringify({
parameters: common.extend({
FieldTypeKind: 7,
LookupFieldName: lookupFieldName,
LookupListId: lookupListId,
Title: title,
"__metadata": { "type": "SP.FieldCreationInformation" },
}, properties),
});
return this.clone(Fields, "addfield").postCore({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldChoice to the collection
*
* @param title The field title.
* @param choices The choices for the field.
* @param format The display format of the available options for the field.
* @param fillIn Specifies whether the field allows fill-in values.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addChoice = function (title, choices, format, fillIn, properties) {
if (format === void 0) { format = exports.ChoiceFieldFormatType.Dropdown; }
var props = {
Choices: {
results: choices,
},
EditFormat: format,
FieldTypeKind: 6,
FillInChoice: fillIn,
};
return this.add(title, "SP.FieldChoice", common.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiChoice to the collection
*
* @param title The field title.
* @param choices The choices for the field.
* @param fillIn Specifies whether the field allows fill-in values.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addMultiChoice = function (title, choices, fillIn, properties) {
var props = {
Choices: {
results: choices,
},
FieldTypeKind: 15,
FillInChoice: fillIn,
};
return this.add(title, "SP.FieldMultiChoice", common.extend(props, properties));
};
/**
* Adds a new SP.FieldBoolean to the collection
*
* @param title The field title.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addBoolean = function (title, properties) {
var props = {
FieldTypeKind: 8,
};
return this.add(title, "SP.Field", common.extend(props, properties));
};
return Fields;
}(SharePointQueryableCollection));
/**
* Describes a single of Field instance
*
*/
var Field = /** @class */ (function (_super) {
tslib_1.__extends(Field, _super);
function Field() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Updates this field intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param fieldType The type value, required to update child field type properties
*/
Field.prototype.update = function (properties, fieldType) {
var _this = this;
if (fieldType === void 0) { fieldType = "SP.Field"; }
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": fieldType },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
field: _this,
};
});
};
/**
* Delete this fields
*
*/
Field.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Sets the value of the ShowInDisplayForm property for this field.
*/
Field.prototype.setShowInDisplayForm = function (show) {
return this.clone(Field, "setshowindisplayform(" + show + ")").postCore();
};
/**
* Sets the value of the ShowInEditForm property for this field.
*/
Field.prototype.setShowInEditForm = function (show) {
return this.clone(Field, "setshowineditform(" + show + ")").postCore();
};
/**
* Sets the value of the ShowInNewForm property for this field.
*/
Field.prototype.setShowInNewForm = function (show) {
return this.clone(Field, "setshowinnewform(" + show + ")").postCore();
};
return Field;
}(SharePointQueryableInstance));
/**
* Describes a collection of Field objects
*
*/
var Forms = /** @class */ (function (_super) {
tslib_1.__extends(Forms, _super);
/**
* Creates a new instance of the Fields class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Forms(baseUrl, path) {
if (path === void 0) { path = "forms"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a form by id
*
* @param id The guid id of the item to retrieve
*/
Forms.prototype.getById = function (id) {
var i = new Form(this);
i.concat("('" + id + "')");
return i;
};
return Forms;
}(SharePointQueryableCollection));
/**
* Describes a single of Form instance
*
*/
var Form = /** @class */ (function (_super) {
tslib_1.__extends(Form, _super);
function Form() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Form;
}(SharePointQueryableInstance));
/**
* Describes a collection of webhook subscriptions
*
*/
var Subscriptions = /** @class */ (function (_super) {
tslib_1.__extends(Subscriptions, _super);
/**
* Creates a new instance of the Subscriptions class
*
* @param baseUrl - The url or SharePointQueryable which forms the parent of this webhook subscriptions collection
*/
function Subscriptions(baseUrl, path) {
if (path === void 0) { path = "subscriptions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Returns all the webhook subscriptions or the specified webhook subscription
*
* @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions
*/
Subscriptions.prototype.getById = function (subscriptionId) {
var subscription = new Subscription(this);
subscription.concat("('" + subscriptionId + "')");
return subscription;
};
/**
* Creates a new webhook subscription
*
* @param notificationUrl The url to receive the notifications
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
* @param clientState A client specific string (defaults to pnp-js-core-subscription when omitted)
*/
Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) {
var _this = this;
var postBody = JSON.stringify({
"clientState": clientState || "pnp-js-core-subscription",
"expirationDateTime": expirationDate,
"notificationUrl": notificationUrl,
"resource": this.toUrl(),
});
return this.postCore({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (result) {
return { data: result, subscription: _this.getById(result.id) };
});
};
return Subscriptions;
}(SharePointQueryableCollection));
/**
* Describes a single webhook subscription instance
*
*/
var Subscription = /** @class */ (function (_super) {
tslib_1.__extends(Subscription, _super);
function Subscription() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Renews this webhook subscription
*
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
*/
Subscription.prototype.update = function (expirationDate) {
var _this = this;
var postBody = JSON.stringify({
"expirationDateTime": expirationDate,
});
return this.patchCore({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (data) {
return { data: data, subscription: _this };
});
};
/**
* Removes this webhook subscription
*
*/
Subscription.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return Subscription;
}(SharePointQueryableInstance));
/**
* Describes a collection of user custom actions
*
*/
var UserCustomActions = /** @class */ (function (_super) {
tslib_1.__extends(UserCustomActions, _super);
/**
* Creates a new instance of the UserCustomActions class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this user custom actions collection
*/
function UserCustomActions(baseUrl, path) {
if (path === void 0) { path = "usercustomactions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Returns the user custom action with the specified id
*
* @param id The GUID id of the user custom action to retrieve
*/
UserCustomActions.prototype.getById = function (id) {
var uca = new UserCustomAction(this);
uca.concat("('" + id + "')");
return uca;
};
/**
* Creates a user custom action
*
* @param properties The information object of property names and values which define the new user custom action
*
*/
UserCustomActions.prototype.add = function (properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties));
return this.postCore({ body: postBody }).then(function (data) {
return {
action: _this.getById(data.Id),
data: data,
};
});
};
/**
* Deletes all user custom actions in the collection
*
*/
UserCustomActions.prototype.clear = function () {
return this.clone(UserCustomActions, "clear").postCore();
};
return UserCustomActions;
}(SharePointQueryableCollection));
/**
* Describes a single user custom action
*
*/
var UserCustomAction = /** @class */ (function (_super) {
tslib_1.__extends(UserCustomAction, _super);
function UserCustomAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Updates this user custom action with the supplied properties
*
* @param properties An information object of property names and values to update for this user custom action
*/
UserCustomAction.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": "SP.UserCustomAction" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
action: _this,
data: data,
};
});
};
/**
* Removes this user custom action
*
*/
UserCustomAction.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return UserCustomAction;
}(SharePointQueryableInstance));
/**
* Describes a collection of List objects
*
*/
var Lists = /** @class */ (function (_super) {
tslib_1.__extends(Lists, _super);
/**
* Creates a new instance of the Lists class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Lists(baseUrl, path) {
if (path === void 0) { path = "lists"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a list from the collection by title
*
* @param title The title of the list
*/
Lists.prototype.getByTitle = function (title) {
return new List(this, "getByTitle('" + title + "')");
};
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the list (GUID)
*/
Lists.prototype.getById = function (id) {
var list = new List(this);
list.concat("('" + id + "')");
return list;
};
/**
* Adds a new list to the collection
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body
*/
Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var addSettings = common.extend({
"AllowContentTypes": enableContentTypes,
"BaseTemplate": template,
"ContentTypesEnabled": enableContentTypes,
"Description": description,
"Title": title,
"__metadata": { "type": "SP.List" },
}, additionalSettings);
return this.postCore({ body: JSON.stringify(addSettings) }).then(function (data) {
return { data: data, list: _this.getByTitle(addSettings.Title) };
});
};
/**
* Ensures that the specified list exists in the collection (note: this method not supported for batching)
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body or used to update an existing list
*/
Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
if (this.hasBatch) {
throw new NotSupportedInBatchException("The ensure list method");
}
return new Promise(function (resolve, reject) {
var addOrUpdateSettings = common.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true);
var list = _this.getByTitle(addOrUpdateSettings.Title);
list.get().then(function (_) {
list.update(addOrUpdateSettings).then(function (d) {
resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
}).catch(function (_) {
_this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) {
resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
});
});
};
/**
* Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages.
*/
Lists.prototype.ensureSiteAssetsLibrary = function () {
return this.clone(Lists, "ensuresiteassetslibrary").postCore().then(function (json) {
return new List(spExtractODataId(json));
});
};
/**
* Gets a list that is the default location for wiki pages.
*/
Lists.prototype.ensureSitePagesLibrary = function () {
return this.clone(Lists, "ensuresitepageslibrary").postCore().then(function (json) {
return new List(spExtractODataId(json));
});
};
return Lists;
}(SharePointQueryableCollection));
/**
* Describes a single List instance
*
*/
var List = /** @class */ (function (_super) {
tslib_1.__extends(List, _super);
function List() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(List.prototype, "contentTypes", {
/**
* Gets the content types in this list
*
*/
get: function () {
return new ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "items", {
/**
* Gets the items in this list
*
*/
get: function () {
return new Items(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "views", {
/**
* Gets the views in this list
*
*/
get: function () {
return new Views(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "fields", {
/**
* Gets the fields in this list
*
*/
get: function () {
return new Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "forms", {
/**
* Gets the forms in this list
*
*/
get: function () {
return new Forms(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "defaultView", {
/**
* Gets the default view of this list
*
*/
get: function () {
return new View(this, "DefaultView");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "userCustomActions", {
/**
* Get all custom actions on a site collection
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions of this list
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "eventReceivers", {
/**
* Gets the event receivers attached to this list
*
*/
get: function () {
return new SharePointQueryableCollection(this, "EventReceivers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "relatedFields", {
/**
* Gets the related fields of this list
*
*/
get: function () {
return new SharePointQueryable(this, "getRelatedFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "informationRightsManagementSettings", {
/**
* Gets the IRM settings for this list
*
*/
get: function () {
return new SharePointQueryable(this, "InformationRightsManagementSettings");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "subscriptions", {
/**
* Gets the webhook subscriptions of this list
*
*/
get: function () {
return new Subscriptions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "rootFolder", {
/**
* The root folder of the list
*/
get: function () {
return new Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
/**
* Gets a view by view guid id
*
*/
List.prototype.getView = function (viewId) {
return new View(this, "getView('" + viewId + "')");
};
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
*/
/* tslint:disable no-string-literal */
List.prototype.update = function (properties, eTag) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": "SP.List" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retList = _this;
if (properties.hasOwnProperty("Title")) {
retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')");
}
return {
data: data,
list: retList,
};
});
};
/* tslint:enable */
/**
* Delete this list
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
List.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query.
*/
List.prototype.getChanges = function (query) {
return this.clone(List, "getchanges").postCore({
body: JSON.stringify({ "query": common.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }),
});
};
/**
* Returns a collection of items from the list based on the specified query.
*
* @param CamlQuery The Query schema of Collaborative Application Markup
* Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation
* to define queries against list data.
* see:
*
* https://msdn.microsoft.com/en-us/library/office/ms467521.aspx
*
* @param expands A URI with a $expand System Query Option indicates that Entries associated with
* the Entry or Collection of Entries identified by the Resource Path
* section of the URI must be represented inline (i.e. eagerly loaded).
* see:
*
* https://msdn.microsoft.com/en-us/library/office/fp142385.aspx
*
* http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption
*/
List.prototype.getItemsByCAMLQuery = function (query) {
var expands = [];
for (var _i = 1; _i < arguments.length; _i++) {
expands[_i - 1] = arguments[_i];
}
var q = this.clone(List, "getitems");
return q.expand.apply(q, expands).postCore({
body: JSON.stringify({ "query": common.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }),
});
};
/**
* See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx
*/
List.prototype.getListItemChangesSinceToken = function (query) {
return this.clone(List, "getlistitemchangessincetoken").postCore({
body: JSON.stringify({ "query": common.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }),
}, { parse: function (r) { return r.text(); } });
};
/**
* Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
List.prototype.recycle = function () {
return this.clone(List, "recycle").postCore().then(function (data) {
if (data.hasOwnProperty("Recycle")) {
return data.Recycle;
}
else {
return data;
}
});
};
/**
* Renders list data based on the view xml provided
*/
List.prototype.renderListData = function (viewXml) {
var q = this.clone(List, "renderlistdata(@viewXml)");
q.query.add("@viewXml", "'" + viewXml + "'");
return q.postCore().then(function (data) {
// data will be a string, so we parse it again
data = JSON.parse(data);
if (data.hasOwnProperty("RenderListData")) {
return data.RenderListData;
}
else {
return data;
}
});
};
/**
* Returns the data for the specified query view
*
* @param parameters The parameters to be used to render list data as JSON string.
* @param overrideParameters The parameters that are used to override and extend the regular SPRenderListDataParameters.
*/
List.prototype.renderListDataAsStream = function (parameters, overrideParameters) {
if (overrideParameters === void 0) { overrideParameters = null; }
var postBody = {
overrideParameters: common.extend({
"__metadata": { "type": "SP.RenderListDataOverrideParameters" },
}, overrideParameters),
parameters: common.extend({
"__metadata": { "type": "SP.RenderListDataParameters" },
}, parameters),
};
return this.clone(List, "RenderListDataAsStream", true).postCore({
body: JSON.stringify(postBody),
});
};
/**
* Gets the field values and field schema attributes for a list item.
*/
List.prototype.renderListFormData = function (itemId, formId, mode) {
return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')").postCore().then(function (data) {
// data will be a string, so we parse it again
data = JSON.parse(data);
if (data.hasOwnProperty("ListData")) {
return data.ListData;
}
else {
return data;
}
});
};
/**
* Reserves a list item ID for idempotent list item creation.
*/
List.prototype.reserveListItemId = function () {
return this.clone(List, "reservelistitemid").postCore().then(function (data) {
if (data.hasOwnProperty("ReserveListItemId")) {
return data.ReserveListItemId;
}
else {
return data;
}
});
};
/**
* Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching.
*
*/
List.prototype.getListItemEntityTypeFullName = function () {
return this.clone(List, null, false).select("ListItemEntityTypeFullName").get().then(function (o) { return o.ListItemEntityTypeFullName; });
};
return List;
}(SharePointQueryableSecurable));
/**
* Describes a collection of Item objects
*
*/
var Items = /** @class */ (function (_super) {
tslib_1.__extends(Items, _super);
/**
* Creates a new instance of the Items class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Items(baseUrl, path) {
if (path === void 0) { path = "items"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets an Item by id
*
* @param id The integer id of the item to retrieve
*/
Items.prototype.getById = function (id) {
var i = new Item(this);
i.concat("(" + id + ")");
return i;
};
/**
* Gets BCS Item by string id
*
* @param stringId The string id of the BCS item to retrieve
*/
Items.prototype.getItemByStringId = function (stringId) {
// creates an item with the parent list path and append out method call
return new Item(this.parentUrl, "getItemByStringId('" + stringId + "')");
};
/**
* Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6)
*
* @param skip The starting id where the page should start, use with top to specify pages
* @param reverse It true the PagedPrev=true parameter is added allowing backwards navigation in the collection
*/
Items.prototype.skip = function (skip, reverse) {
if (reverse === void 0) { reverse = false; }
if (reverse) {
this._query.add("$skiptoken", encodeURIComponent("Paged=TRUE&PagedPrev=TRUE&p_ID=" + skip));
}
else {
this._query.add("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip));
}
return this;
};
/**
* Gets a collection designed to aid in paging through data
*
*/
Items.prototype.getPaged = function () {
return this.get(new PagedItemCollectionParser(this));
};
/**
* Gets all the items in a list, regardless of count. Does not support batching or caching
*
* @param requestSize Number of items to return in each request (Default: 2000)
*/
Items.prototype.getAll = function (requestSize) {
var _this = this;
if (requestSize === void 0) { requestSize = 2000; }
logging.Logger.write("Calling items.getAll should be done sparingly. Ensure this is the correct choice. If you are unsure, it is not.", 2 /* Warning */);
// this will be used for the actual query
// and we set no metadata here to try and reduce traffic
var items = new Items(this, "").top(requestSize).configure({
headers: {
"Accept": "application/json;odata=nometadata",
},
});
// let's copy over the odata query params that can be applied
// $top - allow setting the page size this way (override what we did above)
// $select - allow picking the return fields (good behavior)
// $filter - allow setting a filter, though this may fail due for large lists
this.query.getKeys()
.filter(function (k) { return /^\$select$|^\$filter$|^\$top$|^\$expand$/.test(k.toLowerCase()); })
.reduce(function (i, k) {
i.query.add(k, _this.query.get(k));
return i;
}, items);
// give back the promise
return new Promise(function (resolve, reject) {
// this will eventually hold the items we return
var itemsCollector = [];
// action that will gather up our results recursively
var gatherer = function (last) {
// collect that set of results
[].push.apply(itemsCollector, last.results);
// if we have more, repeat - otherwise resolve with the collected items
if (last.hasNext) {
last.getNext().then(gatherer).catch(reject);
}
else {
resolve(itemsCollector);
}
};
// start the cycle
items.getPaged().then(gatherer).catch(reject);
});
};
/**
* Adds a new item to the collection
*
* @param properties The new items's properties
* @param listItemEntityTypeFullName The type name of the list's entities
*/
Items.prototype.add = function (properties, listItemEntityTypeFullName) {
var _this = this;
if (properties === void 0) { properties = {}; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
var removeDependency = this.addBatchDependency();
return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": listItemEntityType },
}, properties));
var promise = _this.clone(Items, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
item: _this.getById(data.Id),
};
});
removeDependency();
return promise;
});
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.getParent(List).getListItemEntityTypeFullName();
};
return Items;
}(SharePointQueryableCollection));
/**
* Descrines a single Item instance
*
*/
var Item = /** @class */ (function (_super) {
tslib_1.__extends(Item, _super);
function Item() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Item.prototype, "attachmentFiles", {
/**
* Gets the set of attachments for this item
*
*/
get: function () {
return new AttachmentFiles(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "contentType", {
/**
* Gets the content type for this item
*
*/
get: function () {
return new ContentType(this, "ContentType");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions for the item
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", {
/**
* Gets the effective base permissions for the item in a UI context
*
*/
get: function () {
return new SharePointQueryable(this, "EffectiveBasePermissionsForUI");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsHTML", {
/**
* Gets the field values for this list item in their HTML representation
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesAsHTML");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsText", {
/**
* Gets the field values for this list item in their text representation
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesAsText");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesForEdit", {
/**
* Gets the field values for this list item for use in editing controls
*
*/
get: function () {
return new SharePointQueryableInstance(this, "FieldValuesForEdit");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "folder", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new Folder(this, "folder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "file", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new File(this, "file");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "versions", {
/**
* Gets the collection of versions associated with this item
*/
get: function () {
return new ItemVersions(this);
},
enumerable: true,
configurable: true
});
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
* @param listItemEntityTypeFullName The type name of the list's entities
*/
Item.prototype.update = function (properties, eTag, listItemEntityTypeFullName) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
return new Promise(function (resolve, reject) {
var removeDependency = _this.addBatchDependency();
return _this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": listItemEntityType },
}, properties));
removeDependency();
return _this.postCore({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}, new ItemUpdatedParser()).then(function (data) {
resolve({
data: data,
item: _this,
});
});
}).catch(function (e) { return reject(e); });
});
};
/**
* Delete this item
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Item.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Item.prototype.recycle = function () {
return this.clone(Item, "recycle").postCore();
};
/**
* Gets a string representation of the full URL to the WOPI frame.
* If there is no associated WOPI application, or no associated action, an empty string is returned.
*
* @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview
*/
Item.prototype.getWopiFrameUrl = function (action) {
if (action === void 0) { action = 0; }
var i = this.clone(Item, "getWOPIFrameUrl(@action)");
i._query.add("@action", action);
return i.postCore().then(function (data) {
// handle verbose mode
if (data.hasOwnProperty("GetWOPIFrameUrl")) {
return data.GetWOPIFrameUrl;
}
return data;
});
};
/**
* Validates and sets the values of the specified collection of fields for the list item.
*
* @param formValues The fields to change and their new values.
* @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false.
*/
Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) {
if (newDocumentUpdate === void 0) { newDocumentUpdate = false; }
return this.clone(Item, "validateupdatelistitem").postCore({
body: JSON.stringify({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }),
});
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Item.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.getParent(List, this.parentUrl.substr(0, this.parentUrl.lastIndexOf("/"))).getListItemEntityTypeFullName();
};
return Item;
}(SharePointQueryableShareableItem));
/**
* Describes a collection of Version objects
*
*/
var ItemVersions = /** @class */ (function (_super) {
tslib_1.__extends(ItemVersions, _super);
/**
* Creates a new instance of the File class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function ItemVersions(baseUrl, path) {
if (path === void 0) { path = "versions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
ItemVersions.prototype.getById = function (versionId) {
var v = new ItemVersion(this);
v.concat("(" + versionId + ")");
return v;
};
return ItemVersions;
}(SharePointQueryableCollection));
/**
* Describes a single Version instance
*
*/
var ItemVersion = /** @class */ (function (_super) {
tslib_1.__extends(ItemVersion, _super);
function ItemVersion() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
ItemVersion.prototype.delete = function () {
return this.postCore({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return ItemVersion;
}(SharePointQueryableInstance));
/**
* Provides paging functionality for list items
*/
var PagedItemCollection = /** @class */ (function () {
function PagedItemCollection(parent, nextUrl, results) {
this.parent = parent;
this.nextUrl = nextUrl;
this.results = results;
}
Object.defineProperty(PagedItemCollection.prototype, "hasNext", {
/**
* If true there are more results available in the set, otherwise there are not
*/
get: function () {
return typeof this.nextUrl === "string" && this.nextUrl.length > 0;
},
enumerable: true,
configurable: true
});
/**
* Gets the next set of results, or resolves to null if no results are available
*/
PagedItemCollection.prototype.getNext = function () {
if (this.hasNext) {
var items = new Items(this.nextUrl, null).configureFrom(this.parent);
return items.getPaged();
}
return new Promise(function (r) { return r(null); });
};
return PagedItemCollection;
}());
var PagedItemCollectionParser = /** @class */ (function (_super) {
tslib_1.__extends(PagedItemCollectionParser, _super);
function PagedItemCollectionParser(_parent) {
var _this = _super.call(this) || this;
_this._parent = _parent;
return _this;
}
PagedItemCollectionParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
r.json().then(function (json) {
var nextUrl = json.hasOwnProperty("d") && json.d.hasOwnProperty("__next") ? json.d.__next : json["odata.nextLink"];
resolve(new PagedItemCollection(_this._parent, nextUrl, _this.parseODataJSON(json)));
});
}
});
};
return PagedItemCollectionParser;
}(odata.ODataParserBase));
var ItemUpdatedParser = /** @class */ (function (_super) {
tslib_1.__extends(ItemUpdatedParser, _super);
function ItemUpdatedParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
ItemUpdatedParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
resolve({
"odata.etag": r.headers.get("etag"),
});
}
});
};
return ItemUpdatedParser;
}(odata.ODataParserBase));
/**
* Describes a collection of File objects
*
*/
var Files = /** @class */ (function (_super) {
tslib_1.__extends(Files, _super);
/**
* Creates a new instance of the Files class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Files(baseUrl, path) {
if (path === void 0) { path = "files"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a File by filename
*
* @param name The name of the file, including extension.
*/
Files.prototype.getByName = function (name) {
var f = new File(this);
f.concat("('" + name + "')");
return f;
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The file contents blob.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @returns The new File and the raw response.
*/
Files.prototype.add = function (url, content, shouldOverWrite) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return new Files(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')")
.postCore({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(url),
};
});
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The Blob file content to add
* @param progress A callback function which can be used to track the progress of the upload
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
* @returns The new File and the raw response.
*/
Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
if (chunkSize === void 0) { chunkSize = 10485760; }
var adder = this.clone(Files, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')", false);
return adder.postCore()
.then(function () { return _this.getByName(url); })
.then(function (file) { return file.setContentChunked(content, progress, chunkSize); });
};
/**
* Adds a ghosted file to an existing list or document library. Not supported for batching.
*
* @param fileUrl The server-relative url where you want to save the file.
* @param templateFileType The type of use to create the file.
* @returns The template file that was added and the raw response.
*/
Files.prototype.addTemplateFile = function (fileUrl, templateFileType) {
var _this = this;
return this.clone(Files, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")", false)
.postCore().then(function (response) {
return {
data: response,
file: _this.getByName(fileUrl),
};
});
};
return Files;
}(SharePointQueryableCollection));
/**
* Describes a single File instance
*
*/
var File = /** @class */ (function (_super) {
tslib_1.__extends(File, _super);
function File() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(File.prototype, "listItemAllFields", {
/**
* Gets a value that specifies the list item field values for the list item corresponding to the file.
*
*/
get: function () {
return new SharePointQueryableCollection(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(File.prototype, "versions", {
/**
* Gets a collection of versions
*
*/
get: function () {
return new Versions(this);
},
enumerable: true,
configurable: true
});
/**
* Approves the file submitted for content approval with the specified comment.
* Only documents in lists that are enabled for content approval can be approved.
*
* @param comment The comment for the approval.
*/
File.prototype.approve = function (comment) {
if (comment === void 0) { comment = ""; }
return this.clone(File, "approve(comment='" + comment + "')").postCore();
};
/**
* Stops the chunk upload session without saving the uploaded data. Does not support batching.
* If the file doesn’t already exist in the library, the partially uploaded file will be deleted.
* Use this in response to user action (as in a request to cancel an upload) or an error or exception.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
*/
File.prototype.cancelUpload = function (uploadId) {
return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).postCore();
};
/**
* Checks the file in to a document library based on the check-in type.
*
* @param comment A comment for the check-in. Its length must be <= 1023.
* @param checkinType The check-in type for the file.
*/
File.prototype.checkin = function (comment, checkinType) {
if (comment === void 0) { comment = ""; }
if (checkinType === void 0) { checkinType = exports.CheckinType.Major; }
if (comment.length > 1023) {
throw new MaxCommentLengthException();
}
return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")").postCore();
};
/**
* Checks out the file from a document library.
*/
File.prototype.checkout = function () {
return this.clone(File, "checkout").postCore();
};
/**
* Copies the file to the destination url.
*
* @param url The absolute url or server relative url of the destination file path to copy to.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten?
*/
File.prototype.copyTo = function (url, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")").postCore();
};
/**
* Delete this file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
File.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(File, null).postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Denies approval for a file that was submitted for content approval.
* Only documents in lists that are enabled for content approval can be denied.
*
* @param comment The comment for the denial.
*/
File.prototype.deny = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw new MaxCommentLengthException();
}
return this.clone(File, "deny(comment='" + comment + "')").postCore();
};
/**
* Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view.
* An exception is thrown if the file is not an ASPX page.
*
* @param scope The WebPartsPersonalizationScope view on the Web Parts page.
*/
File.prototype.getLimitedWebPartManager = function (scope) {
if (scope === void 0) { scope = exports.WebPartsPersonalizationScope.Shared; }
return new LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")");
};
/**
* Moves the file to the specified destination url.
*
* @param url The absolute url or server relative url of the destination file path to move to.
* @param moveOperations The bitwise MoveOperations value for how to move the file.
*/
File.prototype.moveTo = function (url, moveOperations) {
if (moveOperations === void 0) { moveOperations = exports.MoveOperations.Overwrite; }
return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")").postCore();
};
/**
* Submits the file for content approval with the specified comment.
*
* @param comment The comment for the published file. Its length must be <= 1023.
*/
File.prototype.publish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw new MaxCommentLengthException();
}
return this.clone(File, "publish(comment='" + comment + "')").postCore();
};
/**
* Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*
* @returns The GUID of the recycled file.
*/
File.prototype.recycle = function () {
return this.clone(File, "recycle").postCore();
};
/**
* Reverts an existing checkout for the file.
*
*/
File.prototype.undoCheckout = function () {
return this.clone(File, "undoCheckout").postCore();
};
/**
* Removes the file from content approval or unpublish a major version.
*
* @param comment The comment for the unpublish operation. Its length must be <= 1023.
*/
File.prototype.unpublish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw new MaxCommentLengthException();
}
return this.clone(File, "unpublish(comment='" + comment + "')").postCore();
};
/**
* Gets the contents of the file as text. Not supported in batching.
*
*/
File.prototype.getText = function () {
return this.clone(File, "$value", false).get(new odata.TextParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching.
*
*/
File.prototype.getBlob = function () {
return this.clone(File, "$value", false).get(new odata.BlobParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getBuffer = function () {
return this.clone(File, "$value", false).get(new odata.BufferParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getJSON = function () {
return this.clone(File, "$value", false).get(new odata.JSONParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Sets the content of a file, for large files use setContentChunked. Not supported in batching.
*
* @param content The file content
*
*/
File.prototype.setContent = function (content) {
var _this = this;
return this.clone(File, "$value", false).postCore({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new File(_this); });
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
File.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return common.extend(new Item(spGetEntityUrl(d)), d);
});
};
/**
* Sets the contents of a file using a chunked upload approach. Not supported in batching.
*
* @param file The file to upload
* @param progress A callback function which can be used to track the progress of the upload
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
*/
File.prototype.setContentChunked = function (file, progress, chunkSize) {
var _this = this;
if (chunkSize === void 0) { chunkSize = 10485760; }
if (typeof progress === "undefined") {
progress = function () { return null; };
}
var fileSize = file.size;
var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0);
var uploadId = common.getGUID();
// start the chain with the first fragment
progress({ uploadId: uploadId, blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount });
var chain = this.startUpload(uploadId, file.slice(0, chunkSize));
var _loop_1 = function (i) {
chain = chain.then(function (pointer) {
progress({ uploadId: uploadId, blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount });
return _this.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize));
});
};
// skip the first and last blocks
for (var i = 2; i < blockCount; i++) {
_loop_1(i);
}
return chain.then(function (pointer) {
progress({ uploadId: uploadId, blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount });
return _this.finishUpload(uploadId, pointer, file.slice(pointer));
});
};
/**
* Starts a new chunk upload session and uploads the first fragment.
* The current file content is not changed when this method completes.
* The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream.
* The upload session ends either when you use the CancelUpload method or when you successfully
* complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods.
* The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes,
* so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.startUpload = function (uploadId, fragment) {
return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')", false)
.postCore({ body: fragment })
.then(function (n) {
// When OData=verbose the payload has the following shape:
// { StartUpload: "10485760" }
if (typeof n === "object") {
n = n.StartUpload;
}
return parseFloat(n);
});
};
/**
* Continues the chunk upload session with an additional fragment.
* The current file content is not changed.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.continueUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")", false)
.postCore({ body: fragment })
.then(function (n) {
// When OData=verbose the payload has the following shape:
// { ContinueUpload: "20971520" }
if (typeof n === "object") {
n = n.ContinueUpload;
}
return parseFloat(n);
});
};
/**
* Uploads the last file fragment and commits the file. The current file content is changed when this method completes.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The newly uploaded file.
*/
File.prototype.finishUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")", false)
.postCore({ body: fragment })
.then(function (response) {
return {
data: response,
file: new File(response.ServerRelativeUrl),
};
});
};
return File;
}(SharePointQueryableShareableFile));
/**
* Describes a collection of Version objects
*
*/
var Versions = /** @class */ (function (_super) {
tslib_1.__extends(Versions, _super);
/**
* Creates a new instance of the File class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Versions(baseUrl, path) {
if (path === void 0) { path = "versions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
Versions.prototype.getById = function (versionId) {
var v = new Version(this);
v.concat("(" + versionId + ")");
return v;
};
/**
* Deletes all the file version objects in the collection.
*
*/
Versions.prototype.deleteAll = function () {
return new Versions(this, "deleteAll").postCore();
};
/**
* Deletes the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.deleteById = function (versionId) {
return this.clone(Versions, "deleteById(vid=" + versionId + ")").postCore();
};
/**
* Recycles the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.recycleByID = function (versionId) {
return this.clone(Versions, "recycleByID(vid=" + versionId + ")").postCore();
};
/**
* Deletes the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.deleteByLabel = function (label) {
return this.clone(Versions, "deleteByLabel(versionlabel='" + label + "')").postCore();
};
/**
* Recycles the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.recycleByLabel = function (label) {
return this.clone(Versions, "recycleByLabel(versionlabel='" + label + "')").postCore();
};
/**
* Creates a new file version from the file specified by the version label.
*
* @param label The version label of the file version to restore, for example: 1.2
*/
Versions.prototype.restoreByLabel = function (label) {
return this.clone(Versions, "restoreByLabel(versionlabel='" + label + "')").postCore();
};
return Versions;
}(SharePointQueryableCollection));
/**
* Describes a single Version instance
*
*/
var Version = /** @class */ (function (_super) {
tslib_1.__extends(Version, _super);
function Version() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Version.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.postCore({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
return Version;
}(SharePointQueryableInstance));
(function (CheckinType) {
CheckinType[CheckinType["Minor"] = 0] = "Minor";
CheckinType[CheckinType["Major"] = 1] = "Major";
CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite";
})(exports.CheckinType || (exports.CheckinType = {}));
(function (WebPartsPersonalizationScope) {
WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User";
WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared";
})(exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {}));
(function (MoveOperations) {
MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite";
MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets";
})(exports.MoveOperations || (exports.MoveOperations = {}));
(function (TemplateFileType) {
TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage";
TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage";
TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage";
TemplateFileType[TemplateFileType["ClientSidePage"] = 3] = "ClientSidePage";
})(exports.TemplateFileType || (exports.TemplateFileType = {}));
/**
* Represents an app catalog
*/
var AppCatalog = /** @class */ (function (_super) {
tslib_1.__extends(AppCatalog, _super);
function AppCatalog(baseUrl, path) {
if (path === void 0) { path = "_api/web/tenantappcatalog/AvailableApps"; }
var _this = this;
// we need to handle the case of getting created from something that already has "_api/..." or does not
var candidateUrl = "";
if (typeof baseUrl === "string") {
candidateUrl = baseUrl;
}
else if (typeof baseUrl !== "undefined") {
candidateUrl = baseUrl.toUrl();
}
_this = _super.call(this, extractWebUrl(candidateUrl), path) || this;
return _this;
}
/**
* Get details of specific app from the app catalog
* @param id - Specify the guid of the app
*/
AppCatalog.prototype.getAppById = function (id) {
return new App(this, "getById('" + id + "')");
};
/**
* Uploads an app package. Not supported for batching
*
* @param filename Filename to create.
* @param content app package data (eg: the .app or .sppkg file).
* @param shouldOverWrite Should an app with the same name in the same location be overwritten? (default: true)
* @returns Promise<AppAddResult>
*/
AppCatalog.prototype.add = function (filename, content, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
// you don't add to the availableapps collection
var adder = new AppCatalog(extractWebUrl(this.toUrl()), "_api/web/tenantappcatalog/add(overwrite=" + shouldOverWrite + ",url='" + filename + "')");
return adder.postCore({
body: content,
}).then(function (r) {
return {
data: r,
file: new File(spExtractODataId(r)),
};
});
};
return AppCatalog;
}(SharePointQueryableCollection));
/**
* Represents the actions you can preform on a given app within the catalog
*/
var App = /** @class */ (function (_super) {
tslib_1.__extends(App, _super);
function App() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* This method deploys an app on the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.deploy = function () {
return this.clone(App, "Deploy").postCore();
};
/**
* This method retracts a deployed app on the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.retract = function () {
return this.clone(App, "Retract").postCore();
};
/**
* This method allows an app which is already deployed to be installed on a web
*/
App.prototype.install = function () {
return this.clone(App, "Install").postCore();
};
/**
* This method allows an app which is already insatlled to be uninstalled on a web
*/
App.prototype.uninstall = function () {
return this.clone(App, "Uninstall").postCore();
};
/**
* This method allows an app which is already insatlled to be upgraded on a web
*/
App.prototype.upgrade = function () {
return this.clone(App, "Upgrade").postCore();
};
/**
* This method removes an app from the app catalog. It must be called in the context
* of the tenant app catalog web or it will fail.
*/
App.prototype.remove = function () {
return this.clone(App, "Remove").postCore();
};
return App;
}(SharePointQueryableInstance));
/**
* Gets the next order value 1 based for the provided collection
*
* @param collection Collection of orderable things
*/
function getNextOrder(collection) {
if (collection.length < 1) {
return 1;
}
return Math.max.apply(null, collection.map(function (i) { return i.order; })) + 1;
}
/**
* After https://stackoverflow.com/questions/273789/is-there-a-version-of-javascripts-string-indexof-that-allows-for-regular-expr/274094#274094
*
* @param this Types the called context this to a string in which the search will be conducted
* @param regex A regex or string to match
* @param startpos A starting position from which the search will begin
*/
function regexIndexOf(regex, startpos) {
if (startpos === void 0) { startpos = 0; }
var indexOf = this.substring(startpos).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos)) : indexOf;
}
/**
* Gets an attribute value from an html string block
*
* @param html HTML to search
* @param attrName The name of the attribute to find
*/
function getAttrValueFromString(html, attrName) {
var reg = new RegExp(attrName + "=\"([^\"]*?)\"", "i");
var match = reg.exec(html);
return match.length > 0 ? match[1] : null;
}
/**
* Finds bounded blocks of markup bounded by divs, ensuring to match the ending div even with nested divs in the interstitial markup
*
* @param html HTML to search
* @param boundaryStartPattern The starting pattern to find, typically a div with attribute
* @param collector A func to take the found block and provide a way to form it into a useful return that is added into the return array
*/
function getBoundedDivMarkup(html, boundaryStartPattern, collector) {
var blocks = [];
if (typeof html === "undefined" || html === null) {
return blocks;
}
// remove some extra whitespace if present
var cleanedHtml = html.replace(/[\t\r\n]/g, "");
// find the first div
var startIndex = regexIndexOf.call(cleanedHtml, boundaryStartPattern);
if (startIndex < 0) {
// we found no blocks in the supplied html
return blocks;
}
// this loop finds each of the blocks
while (startIndex > -1) {
// we have one open div counting from the one found above using boundaryStartPattern so we need to ensure we find it's close
var openCounter = 1;
var searchIndex = startIndex + 1;
var nextDivOpen = -1;
var nextCloseDiv = -1;
// this loop finds the </div> tag that matches the opening of the control
while (true) {
// find both the next opening and closing div tags from our current searching index
nextDivOpen = regexIndexOf.call(cleanedHtml, /<div[^>]*>/i, searchIndex);
nextCloseDiv = regexIndexOf.call(cleanedHtml, /<\/div>/i, searchIndex);
if (nextDivOpen < 0) {
// we have no more opening divs, just set this to simplify checks below
nextDivOpen = cleanedHtml.length + 1;
}
// determine which we found first, then increment or decrement our counter
// and set the location to begin searching again
if (nextDivOpen < nextCloseDiv) {
openCounter++;
searchIndex = nextDivOpen + 1;
}
else if (nextCloseDiv < nextDivOpen) {
openCounter--;
searchIndex = nextCloseDiv + 1;
}
// once we have no open divs back to the level of the opening control div
// meaning we have all of the markup we intended to find
if (openCounter === 0) {
// get the bounded markup, +6 is the size of the ending </div> tag
var markup = cleanedHtml.substring(startIndex, nextCloseDiv + 6).trim();
// save the control data we found to the array
blocks.push(collector(markup));
// get out of our while loop
break;
}
if (openCounter > 1000 || openCounter < 0) {
// this is an arbitrary cut-off but likely we will not have 1000 nested divs
// something has gone wrong above and we are probably stuck in our while loop
// let's get out of our while loop and not hang everything
throw new Error("getBoundedDivMarkup exceeded depth parameters.");
}
}
// get the start of the next control
startIndex = regexIndexOf.call(cleanedHtml, boundaryStartPattern, nextCloseDiv);
}
return blocks;
}
/**
* Normalizes the order value for all the sections, columns, and controls to be 1 based and stepped (1, 2, 3...)
*
* @param collection The collection to normalize
*/
function reindex(collection) {
for (var i = 0; i < collection.length; i++) {
collection[i].order = i + 1;
if (collection[i].hasOwnProperty("columns")) {
reindex(collection[i].columns);
}
else if (collection[i].hasOwnProperty("controls")) {
reindex(collection[i].controls);
}
}
}
/**
* Represents the data and methods associated with client side "modern" pages
*/
var ClientSidePage = /** @class */ (function (_super) {
tslib_1.__extends(ClientSidePage, _super);
/**
* Creates a new instance of the ClientSidePage class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this web collection
* @param commentsDisabled Indicates if comments are disabled, not valid until load is called
*/
function ClientSidePage(file, sections, commentsDisabled) {
if (sections === void 0) { sections = []; }
if (commentsDisabled === void 0) { commentsDisabled = false; }
var _this = _super.call(this, file) || this;
_this.sections = sections;
_this.commentsDisabled = commentsDisabled;
return _this;
}
/**
* Creates a new blank page within the supplied library
*
* @param library The library in which to create the page
* @param pageName Filename of the page, such as "page.aspx"
* @param title The display title of the page
* @param pageLayoutType Layout type of the page to use
*/
ClientSidePage.create = function (library, pageName, title, pageLayoutType) {
if (pageLayoutType === void 0) { pageLayoutType = "Article"; }
// see if file exists, if not create it
return library.rootFolder.files.select("Name").filter("Name eq '" + pageName + "'").get().then(function (fs) {
if (fs.length > 0) {
throw new Error("A file with the name '" + pageName + "' already exists in the library '" + library.toUrl() + "'.");
}
// get our server relative path
return library.rootFolder.select("ServerRelativePath").get().then(function (path) {
var pageServerRelPath = common.combinePaths("/", path.ServerRelativePath.DecodedUrl, pageName);
// add the template file
return library.rootFolder.files.addTemplateFile(pageServerRelPath, exports.TemplateFileType.ClientSidePage).then(function (far) {
// get the item associated with the file
return far.file.getItem().then(function (i) {
// update the item to have the correct values to create the client side page
return i.update({
BannerImageUrl: {
Url: "/_layouts/15/images/sitepagethumbnail.png",
},
CanvasContent1: "",
ClientSideApplicationId: "b6917cb1-93a0-4b97-a84d-7cf49975d4ec",
ContentTypeId: "0x0101009D1CB255DA76424F860D91F20E6C4118",
PageLayoutType: pageLayoutType,
PromotedState: 0 /* NotPromoted */,
Title: title,
}).then(function (iar) { return new ClientSidePage(iar.item.file, iar.item.CommentsDisabled); });
});
});
});
});
};
/**
* Creates a new ClientSidePage instance from the provided html content string
*
* @param html HTML markup representing the page
*/
ClientSidePage.fromFile = function (file) {
var page = new ClientSidePage(file);
return page.load().then(function (_) { return page; });
};
/**
* Converts a json object to an escaped string appropriate for use in attributes when storing client-side controls
*
* @param json The json object to encode into a string
*/
ClientSidePage.jsonToEscapedString = function (json) {
return JSON.stringify(json)
.replace(/"/g, """)
.replace(/:/g, ":")
.replace(/{/g, "{")
.replace(/}/g, "}");
};
/**
* Converts an escaped string from a client-side control attribute to a json object
*
* @param escapedString
*/
ClientSidePage.escapedStringToJson = function (escapedString) {
return JSON.parse(escapedString
.replace(/"/g, "\"")
.replace(/:/g, ":")
.replace(/{/g, "{")
.replace(/}/g, "}"));
};
/**
* Add a section to this page
*/
ClientSidePage.prototype.addSection = function () {
var section = new CanvasSection(this, getNextOrder(this.sections));
this.sections.push(section);
return section;
};
/**
* Converts this page's content to html markup
*/
ClientSidePage.prototype.toHtml = function () {
// trigger reindex of the entire tree
reindex(this.sections);
var html = [];
html.push("<div>");
for (var i = 0; i < this.sections.length; i++) {
html.push(this.sections[i].toHtml());
}
html.push("</div>");
return html.join("");
};
/**
* Loads this page instance's content from the supplied html
*
* @param html html string representing the page's content
*/
ClientSidePage.prototype.fromHtml = function (html) {
var _this = this;
// reset sections
this.sections = [];
// gather our controls from the supplied html
getBoundedDivMarkup(html, /<div\b[^>]*data-sp-canvascontrol[^>]*?>/i, function (markup) {
// get the control type
var ct = /controlType":(\d*?),/i.exec(markup);
// if no control type is present this is a column which we give type 0 to let us process it
var controlType = ct == null || ct.length < 2 ? 0 : parseInt(ct[1], 10);
var control = null;
switch (controlType) {
case 0:
// empty canvas column
control = new CanvasColumn(null, 0);
control.fromHtml(markup);
_this.mergeColumnToTree(control);
break;
case 3:
// client side webpart
control = new ClientSideWebpart("");
control.fromHtml(markup);
_this.mergePartToTree(control);
break;
case 4:
// client side text
control = new ClientSideText();
control.fromHtml(markup);
_this.mergePartToTree(control);
break;
}
});
// refresh all the orders within the tree
reindex(this.sections);
return this;
};
/**
* Loads this page's content from the server
*/
ClientSidePage.prototype.load = function () {
var _this = this;
return this.getItem("CanvasContent1", "CommentsDisabled").then(function (item) {
_this.fromHtml(item.CanvasContent1);
_this.commentsDisabled = item.CommentsDisabled;
});
};
/**
* Persists the content changes (sections, columns, and controls)
*/
ClientSidePage.prototype.save = function () {
return this.updateProperties({ CanvasContent1: this.toHtml() });
};
/**
* Enables comments on this page
*/
ClientSidePage.prototype.enableComments = function () {
var _this = this;
return this.setCommentsOn(true).then(function (r) {
_this.commentsDisabled = false;
return r;
});
};
/**
* Disables comments on this page
*/
ClientSidePage.prototype.disableComments = function () {
var _this = this;
return this.setCommentsOn(false).then(function (r) {
_this.commentsDisabled = true;
return r;
});
};
/**
* Finds a control by the specified instance id
*
* @param id Instance id of the control to find
*/
ClientSidePage.prototype.findControlById = function (id) {
return this.findControl(function (c) { return c.id === id; });
};
/**
* Finds a control within this page's control tree using the supplied predicate
*
* @param predicate Takes a control and returns true or false, if true that control is returned by findControl
*/
ClientSidePage.prototype.findControl = function (predicate) {
// check all sections
for (var i = 0; i < this.sections.length; i++) {
// check all columns
for (var j = 0; j < this.sections[i].columns.length; j++) {
// check all controls
for (var k = 0; k < this.sections[i].columns[j].controls.length; k++) {
// check to see if the predicate likes this control
if (predicate(this.sections[i].columns[j].controls[k])) {
return this.sections[i].columns[j].controls[k];
}
}
}
}
// we found nothing so give nothing back
return null;
};
/**
* Sets the comments flag for a page
*
* @param on If true comments are enabled, false they are disabled
*/
ClientSidePage.prototype.setCommentsOn = function (on) {
return this.getItem().then(function (i) {
var updater = new Item(i, "SetCommentsDisabled(" + !on + ")");
return updater.update({});
});
};
/**
* Merges the control into the tree of sections and columns for this page
*
* @param control The control to merge
*/
ClientSidePage.prototype.mergePartToTree = function (control) {
var section = null;
var column = null;
var sections = this.sections.filter(function (s) { return s.order === control.controlData.position.zoneIndex; });
if (sections.length < 1) {
section = new CanvasSection(this, control.controlData.position.zoneIndex);
this.sections.push(section);
}
else {
section = sections[0];
}
var columns = section.columns.filter(function (c) { return c.order === control.controlData.position.sectionIndex; });
if (columns.length < 1) {
column = new CanvasColumn(section, control.controlData.position.sectionIndex, control.controlData.position.sectionFactor);
section.columns.push(column);
}
else {
column = columns[0];
}
control.column = column;
column.addControl(control);
};
/**
* Merges the supplied column into the tree
*
* @param column Column to merge
* @param position The position data for the column
*/
ClientSidePage.prototype.mergeColumnToTree = function (column) {
var section = null;
var sections = this.sections.filter(function (s) { return s.order === column.controlData.position.zoneIndex; });
if (sections.length < 1) {
section = new CanvasSection(this, column.controlData.position.zoneIndex);
this.sections.push(section);
}
else {
section = sections[0];
}
column.section = section;
section.columns.push(column);
};
/**
* Updates the properties of the underlying ListItem associated with this ClientSidePage
*
* @param properties Set of properties to update
* @param eTag Value used in the IF-Match header, by default "*"
*/
ClientSidePage.prototype.updateProperties = function (properties, eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.getItem().then(function (i) { return i.update(properties, eTag); });
};
return ClientSidePage;
}(File));
var CanvasSection = /** @class */ (function () {
function CanvasSection(page, order, columns) {
if (columns === void 0) { columns = []; }
this.page = page;
this.order = order;
this.columns = columns;
this._memId = common.getGUID();
}
Object.defineProperty(CanvasSection.prototype, "defaultColumn", {
/**
* Default column (this.columns[0]) for this section
*/
get: function () {
if (this.columns.length < 1) {
this.addColumn(12);
}
return this.columns[0];
},
enumerable: true,
configurable: true
});
/**
* Adds a new column to this section
*/
CanvasSection.prototype.addColumn = function (factor) {
var column = new CanvasColumn(this, getNextOrder(this.columns), factor);
this.columns.push(column);
return column;
};
/**
* Adds a control to the default column for this section
*
* @param control Control to add to the default column
*/
CanvasSection.prototype.addControl = function (control) {
this.defaultColumn.addControl(control);
return this;
};
CanvasSection.prototype.toHtml = function () {
var html = [];
for (var i = 0; i < this.columns.length; i++) {
html.push(this.columns[i].toHtml());
}
return html.join("");
};
/**
* Removes this section and all contained columns and controls from the collection
*/
CanvasSection.prototype.remove = function () {
var _this = this;
this.page.sections = this.page.sections.filter(function (section) { return section._memId !== _this._memId; });
reindex(this.page.sections);
};
return CanvasSection;
}());
var CanvasControl = /** @class */ (function () {
function CanvasControl(controlType, dataVersion, column, order, id, controlData) {
if (column === void 0) { column = null; }
if (order === void 0) { order = 1; }
if (id === void 0) { id = common.getGUID(); }
if (controlData === void 0) { controlData = null; }
this.controlType = controlType;
this.dataVersion = dataVersion;
this.column = column;
this.order = order;
this.id = id;
this.controlData = controlData;
}
Object.defineProperty(CanvasControl.prototype, "jsonData", {
/**
* Value of the control's "data-sp-controldata" attribute
*/
get: function () {
return ClientSidePage.jsonToEscapedString(this.getControlData());
},
enumerable: true,
configurable: true
});
CanvasControl.prototype.fromHtml = function (html) {
this.controlData = ClientSidePage.escapedStringToJson(getAttrValueFromString(html, "data-sp-controldata"));
this.dataVersion = getAttrValueFromString(html, "data-sp-canvasdataversion");
this.controlType = this.controlData.controlType;
this.id = this.controlData.id;
};
return CanvasControl;
}());
var CanvasColumn = /** @class */ (function (_super) {
tslib_1.__extends(CanvasColumn, _super);
function CanvasColumn(section, order, factor, controls, dataVersion) {
if (factor === void 0) { factor = 12; }
if (controls === void 0) { controls = []; }
if (dataVersion === void 0) { dataVersion = "1.0"; }
var _this = _super.call(this, 0, dataVersion) || this;
_this.section = section;
_this.order = order;
_this.factor = factor;
_this.controls = controls;
return _this;
}
CanvasColumn.prototype.addControl = function (control) {
control.column = this;
this.controls.push(control);
return this;
};
CanvasColumn.prototype.getControl = function (index) {
return this.controls[index];
};
CanvasColumn.prototype.toHtml = function () {
var html = [];
if (this.controls.length < 1) {
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.dataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\"></div>");
}
else {
for (var i = 0; i < this.controls.length; i++) {
html.push(this.controls[i].toHtml(i + 1));
}
}
return html.join("");
};
CanvasColumn.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
this.controlData = ClientSidePage.escapedStringToJson(getAttrValueFromString(html, "data-sp-controldata"));
this.factor = this.controlData.position.sectionFactor;
this.order = this.controlData.position.sectionIndex;
};
CanvasColumn.prototype.getControlData = function () {
return {
displayMode: 2,
position: {
sectionFactor: this.factor,
sectionIndex: this.order,
zoneIndex: this.section.order,
},
};
};
/**
* Removes this column and all contained controls from the collection
*/
CanvasColumn.prototype.remove = function () {
var _this = this;
this.section.columns = this.section.columns.filter(function (column) { return column.id !== _this.id; });
reindex(this.column.controls);
};
return CanvasColumn;
}(CanvasControl));
/**
* Abstract class with shared functionality for parts
*/
var ClientSidePart = /** @class */ (function (_super) {
tslib_1.__extends(ClientSidePart, _super);
function ClientSidePart() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes this column and all contained controls from the collection
*/
ClientSidePart.prototype.remove = function () {
var _this = this;
this.column.controls = this.column.controls.filter(function (control) { return control.id !== _this.id; });
reindex(this.column.controls);
};
return ClientSidePart;
}(CanvasControl));
var ClientSideText = /** @class */ (function (_super) {
tslib_1.__extends(ClientSideText, _super);
function ClientSideText(text) {
if (text === void 0) { text = ""; }
var _this = _super.call(this, 4, "1.0") || this;
_this.text = text;
return _this;
}
Object.defineProperty(ClientSideText.prototype, "text", {
/**
* The text markup of this control
*/
get: function () {
return this._text;
},
set: function (text) {
if (!text.startsWith("<p>")) {
text = "<p>" + text + "</p>";
}
this._text = text;
},
enumerable: true,
configurable: true
});
ClientSideText.prototype.getControlData = function () {
return {
controlType: this.controlType,
editorType: "CKEditor",
id: this.id,
position: {
controlIndex: this.order,
sectionFactor: this.column.factor,
sectionIndex: this.column.order,
zoneIndex: this.column.section.order,
},
};
};
ClientSideText.prototype.toHtml = function (index) {
// set our order to the value passed in
this.order = index;
var html = [];
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.dataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\">");
html.push("<div data-sp-rte=\"\">");
html.push("" + this.text);
html.push("</div>");
html.push("</div>");
return html.join("");
};
ClientSideText.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
var match = /<div[^>]*data-sp-rte[^>]*>(.*?)<\/div>$/i.exec(html);
this.text = match.length > 1 ? match[1] : "";
};
return ClientSideText;
}(ClientSidePart));
var ClientSideWebpart = /** @class */ (function (_super) {
tslib_1.__extends(ClientSideWebpart, _super);
function ClientSideWebpart(title, description, propertieJson, webPartId, htmlProperties, serverProcessedContent, canvasDataVersion) {
if (description === void 0) { description = ""; }
if (propertieJson === void 0) { propertieJson = {}; }
if (webPartId === void 0) { webPartId = ""; }
if (htmlProperties === void 0) { htmlProperties = ""; }
if (serverProcessedContent === void 0) { serverProcessedContent = null; }
if (canvasDataVersion === void 0) { canvasDataVersion = "1.0"; }
var _this = _super.call(this, 3, "1.0") || this;
_this.title = title;
_this.description = description;
_this.propertieJson = propertieJson;
_this.webPartId = webPartId;
_this.htmlProperties = htmlProperties;
_this.serverProcessedContent = serverProcessedContent;
_this.canvasDataVersion = canvasDataVersion;
return _this;
}
ClientSideWebpart.fromComponentDef = function (definition) {
var part = new ClientSideWebpart("");
part.import(definition);
return part;
};
ClientSideWebpart.prototype.import = function (component) {
this.webPartId = component.Id.replace(/^\{|\}$/g, "").toLowerCase();
var manifest = JSON.parse(component.Manifest);
this.title = manifest.preconfiguredEntries[0].title.default;
this.description = manifest.preconfiguredEntries[0].description.default;
this.dataVersion = "";
this.propertieJson = this.parseJsonProperties(manifest.preconfiguredEntries[0].properties);
};
ClientSideWebpart.prototype.setProperties = function (properties) {
this.propertieJson = common.extend(this.propertieJson, properties);
return this;
};
ClientSideWebpart.prototype.getProperties = function () {
return this.propertieJson;
};
ClientSideWebpart.prototype.toHtml = function (index) {
// set our order to the value passed in
this.order = index;
// will form the value of the data-sp-webpartdata attribute
var data = {
dataVersion: this.dataVersion,
description: this.description,
id: this.webPartId,
instanceId: this.id,
properties: this.propertieJson,
title: this.title,
};
var html = [];
html.push("<div data-sp-canvascontrol=\"\" data-sp-canvasdataversion=\"" + this.canvasDataVersion + "\" data-sp-controldata=\"" + this.jsonData + "\">");
html.push("<div data-sp-webpart=\"\" data-sp-webpartdataversion=\"" + this.dataVersion + "\" data-sp-webpartdata=\"" + ClientSidePage.jsonToEscapedString(data) + "\">");
html.push("<div data-sp-componentid>");
html.push(this.webPartId);
html.push("</div>");
html.push("<div data-sp-htmlproperties=\"\">");
html.push(this.renderHtmlProperties());
html.push("</div>");
html.push("</div>");
html.push("</div>");
return html.join("");
};
ClientSideWebpart.prototype.fromHtml = function (html) {
_super.prototype.fromHtml.call(this, html);
var webPartData = ClientSidePage.escapedStringToJson(getAttrValueFromString(html, "data-sp-webpartdata"));
this.title = webPartData.title;
this.description = webPartData.description;
this.webPartId = webPartData.id;
this.canvasDataVersion = getAttrValueFromString(html, "data-sp-canvasdataversion");
this.dataVersion = getAttrValueFromString(html, "data-sp-webpartdataversion");
this.setProperties(webPartData.properties);
if (typeof webPartData.serverProcessedContent !== "undefined") {
this.serverProcessedContent = webPartData.serverProcessedContent;
}
// get our html properties
var htmlProps = getBoundedDivMarkup(html, /<div\b[^>]*data-sp-htmlproperties[^>]*?>/i, function (markup) {
return markup.replace(/^<div\b[^>]*data-sp-htmlproperties[^>]*?>/i, "").replace(/<\/div>$/i, "");
});
this.htmlProperties = htmlProps.length > 0 ? htmlProps[0] : "";
};
ClientSideWebpart.prototype.getControlData = function () {
return {
controlType: this.controlType,
id: this.id,
position: {
controlIndex: this.order,
sectionFactor: this.column.factor,
sectionIndex: this.column.order,
zoneIndex: this.column.section.order,
},
webPartId: this.webPartId,
};
};
ClientSideWebpart.prototype.renderHtmlProperties = function () {
var html = [];
if (typeof this.serverProcessedContent === "undefined" || this.serverProcessedContent === null) {
html.push(this.htmlProperties);
}
else if (typeof this.serverProcessedContent !== "undefined") {
if (typeof this.serverProcessedContent.searchablePlainTexts !== "undefined") {
var keys = Object.keys(this.serverProcessedContent.searchablePlainTexts);
for (var i = 0; i < keys.length; i++) {
html.push("<div data-sp-prop-name=\"" + keys[i] + "\" data-sp-searchableplaintext=\"true\">");
html.push(this.serverProcessedContent.searchablePlainTexts[keys[i]]);
html.push("</div>");
}
}
if (typeof this.serverProcessedContent.imageSources !== "undefined") {
var keys = Object.keys(this.serverProcessedContent.imageSources);
for (var i = 0; i < keys.length; i++) {
html.push("<img data-sp-prop-name=\"" + keys[i] + "\" src=\"" + this.serverProcessedContent.imageSources[keys[i]] + "\" />");
}
}
if (typeof this.serverProcessedContent.links !== "undefined") {
var keys = Object.keys(this.serverProcessedContent.links);
for (var i = 0; i < keys.length; i++) {
html.push("<a data-sp-prop-name=\"" + keys[i] + "\" href=\"" + this.serverProcessedContent.links[keys[i]] + "\"></a>");
}
}
}
return html.join("");
};
ClientSideWebpart.prototype.parseJsonProperties = function (props) {
// If the web part has the serverProcessedContent property then keep this one as it might be needed as input to render the web part HTML later on
if (typeof props.webPartData !== "undefined" && typeof props.webPartData.serverProcessedContent !== "undefined") {
this.serverProcessedContent = props.webPartData.serverProcessedContent;
}
else if (typeof props.serverProcessedContent !== "undefined") {
this.serverProcessedContent = props.serverProcessedContent;
}
else {
this.serverProcessedContent = null;
}
if (typeof props.webPartData !== "undefined" && typeof props.webPartData.properties !== "undefined") {
return props.webPartData.properties;
}
else if (typeof props.properties !== "undefined") {
return props.properties;
}
else {
return props;
}
};
return ClientSideWebpart;
}(ClientSidePart));
/**
* Represents a collection of navigation nodes
*
*/
var NavigationNodes = /** @class */ (function (_super) {
tslib_1.__extends(NavigationNodes, _super);
function NavigationNodes() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a navigation node by id
*
* @param id The id of the node
*/
NavigationNodes.prototype.getById = function (id) {
var node = new NavigationNode(this);
node.concat("(" + id + ")");
return node;
};
/**
* Adds a new node to the collection
*
* @param title Display name of the node
* @param url The url of the node
* @param visible If true the node is visible, otherwise it is hidden (default: true)
*/
NavigationNodes.prototype.add = function (title, url, visible) {
var _this = this;
if (visible === void 0) { visible = true; }
var postBody = JSON.stringify({
IsVisible: visible,
Title: title,
Url: url,
"__metadata": { "type": "SP.NavigationNode" },
});
return this.clone(NavigationNodes, null).postCore({ body: postBody }).then(function (data) {
return {
data: data,
node: _this.getById(data.Id),
};
});
};
/**
* Moves a node to be after another node in the navigation
*
* @param nodeId Id of the node to move
* @param previousNodeId Id of the node after which we move the node specified by nodeId
*/
NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) {
var postBody = JSON.stringify({
nodeId: nodeId,
previousNodeId: previousNodeId,
});
return this.clone(NavigationNodes, "MoveAfter").postCore({ body: postBody });
};
return NavigationNodes;
}(SharePointQueryableCollection));
/**
* Represents an instance of a navigation node
*
*/
var NavigationNode = /** @class */ (function (_super) {
tslib_1.__extends(NavigationNode, _super);
function NavigationNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(NavigationNode.prototype, "children", {
/**
* Represents the child nodes of this node
*/
get: function () {
return new NavigationNodes(this, "Children");
},
enumerable: true,
configurable: true
});
/**
* Deletes this node and any child nodes
*/
NavigationNode.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
return NavigationNode;
}(SharePointQueryableInstance));
/**
* Exposes the navigation components
*
*/
var Navigation = /** @class */ (function (_super) {
tslib_1.__extends(Navigation, _super);
/**
* Creates a new instance of the Navigation class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of these navigation components
*/
function Navigation(baseUrl, path) {
if (path === void 0) { path = "navigation"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(Navigation.prototype, "quicklaunch", {
/**
* Gets the quicklaunch navigation nodes for the current context
*
*/
get: function () {
return new NavigationNodes(this, "quicklaunch");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Navigation.prototype, "topNavigationBar", {
/**
* Gets the top bar navigation nodes for the current context
*
*/
get: function () {
return new NavigationNodes(this, "topnavigationbar");
},
enumerable: true,
configurable: true
});
return Navigation;
}(SharePointQueryable));
/**
* Represents the top level navigation service
*/
var NavigationService = /** @class */ (function (_super) {
tslib_1.__extends(NavigationService, _super);
function NavigationService(path) {
if (path === void 0) { path = null; }
return _super.call(this, "_api/navigation", path) || this;
}
/**
* The MenuState service operation returns a Menu-State (dump) of a SiteMapProvider on a site.
*
* @param menuNodeKey MenuNode.Key of the start node within the SiteMapProvider If no key is provided the SiteMapProvider.RootNode will be the root of the menu state.
* @param depth Depth of the dump. If no value is provided a dump with the depth of 10 is returned
* @param mapProviderName The name identifying the SiteMapProvider to be used
* @param customProperties comma seperated list of custom properties to be returned.
*/
NavigationService.prototype.getMenuState = function (menuNodeKey, depth, mapProviderName, customProperties) {
if (menuNodeKey === void 0) { menuNodeKey = null; }
if (depth === void 0) { depth = 10; }
if (mapProviderName === void 0) { mapProviderName = null; }
if (customProperties === void 0) { customProperties = null; }
return (new NavigationService("MenuState")).postCore({
body: JSON.stringify({
customProperties: customProperties,
depth: depth,
mapProviderName: mapProviderName,
menuNodeKey: menuNodeKey,
}),
});
};
/**
* Tries to get a SiteMapNode.Key for a given URL within a site collection.
*
* @param currentUrl A url representing the SiteMapNode
* @param mapProviderName The name identifying the SiteMapProvider to be used
*/
NavigationService.prototype.getMenuNodeKey = function (currentUrl, mapProviderName) {
if (mapProviderName === void 0) { mapProviderName = null; }
return (new NavigationService("MenuNodeKey")).postCore({
body: JSON.stringify({
currentUrl: currentUrl,
mapProviderName: mapProviderName,
}),
});
};
return NavigationService;
}(SharePointQueryable));
/**
* Describes regional settings ODada object
*/
var RegionalSettings = /** @class */ (function (_super) {
tslib_1.__extends(RegionalSettings, _super);
/**
* Creates a new instance of the RegionalSettings class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this regional settings collection
*/
function RegionalSettings(baseUrl, path) {
if (path === void 0) { path = "regionalsettings"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(RegionalSettings.prototype, "installedLanguages", {
/**
* Gets the collection of languages used in a server farm.
*/
get: function () {
return new InstalledLanguages(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "globalInstalledLanguages", {
/**
* Gets the collection of language packs that are installed on the server.
*/
get: function () {
return new InstalledLanguages(this, "globalinstalledlanguages");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "timeZone", {
/**
* Gets time zone
*/
get: function () {
return new TimeZone(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(RegionalSettings.prototype, "timeZones", {
/**
* Gets time zones
*/
get: function () {
return new TimeZones(this);
},
enumerable: true,
configurable: true
});
return RegionalSettings;
}(SharePointQueryableInstance));
/**
* Describes installed languages ODada queriable collection
*/
var InstalledLanguages = /** @class */ (function (_super) {
tslib_1.__extends(InstalledLanguages, _super);
function InstalledLanguages(baseUrl, path) {
if (path === void 0) { path = "installedlanguages"; }
return _super.call(this, baseUrl, path) || this;
}
return InstalledLanguages;
}(SharePointQueryableCollection));
/**
* Describes TimeZone ODada object
*/
var TimeZone = /** @class */ (function (_super) {
tslib_1.__extends(TimeZone, _super);
function TimeZone(baseUrl, path) {
if (path === void 0) { path = "timezone"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets an Local Time by UTC Time
*
* @param utcTime UTC Time as Date or ISO String
*/
TimeZone.prototype.utcToLocalTime = function (utcTime) {
var dateIsoString;
if (typeof utcTime === "string") {
dateIsoString = utcTime;
}
else {
dateIsoString = utcTime.toISOString();
}
return this.clone(TimeZone, "utctolocaltime('" + dateIsoString + "')")
.postCore()
.then(function (res) { return res.hasOwnProperty("UTCToLocalTime") ? res.UTCToLocalTime : res; });
};
/**
* Gets an UTC Time by Local Time
*
* @param localTime Local Time as Date or ISO String
*/
TimeZone.prototype.localTimeToUTC = function (localTime) {
var dateIsoString;
if (typeof localTime === "string") {
dateIsoString = localTime;
}
else {
dateIsoString = common.dateAdd(localTime, "minute", localTime.getTimezoneOffset() * -1).toISOString();
}
return this.clone(TimeZone, "localtimetoutc('" + dateIsoString + "')")
.postCore()
.then(function (res) { return res.hasOwnProperty("LocalTimeToUTC") ? res.LocalTimeToUTC : res; });
};
return TimeZone;
}(SharePointQueryableInstance));
/**
* Describes time zones queriable collection
*/
var TimeZones = /** @class */ (function (_super) {
tslib_1.__extends(TimeZones, _super);
function TimeZones(baseUrl, path) {
if (path === void 0) { path = "timezones"; }
return _super.call(this, baseUrl, path) || this;
}
// https://msdn.microsoft.com/en-us/library/office/jj247008.aspx - timezones ids
/**
* Gets an TimeZone by id
*
* @param id The integer id of the timezone to retrieve
*/
TimeZones.prototype.getById = function (id) {
// do the post and merge the result into a TimeZone instance so the data and methods are available
return this.clone(TimeZones, "GetById(" + id + ")").postCore({}, spODataEntity(TimeZone));
};
return TimeZones;
}(SharePointQueryableCollection));
/**
* Allows for the fluent construction of search queries
*/
var SearchQueryBuilder = /** @class */ (function () {
function SearchQueryBuilder(queryText, _query) {
if (queryText === void 0) { queryText = ""; }
if (_query === void 0) { _query = {}; }
this._query = _query;
if (typeof queryText === "string" && queryText.length > 0) {
this.extendQuery({ Querytext: queryText });
}
}
SearchQueryBuilder.create = function (queryText, queryTemplate) {
if (queryText === void 0) { queryText = ""; }
if (queryTemplate === void 0) { queryTemplate = {}; }
return new SearchQueryBuilder(queryText, queryTemplate);
};
SearchQueryBuilder.prototype.text = function (queryText) {
return this.extendQuery({ Querytext: queryText });
};
SearchQueryBuilder.prototype.template = function (template) {
return this.extendQuery({ QueryTemplate: template });
};
SearchQueryBuilder.prototype.sourceId = function (id) {
return this.extendQuery({ SourceId: id });
};
Object.defineProperty(SearchQueryBuilder.prototype, "enableInterleaving", {
get: function () {
return this.extendQuery({ EnableInterleaving: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableStemming", {
get: function () {
return this.extendQuery({ EnableStemming: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "trimDuplicates", {
get: function () {
return this.extendQuery({ TrimDuplicates: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.trimDuplicatesIncludeId = function (n) {
return this.extendQuery({ TrimDuplicatesIncludeId: n });
};
Object.defineProperty(SearchQueryBuilder.prototype, "enableNicknames", {
get: function () {
return this.extendQuery({ EnableNicknames: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableFql", {
get: function () {
return this.extendQuery({ EnableFQL: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enablePhonetic", {
get: function () {
return this.extendQuery({ EnablePhonetic: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "bypassResultTypes", {
get: function () {
return this.extendQuery({ BypassResultTypes: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "processBestBets", {
get: function () {
return this.extendQuery({ ProcessBestBets: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableQueryRules", {
get: function () {
return this.extendQuery({ EnableQueryRules: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableSorting", {
get: function () {
return this.extendQuery({ EnableSorting: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "generateBlockRankLog", {
get: function () {
return this.extendQuery({ GenerateBlockRankLog: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.rankingModelId = function (id) {
return this.extendQuery({ RankingModelId: id });
};
SearchQueryBuilder.prototype.startRow = function (n) {
return this.extendQuery({ StartRow: n });
};
SearchQueryBuilder.prototype.rowLimit = function (n) {
return this.extendQuery({ RowLimit: n });
};
SearchQueryBuilder.prototype.rowsPerPage = function (n) {
return this.extendQuery({ RowsPerPage: n });
};
SearchQueryBuilder.prototype.selectProperties = function () {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
return this.extendQuery({ SelectProperties: properties });
};
SearchQueryBuilder.prototype.culture = function (culture) {
return this.extendQuery({ Culture: culture });
};
SearchQueryBuilder.prototype.timeZoneId = function (id) {
return this.extendQuery({ TimeZoneId: id });
};
SearchQueryBuilder.prototype.refinementFilters = function () {
var filters = [];
for (var _i = 0; _i < arguments.length; _i++) {
filters[_i] = arguments[_i];
}
return this.extendQuery({ RefinementFilters: filters });
};
SearchQueryBuilder.prototype.refiners = function (refiners) {
return this.extendQuery({ Refiners: refiners });
};
SearchQueryBuilder.prototype.hiddenConstraints = function (constraints) {
return this.extendQuery({ HiddenConstraints: constraints });
};
SearchQueryBuilder.prototype.sortList = function () {
var sorts = [];
for (var _i = 0; _i < arguments.length; _i++) {
sorts[_i] = arguments[_i];
}
return this.extendQuery({ SortList: sorts });
};
SearchQueryBuilder.prototype.timeout = function (milliseconds) {
return this.extendQuery({ Timeout: milliseconds });
};
SearchQueryBuilder.prototype.hithighlightedProperties = function () {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
return this.extendQuery({ HitHighlightedProperties: properties });
};
SearchQueryBuilder.prototype.clientType = function (clientType) {
return this.extendQuery({ ClientType: clientType });
};
SearchQueryBuilder.prototype.personalizationData = function (data) {
return this.extendQuery({ PersonalizationData: data });
};
SearchQueryBuilder.prototype.resultsURL = function (url) {
return this.extendQuery({ ResultsUrl: url });
};
SearchQueryBuilder.prototype.queryTag = function () {
var tags = [];
for (var _i = 0; _i < arguments.length; _i++) {
tags[_i] = arguments[_i];
}
return this.extendQuery({ QueryTag: tags });
};
SearchQueryBuilder.prototype.properties = function () {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
return this.extendQuery({ Properties: properties });
};
Object.defineProperty(SearchQueryBuilder.prototype, "processPersonalFavorites", {
get: function () {
return this.extendQuery({ ProcessPersonalFavorites: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.queryTemplatePropertiesUrl = function (url) {
return this.extendQuery({ QueryTemplatePropertiesUrl: url });
};
SearchQueryBuilder.prototype.reorderingRules = function () {
var rules = [];
for (var _i = 0; _i < arguments.length; _i++) {
rules[_i] = arguments[_i];
}
return this.extendQuery({ ReorderingRules: rules });
};
SearchQueryBuilder.prototype.hitHighlightedMultivaluePropertyLimit = function (limit) {
return this.extendQuery({ HitHighlightedMultivaluePropertyLimit: limit });
};
Object.defineProperty(SearchQueryBuilder.prototype, "enableOrderingHitHighlightedProperty", {
get: function () {
return this.extendQuery({ EnableOrderingHitHighlightedProperty: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.collapseSpecification = function (spec) {
return this.extendQuery({ CollapseSpecification: spec });
};
SearchQueryBuilder.prototype.uiLanguage = function (lang) {
return this.extendQuery({ UILanguage: lang });
};
SearchQueryBuilder.prototype.desiredSnippetLength = function (len) {
return this.extendQuery({ DesiredSnippetLength: len });
};
SearchQueryBuilder.prototype.maxSnippetLength = function (len) {
return this.extendQuery({ MaxSnippetLength: len });
};
SearchQueryBuilder.prototype.summaryLength = function (len) {
return this.extendQuery({ SummaryLength: len });
};
SearchQueryBuilder.prototype.toSearchQuery = function () {
return this._query;
};
SearchQueryBuilder.prototype.extendQuery = function (part) {
this._query = common.extend(this._query, part);
return this;
};
return SearchQueryBuilder;
}());
/**
* Describes the search API
*
*/
var Search = /** @class */ (function (_super) {
tslib_1.__extends(Search, _super);
/**
* Creates a new instance of the Search class
*
* @param baseUrl The url for the search context
* @param query The SearchQuery object to execute
*/
function Search(baseUrl, path) {
if (path === void 0) { path = "_api/search/postquery"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* .......
* @returns Promise
*/
Search.prototype.execute = function (query) {
var _this = this;
var formattedBody;
formattedBody = query;
if (formattedBody.SelectProperties) {
formattedBody.SelectProperties = this.fixupProp(query.SelectProperties);
}
if (formattedBody.RefinementFilters) {
formattedBody.RefinementFilters = this.fixupProp(query.RefinementFilters);
}
if (formattedBody.SortList) {
formattedBody.SortList = this.fixupProp(query.SortList);
}
if (formattedBody.HithighlightedProperties) {
formattedBody.HithighlightedProperties = this.fixupProp(query.HitHighlightedProperties);
}
if (formattedBody.ReorderingRules) {
formattedBody.ReorderingRules = this.fixupProp(query.ReorderingRules);
}
if (formattedBody.Properties) {
formattedBody.Properties = this.fixupProp(query.Properties);
}
var postBody = JSON.stringify({
request: common.extend({
"__metadata": { "type": "Microsoft.Office.Server.Search.REST.SearchRequest" },
}, formattedBody),
});
return this.postCore({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); });
};
/**
* Fixes up properties that expect to consist of a "results" collection when needed
*
* @param prop property to fixup for container struct
*/
Search.prototype.fixupProp = function (prop) {
if (prop.hasOwnProperty("results")) {
return prop;
}
return { results: prop };
};
return Search;
}(SharePointQueryableInstance));
/**
* Describes the SearchResults class, which returns the formatted and raw version of the query response
*/
var SearchResults = /** @class */ (function () {
/**
* Creates a new instance of the SearchResult class
*
*/
function SearchResults(rawResponse, _url, _query, _raw, _primary) {
if (_raw === void 0) { _raw = null; }
if (_primary === void 0) { _primary = null; }
this._url = _url;
this._query = _query;
this._raw = _raw;
this._primary = _primary;
this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse;
}
Object.defineProperty(SearchResults.prototype, "ElapsedTime", {
get: function () {
return this.RawSearchResults.ElapsedTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RowCount", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRows", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RawSearchResults", {
get: function () {
return this._raw;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", {
get: function () {
if (this._primary === null) {
this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows);
}
return this._primary;
},
enumerable: true,
configurable: true
});
/**
* Gets a page of results
*
* @param pageNumber Index of the page to return. Used to determine StartRow
* @param pageSize Optional, items per page (default = 10)
*/
SearchResults.prototype.getPage = function (pageNumber, pageSize) {
// if we got all the available rows we don't have another page
if (this.TotalRows < this.RowCount) {
return Promise.resolve(null);
}
// if pageSize is supplied, then we use that regardless of any previous values
// otherwise get the previous RowLimit or default to 10
var rows = typeof pageSize !== "undefined" ? pageSize : this._query.hasOwnProperty("RowLimit") ? this._query.RowLimit : 10;
var query = common.extend(this._query, {
RowLimit: rows,
StartRow: rows * (pageNumber - 1),
});
// we have reached the end
if (query.StartRow > this.TotalRows) {
return Promise.resolve(null);
}
var search = new Search(this._url, null);
return search.execute(query);
};
/**
* Formats a search results array
*
* @param rawResults The array to process
*/
SearchResults.prototype.formatSearchResults = function (rawResults) {
var results = new Array();
var tempResults = rawResults.results ? rawResults.results : rawResults;
for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) {
var tempResult = tempResults_1[_i];
var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells;
results.push(cells.reduce(function (res, cell) {
Object.defineProperty(res, cell.Key, {
configurable: false,
enumerable: true,
value: cell.Value,
writable: false,
});
return res;
}, {}));
}
return results;
};
return SearchResults;
}());
(function (SortDirection) {
SortDirection[SortDirection["Ascending"] = 0] = "Ascending";
SortDirection[SortDirection["Descending"] = 1] = "Descending";
SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula";
})(exports.SortDirection || (exports.SortDirection = {}));
(function (ReorderingRuleMatchType) {
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs";
ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag";
ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition";
})(exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {}));
(function (QueryPropertyValueType) {
QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None";
QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType";
QueryPropertyValueType[QueryPropertyValueType["Int32Type"] = 2] = "Int32Type";
QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType";
QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType";
QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType";
})(exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {}));
var SearchBuiltInSourceId = /** @class */ (function () {
function SearchBuiltInSourceId() {
}
SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84";
SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419";
SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7";
SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d";
SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48";
SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31";
SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b";
SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89";
SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf";
SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc";
SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a";
SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12";
SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c";
SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181";
SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1";
return SearchBuiltInSourceId;
}());
var SearchSuggest = /** @class */ (function (_super) {
tslib_1.__extends(SearchSuggest, _super);
function SearchSuggest(baseUrl, path) {
if (path === void 0) { path = "_api/search/suggest"; }
return _super.call(this, baseUrl, path) || this;
}
SearchSuggest.prototype.execute = function (query) {
this.mapQueryToQueryString(query);
return this.get().then(function (response) { return new SearchSuggestResult(response); });
};
SearchSuggest.prototype.mapQueryToQueryString = function (query) {
this.query.add("querytext", "'" + query.querytext + "'");
if (query.hasOwnProperty("count")) {
this.query.add("inumberofquerysuggestions", query.count.toString());
}
if (query.hasOwnProperty("personalCount")) {
this.query.add("inumberofresultsuggestions", query.personalCount.toString());
}
if (query.hasOwnProperty("preQuery")) {
this.query.add("fprequerysuggestions", query.preQuery.toString());
}
if (query.hasOwnProperty("hitHighlighting")) {
this.query.add("fhithighlighting", query.hitHighlighting.toString());
}
if (query.hasOwnProperty("capitalize")) {
this.query.add("fcapitalizefirstletters", query.capitalize.toString());
}
if (query.hasOwnProperty("culture")) {
this.query.add("culture", query.culture.toString());
}
if (query.hasOwnProperty("stemming")) {
this.query.add("enablestemming", query.stemming.toString());
}
if (query.hasOwnProperty("includePeople")) {
this.query.add("showpeoplenamesuggestions", query.includePeople.toString());
}
if (query.hasOwnProperty("queryRules")) {
this.query.add("enablequeryrules", query.queryRules.toString());
}
if (query.hasOwnProperty("prefixMatch")) {
this.query.add("fprefixmatchallterms", query.prefixMatch.toString());
}
};
return SearchSuggest;
}(SharePointQueryableInstance));
var SearchSuggestResult = /** @class */ (function () {
function SearchSuggestResult(json) {
if (json.hasOwnProperty("suggest")) {
// verbose
this.PeopleNames = json.suggest.PeopleNames.results;
this.PersonalResults = json.suggest.PersonalResults.results;
this.Queries = json.suggest.Queries.results;
}
else {
this.PeopleNames = json.PeopleNames;
this.PersonalResults = json.PersonalResults;
this.Queries = json.Queries;
}
}
return SearchSuggestResult;
}());
/**
* Manages a batch of OData operations
*/
var SPBatch = /** @class */ (function (_super) {
tslib_1.__extends(SPBatch, _super);
function SPBatch(baseUrl) {
var _this = _super.call(this) || this;
_this.baseUrl = baseUrl;
return _this;
}
/**
* Parses the response from a batch request into an array of Response instances
*
* @param body Text body of the response from the batch request
*/
SPBatch.ParseResponse = function (body) {
return new Promise(function (resolve, reject) {
var responses = [];
var header = "--batchresponse_";
// Ex. "HTTP/1.1 500 Internal Server Error"
var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i");
var lines = body.split("\n");
var state = "batch";
var status;
var statusText;
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
switch (state) {
case "batch":
if (line.substr(0, header.length) === header) {
state = "batchHeaders";
}
else {
if (line.trim() !== "") {
throw new SPBatchParseException("Invalid response, line " + i);
}
}
break;
case "batchHeaders":
if (line.trim() === "") {
state = "status";
}
break;
case "status":
var parts = statusRegExp.exec(line);
if (parts.length !== 3) {
throw new SPBatchParseException("Invalid status, line " + i);
}
status = parseInt(parts[1], 10);
statusText = parts[2];
state = "statusHeaders";
break;
case "statusHeaders":
if (line.trim() === "") {
state = "body";
}
break;
case "body":
responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText }));
state = "batch";
break;
}
}
if (state !== "status") {
reject(new SPBatchParseException("Unexpected end of input"));
}
resolve(responses);
});
};
SPBatch.prototype.executeImpl = function () {
var _this = this;
logging.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this.requests.length + " requests.", 1 /* Info */);
// if we don't have any requests, don't bother sending anything
// this could be due to caching further upstream, or just an empty batch
if (this.requests.length < 1) {
logging.Logger.write("Resolving empty batch.", 1 /* Info */);
return Promise.resolve();
}
// creating the client here allows the url to be populated for nodejs client as well as potentially
// any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl
// below to be correct
var client = new SPHttpClient();
// due to timing we need to get the absolute url here so we can use it for all the individual requests
// and for sending the entire batch
return toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) {
// build all the requests, send them, pipe results in order to parsers
var batchBody = [];
var currentChangeSetId = "";
for (var i = 0; i < _this.requests.length; i++) {
var reqInfo = _this.requests[i];
if (reqInfo.method === "GET") {
if (currentChangeSetId.length > 0) {
// end an existing change set
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this.batchId + "\n");
}
else {
if (currentChangeSetId.length < 1) {
// start new change set
currentChangeSetId = common.getGUID();
batchBody.push("--batch_" + _this.batchId + "\n");
batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n");
}
batchBody.push("--changeset_" + currentChangeSetId + "\n");
}
// common batch part prefix
batchBody.push("Content-Type: application/http\n");
batchBody.push("Content-Transfer-Encoding: binary\n\n");
var headers = new Headers();
// this is the url of the individual request within the batch
var url = common.isUrlAbsolute(reqInfo.url) ? reqInfo.url : common.combinePaths(absoluteRequestUrl, reqInfo.url);
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", 0 /* Verbose */);
if (reqInfo.method !== "GET") {
var method = reqInfo.method;
var castHeaders = reqInfo.options.headers;
if (reqInfo.hasOwnProperty("options") && reqInfo.options.hasOwnProperty("headers") && typeof castHeaders["X-HTTP-Method"] !== "undefined") {
method = castHeaders["X-HTTP-Method"];
delete castHeaders["X-HTTP-Method"];
}
batchBody.push(method + " " + url + " HTTP/1.1\n");
headers.set("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
else {
batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n");
}
// merge global config headers
common.mergeHeaders(headers, SPRuntimeConfig.headers);
// merge per-request headers
if (reqInfo.options) {
common.mergeHeaders(headers, reqInfo.options.headers);
}
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:@pnp-$$Version$$");
}
// write headers into batch body
headers.forEach(function (value, name) {
batchBody.push(name + ": " + value + "\n");
});
batchBody.push("\n");
if (reqInfo.options.body) {
batchBody.push(reqInfo.options.body + "\n\n");
}
}
if (currentChangeSetId.length > 0) {
// Close the changeset
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this.batchId + "--\n");
var batchOptions = {
"body": batchBody.join(""),
"headers": {
"Content-Type": "multipart/mixed; boundary=batch_" + _this.batchId,
},
"method": "POST",
};
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", 1 /* Info */);
return client.fetch(common.combinePaths(absoluteRequestUrl, "/_api/$batch"), batchOptions)
.then(function (r) { return r.text(); })
.then(SPBatch.ParseResponse)
.then(function (responses) {
if (responses.length !== _this.requests.length) {
throw new SPBatchParseException("Could not properly parse responses to match requests in batch.");
}
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", 1 /* Info */);
return responses.reduce(function (chain, response, index) {
var request = _this.requests[index];
logging.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", 0 /* Verbose */);
return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); });
}, Promise.resolve());
});
});
};
return SPBatch;
}(odata.ODataBatch));
/**
* Describes a collection of List objects
*
*/
var Features = /** @class */ (function (_super) {
tslib_1.__extends(Features, _super);
/**
* Creates a new instance of the Lists class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this fields collection
*/
function Features(baseUrl, path) {
if (path === void 0) { path = "features"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the feature (GUID)
*/
Features.prototype.getById = function (id) {
var feature = new Feature(this);
feature.concat("('" + id + "')");
return feature;
};
/**
* Adds a new list to the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature activation will be forced
*/
Features.prototype.add = function (id, force) {
var _this = this;
if (force === void 0) { force = false; }
return this.clone(Features, "add").postCore({
body: JSON.stringify({
featdefScope: 0,
featureId: id,
force: force,
}),
}).then(function (data) {
return {
data: data,
feature: _this.getById(id),
};
});
};
/**
* Removes (deactivates) a feature from the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature deactivation will be forced
*/
Features.prototype.remove = function (id, force) {
if (force === void 0) { force = false; }
return this.clone(Features, "remove").postCore({
body: JSON.stringify({
featureId: id,
force: force,
}),
});
};
return Features;
}(SharePointQueryableCollection));
var Feature = /** @class */ (function (_super) {
tslib_1.__extends(Feature, _super);
function Feature() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes (deactivates) a feature from the collection
*
* @param force If true the feature deactivation will be forced
*/
Feature.prototype.deactivate = function (force) {
var _this = this;
if (force === void 0) { force = false; }
var removeDependency = this.addBatchDependency();
var idGet = new Feature(this).select("DefinitionId");
return idGet.get().then(function (feature) {
var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force);
removeDependency();
return promise;
});
};
return Feature;
}(SharePointQueryableInstance));
var RelatedItemManagerImpl = /** @class */ (function (_super) {
tslib_1.__extends(RelatedItemManagerImpl, _super);
function RelatedItemManagerImpl(baseUrl, path) {
if (path === void 0) { path = "_api/SP.RelatedItemManager"; }
return _super.call(this, baseUrl, path) || this;
}
RelatedItemManagerImpl.FromUrl = function (url) {
if (url === null) {
return new RelatedItemManagerImpl("");
}
var index = url.indexOf("_api/");
if (index > -1) {
return new RelatedItemManagerImpl(url.substr(0, index));
}
return new RelatedItemManagerImpl(url);
};
RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl, null);
query.concat(".GetRelatedItems");
return query.postCore({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl, null);
query.concat(".GetPageOneRelatedItems");
return query.postCore({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null);
query.concat(".AddSingleLink");
return query.postCore({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemID,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by list name and item id, to an item specified by url
*
* @param sourceListName The source list name or list id
* @param sourceItemId The source item id
* @param targetItemUrl The target item url
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null);
query.concat(".AddSingleLinkToUrl");
return query.postCore({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
TargetItemUrl: targetItemUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by url, to an item specified by list name and item id
*
* @param sourceItemUrl The source item url
* @param targetListName The target list name or list id
* @param targetItemId The target item id
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null);
query.concat(".AddSingleLinkFromUrl");
return query.postCore({
body: JSON.stringify({
SourceItemUrl: sourceItemUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) {
if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null);
query.concat(".DeleteSingleLink");
return query.postCore({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryDeleteReverseLink: tryDeleteReverseLink,
}),
});
};
return RelatedItemManagerImpl;
}(SharePointQueryable));
/**
* Describes a collection of webs
*
*/
var Webs = /** @class */ (function (_super) {
tslib_1.__extends(Webs, _super);
/**
* Creates a new instance of the Webs class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this web collection
*/
function Webs(baseUrl, webPath) {
if (webPath === void 0) { webPath = "webs"; }
return _super.call(this, baseUrl, webPath) || this;
}
/**
* Adds a new web to the collection
*
* @param title The new web's title
* @param url The new web's relative url
* @param description The new web's description
* @param template The new web's template internal name (default = STS)
* @param language The locale id that specifies the new web's language (default = 1033 [English, US])
* @param inheritPermissions When true, permissions will be inherited from the new web's parent (default = true)
*/
Webs.prototype.add = function (title, url, description, template, language, inheritPermissions) {
if (description === void 0) { description = ""; }
if (template === void 0) { template = "STS"; }
if (language === void 0) { language = 1033; }
if (inheritPermissions === void 0) { inheritPermissions = true; }
var props = {
Description: description,
Language: language,
Title: title,
Url: url,
UseSamePermissionsAsParentSite: inheritPermissions,
WebTemplate: template,
};
var postBody = JSON.stringify({
"parameters": common.extend({
"__metadata": { "type": "SP.WebCreationInformation" },
}, props),
});
return this.clone(Webs, "add").postCore({ body: postBody }).then(function (data) {
return {
data: data,
web: new Web(spExtractODataId(data).replace(/_api\/web\/?/i, "")),
};
});
};
return Webs;
}(SharePointQueryableCollection));
/**
* Describes a collection of web infos
*
*/
var WebInfos = /** @class */ (function (_super) {
tslib_1.__extends(WebInfos, _super);
/**
* Creates a new instance of the WebInfos class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this web infos collection
*/
function WebInfos(baseUrl, webPath) {
if (webPath === void 0) { webPath = "webinfos"; }
return _super.call(this, baseUrl, webPath) || this;
}
return WebInfos;
}(SharePointQueryableCollection));
/**
* Describes a web
*
*/
var Web = /** @class */ (function (_super) {
tslib_1.__extends(Web, _super);
/**
* Creates a new instance of the Web class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this web
*/
function Web(baseUrl, path) {
if (path === void 0) { path = "_api/web"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Creates a new web instance from the given url by indexing the location of the /_api/
* segment. If this is not found the method creates a new web with the entire string as
* supplied.
*
* @param url
*/
Web.fromUrl = function (url, path) {
return new Web(extractWebUrl(url), path);
};
Object.defineProperty(Web.prototype, "webs", {
/**
* Gets this web's subwebs
*
*/
get: function () {
return new Webs(this);
},
enumerable: true,
configurable: true
});
/**
* Gets this web's parent web and data
*
*/
Web.prototype.getParentWeb = function () {
var _this = this;
return this.select("ParentWeb/Id").expand("ParentWeb").get()
.then(function (_a) {
var ParentWeb = _a.ParentWeb;
return new Site(_this.toUrlAndQuery().split("/_api")[0]).openWebById(ParentWeb.Id);
});
};
/**
* Returns a collection of objects that contain metadata about subsites of the current site in which the current user is a member.
*
* @param nWebTemplateFilter Specifies the site definition (default = -1)
* @param nConfigurationFilter A 16-bit integer that specifies the identifier of a configuration (default = -1)
*/
Web.prototype.getSubwebsFilteredForCurrentUser = function (nWebTemplateFilter, nConfigurationFilter) {
if (nWebTemplateFilter === void 0) { nWebTemplateFilter = -1; }
if (nConfigurationFilter === void 0) { nConfigurationFilter = -1; }
return this.clone(Webs, "getSubwebsFilteredForCurrentUser(nWebTemplateFilter=" + nWebTemplateFilter + ",nConfigurationFilter=" + nConfigurationFilter + ")");
};
Object.defineProperty(Web.prototype, "allProperties", {
/**
* Allows access to the web's all properties collection
*/
get: function () {
return this.clone(SharePointQueryableCollection, "allproperties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "webinfos", {
/**
* Gets a collection of WebInfos for this web's subwebs
*
*/
get: function () {
return new WebInfos(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "contentTypes", {
/**
* Gets the content types available in this web
*
*/
get: function () {
return new ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "lists", {
/**
* Gets the lists in this web
*
*/
get: function () {
return new Lists(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "fields", {
/**
* Gets the fields in this web
*
*/
get: function () {
return new Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "features", {
/**
* Gets the active features for this web
*
*/
get: function () {
return new Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "availablefields", {
/**
* Gets the available fields in this web
*
*/
get: function () {
return new Fields(this, "availablefields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "navigation", {
/**
* Gets the navigation options in this web
*
*/
get: function () {
return new Navigation(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUsers", {
/**
* Gets the site users
*
*/
get: function () {
return new SiteUsers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteGroups", {
/**
* Gets the site groups
*
*/
get: function () {
return new SiteGroups(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUserInfoList", {
/**
* Gets site user info list
*
*/
get: function () {
return new List(this, "siteuserinfolist");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "regionalSettings", {
/**
* Gets regional settings
*
*/
get: function () {
return new RegionalSettings(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "currentUser", {
/**
* Gets the current user
*/
get: function () {
return new CurrentUser(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "folders", {
/**
* Gets the top-level folders in this web
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "userCustomActions", {
/**
* Gets all user custom actions for this web
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "roleDefinitions", {
/**
* Gets the collection of RoleDefinition resources
*
*/
get: function () {
return new RoleDefinitions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "relatedItems", {
/**
* Provides an interface to manage related items
*
*/
get: function () {
return RelatedItemManagerImpl.FromUrl(this.toUrl());
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch for requests within the context of this web
*
*/
Web.prototype.createBatch = function () {
return new SPBatch(this.parentUrl);
};
Object.defineProperty(Web.prototype, "rootFolder", {
/**
* Gets the root folder of this web
*
*/
get: function () {
return new Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedOwnerGroup", {
/**
* Gets the associated owner group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedownergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedMemberGroup", {
/**
* Gets the associated member group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedmembergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedVisitorGroup", {
/**
* Gets the associated visitor group for this web
*
*/
get: function () {
return new SiteGroup(this, "associatedvisitorgroup");
},
enumerable: true,
configurable: true
});
/**
* Gets a folder by server relative url
*
* @param folderRelativeUrl The server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) {
return new Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')");
};
/**
* Gets a folder by server relative relative path if your folder name contains # and % characters
* you need to first encode the file name using encodeURIComponent() and then pass the url
* let url = "/sites/test/Shared Documents/" + encodeURIComponent("%123");
* This works only in SharePoint online.
*
* @param folderRelativeUrl The server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativePath = function (folderRelativeUrl) {
return new Folder(this, "getFolderByServerRelativePath(decodedUrl='" + folderRelativeUrl + "')");
};
/**
* Gets a file by server relative url
*
* @param fileRelativeUrl The server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) {
return new File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')");
};
/**
* Gets a file by server relative url if your file name contains # and % characters
* you need to first encode the file name using encodeURIComponent() and then pass the url
* let url = "/sites/test/Shared Documents/" + encodeURIComponent("%123.docx");
*
* @param fileRelativeUrl The server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativePath = function (fileRelativeUrl) {
return new File(this, "getFileByServerRelativePath(decodedUrl='" + fileRelativeUrl + "')");
};
/**
* Gets a list by server relative url (list's root folder)
*
* @param listRelativeUrl The server relative path to the list's root folder (including /sites/ if applicable)
*/
Web.prototype.getList = function (listRelativeUrl) {
return new List(this, "getList('" + listRelativeUrl + "')");
};
/**
* Updates this web instance with the supplied properties
*
* @param properties A plain object hash of values to update for the web
*/
Web.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(common.extend({
"__metadata": { "type": "SP.Web" },
}, properties));
return this.postCore({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
web: _this,
};
});
};
/**
* Deletes this web
*
*/
Web.prototype.delete = function () {
return _super.prototype.deleteCore.call(this);
};
/**
* Applies the theme specified by the contents of each of the files specified in the arguments to the site
*
* @param colorPaletteUrl The server-relative URL of the color palette file
* @param fontSchemeUrl The server-relative URL of the font scheme
* @param backgroundImageUrl The server-relative URL of the background image
* @param shareGenerated When true, the generated theme files are stored in the root site. When false, they are stored in this web
*/
Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) {
var postBody = JSON.stringify({
backgroundImageUrl: backgroundImageUrl,
colorPaletteUrl: colorPaletteUrl,
fontSchemeUrl: fontSchemeUrl,
shareGenerated: shareGenerated,
});
return this.clone(Web, "applytheme").postCore({ body: postBody });
};
/**
* Applies the specified site definition or site template to the Web site that has no template applied to it
*
* @param template Name of the site definition or the name of the site template
*/
Web.prototype.applyWebTemplate = function (template) {
var q = this.clone(Web, "applywebtemplate");
q.concat("(@t)");
q.query.add("@t", template);
return q.postCore();
};
/**
* Checks whether the specified login name belongs to a valid user in the web. If the user doesn't exist, adds the user to the web.
*
* @param loginName The login name of the user (ex: i:0#.f|membership|user@domain.onmicrosoft.com)
*/
Web.prototype.ensureUser = function (loginName) {
var postBody = JSON.stringify({
logonName: loginName,
});
return this.clone(Web, "ensureuser").postCore({ body: postBody }).then(function (data) {
return {
data: data,
user: new SiteUser(spExtractODataId(data)),
};
});
};
/**
* Returns a collection of site templates available for the site
*
* @param language The locale id of the site templates to retrieve (default = 1033 [English, US])
* @param includeCrossLanguage When true, includes language-neutral site templates; otherwise false (default = true)
*/
Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) {
if (language === void 0) { language = 1033; }
if (includeCrossLanugage === void 0) { includeCrossLanugage = true; }
return new SharePointQueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")");
};
/**
* Returns the list gallery on the site
*
* @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114,
* MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125
*/
Web.prototype.getCatalog = function (type) {
return this.clone(Web, "getcatalog(" + type + ")").select("Id").get().then(function (data) {
return new List(spExtractODataId(data));
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query
*
* @param query The change query
*/
Web.prototype.getChanges = function (query) {
var postBody = JSON.stringify({ "query": common.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) });
return this.clone(Web, "getchanges").postCore({ body: postBody });
};
Object.defineProperty(Web.prototype, "customListTemplate", {
/**
* Gets the custom list templates for the site
*
*/
get: function () {
return new SharePointQueryableCollection(this, "getcustomlisttemplates");
},
enumerable: true,
configurable: true
});
/**
* Returns the user corresponding to the specified member identifier for the current site
*
* @param id The id of the user
*/
Web.prototype.getUserById = function (id) {
return new SiteUser(this, "getUserById(" + id + ")");
};
/**
* Returns the name of the image file for the icon that is used to represent the specified file
*
* @param filename The file name. If this parameter is empty, the server returns an empty string
* @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1 (default = 0)
* @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName
*/
Web.prototype.mapToIcon = function (filename, size, progId) {
if (size === void 0) { size = 0; }
if (progId === void 0) { progId = ""; }
return this.clone(Web, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")").get();
};
/**
* Returns the tenant property corresponding to the specified key in the app catalog site
*
* @param key Id of storage entity to be set
*/
Web.prototype.getStorageEntity = function (key) {
return this.clone(Web, "getStorageEntity('" + key + "')").get();
};
/**
* This will set the storage entity identified by the given key (MUST be called in the context of the app catalog)
*
* @param key Id of storage entity to be set
* @param value Value of storage entity to be set
* @param description Description of storage entity to be set
* @param comments Comments of storage entity to be set
*/
Web.prototype.setStorageEntity = function (key, value, description, comments) {
if (description === void 0) { description = ""; }
if (comments === void 0) { comments = ""; }
return this.clone(Web, "setStorageEntity").postCore({
body: JSON.stringify({
comments: comments,
description: description,
key: key,
value: value,
}),
});
};
/**
* This will remove the storage entity identified by the given key
*
* @param key Id of storage entity to be removed
*/
Web.prototype.removeStorageEntity = function (key) {
return this.clone(Web, "removeStorageEntity('" + key + "')").postCore();
};
/**
* Gets the app catalog for this web
*
* @param url Optional url or web containing the app catalog (default: current web)
*/
Web.prototype.getAppCatalog = function (url) {
return new AppCatalog(url || this);
};
/**
* Gets the collection of available client side web parts for this web instance
*/
Web.prototype.getClientSideWebParts = function () {
return this.clone(SharePointQueryableCollection, "GetClientSideWebParts").get();
};
/**
* Creates a new client side page
*
* @param pageName Name of the new page
* @param title Display title of the new page
* @param libraryTitle Title of the library in which to create the new page. Default: "Site Pages"
*/
Web.prototype.addClientSidePage = function (pageName, title, libraryTitle) {
if (title === void 0) { title = pageName.replace(/\.[^/.]+$/, ""); }
if (libraryTitle === void 0) { libraryTitle = "Site Pages"; }
return ClientSidePage.create(this.lists.getByTitle(libraryTitle), pageName, title);
};
return Web;
}(SharePointQueryableShareableWeb));
/**
* Describes a site collection
*
*/
var Site = /** @class */ (function (_super) {
tslib_1.__extends(Site, _super);
/**
* Creates a new instance of the Site class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this site collection
*/
function Site(baseUrl, path) {
if (path === void 0) { path = "_api/site"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(Site.prototype, "rootWeb", {
/**
* Gets the root web of the site collection
*
*/
get: function () {
return new Web(this, "rootweb");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "features", {
/**
* Gets the active features for this site collection
*
*/
get: function () {
return new Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "userCustomActions", {
/**
* Gets all custom actions for this site collection
*
*/
get: function () {
return new UserCustomActions(this);
},
enumerable: true,
configurable: true
});
/**
* Gets the context information for this site collection
*/
Site.prototype.getContextInfo = function () {
var q = new Site(this.parentUrl, "_api/contextinfo");
return q.postCore().then(function (data) {
if (data.hasOwnProperty("GetContextWebInformation")) {
var info = data.GetContextWebInformation;
info.SupportedSchemaVersions = info.SupportedSchemaVersions.results;
return info;
}
else {
return data;
}
});
};
/**
* Gets the document libraries on a site. Static method. (SharePoint Online only)
*
* @param absoluteWebUrl The absolute url of the web whose document libraries should be returned
*/
Site.prototype.getDocumentLibraries = function (absoluteWebUrl) {
var q = new SharePointQueryable("", "_api/sp.web.getdocumentlibraries(@v)");
q.query.add("@v", "'" + absoluteWebUrl + "'");
return q.get().then(function (data) {
if (data.hasOwnProperty("GetDocumentLibraries")) {
return data.GetDocumentLibraries;
}
else {
return data;
}
});
};
/**
* Gets the site url from a page url
*
* @param absolutePageUrl The absolute url of the page
*/
Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) {
var q = new SharePointQueryable("", "_api/sp.web.getweburlfrompageurl(@v)");
q.query.add("@v", "'" + absolutePageUrl + "'");
return q.get().then(function (data) {
if (data.hasOwnProperty("GetWebUrlFromPageUrl")) {
return data.GetWebUrlFromPageUrl;
}
else {
return data;
}
});
};
/**
* Creates a new batch for requests within the context of this site collection
*
*/
Site.prototype.createBatch = function () {
return new SPBatch(this.parentUrl);
};
/**
* Opens a web by id (using POST)
*
* @param webId The GUID id of the web to open
*/
Site.prototype.openWebById = function (webId) {
return this.clone(Site, "openWebById('" + webId + "')").postCore().then(function (d) {
return {
data: d,
web: Web.fromUrl(spExtractODataId(d)),
};
});
};
return Site;
}(SharePointQueryableInstance));
var UserProfileQuery = /** @class */ (function (_super) {
tslib_1.__extends(UserProfileQuery, _super);
/**
* Creates a new instance of the UserProfileQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this user profile query
*/
function UserProfileQuery(baseUrl, path) {
if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; }
var _this = _super.call(this, baseUrl, path) || this;
_this.clientPeoplePickerQuery = new ClientPeoplePickerQuery(baseUrl);
_this.profileLoader = new ProfileLoader(baseUrl);
return _this;
}
Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", {
/**
* The url of the edit profile page for the current user
*/
get: function () {
return this.clone(UserProfileQuery, "EditProfileLink").get();
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", {
/**
* A boolean value that indicates whether the current user's "People I'm Following" list is public
*/
get: function () {
return this.clone(UserProfileQuery, "IsMyPeopleListPublic").get();
},
enumerable: true,
configurable: true
});
/**
* A boolean value that indicates whether the current user is being followed by the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowedby(@v)");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* A boolean value that indicates whether the current user is following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowing = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowing(@v)");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets tags that the current user is following
*
* @param maxCount The maximum number of tags to retrieve (default is 20)
*/
UserProfileQuery.prototype.getFollowedTags = function (maxCount) {
if (maxCount === void 0) { maxCount = 20; }
return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")").get();
};
/**
* Gets the people who are following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.getFollowersFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getfollowersfor(@v)");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "myFollowers", {
/**
* Gets the people who are following the current user
*
*/
get: function () {
return new SharePointQueryableCollection(this, "getmyfollowers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "myProperties", {
/**
* Gets user properties for the current user
*
*/
get: function () {
return new UserProfileQuery(this, "getmyproperties");
},
enumerable: true,
configurable: true
});
/**
* Gets the people who the specified user is following
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets user properties for the specified user.
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPropertiesFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "trendingTags", {
/**
* Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first
*
*/
get: function () {
var q = this.clone(UserProfileQuery, null);
q.concat(".gettrendingtags");
return q.get();
},
enumerable: true,
configurable: true
});
/**
* Gets the specified user profile property for the specified user
*
* @param loginName The account name of the user
* @param propertyName The case-sensitive name of the property to get
*/
UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) {
var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Removes the specified user from the user's list of suggested people to follow
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.hideSuggestion = function (loginName) {
var q = this.clone(UserProfileQuery, "hidesuggestion(@v)");
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.postCore();
};
/**
* A boolean values that indicates whether the first user is following the second user
*
* @param follower The account name of the user who might be following the followee
* @param followee The account name of the user who might be followed by the follower
*/
UserProfileQuery.prototype.isFollowing = function (follower, followee) {
var q = this.clone(UserProfileQuery, null);
q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)");
q.query.add("@v", "'" + encodeURIComponent(follower) + "'");
q.query.add("@y", "'" + encodeURIComponent(followee) + "'");
return q.get();
};
/**
* Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching.
*
* @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB
*/
UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) {
var _this = this;
return new Promise(function (resolve, reject) {
common.readBlobAsArrayBuffer(profilePicSource).then(function (buffer) {
var request = new UserProfileQuery(_this, "setmyprofilepicture");
request.postCore({
body: String.fromCharCode.apply(null, new Uint16Array(buffer)),
}).then(function (_) { return resolve(); });
}).catch(function (e) { return reject(e); });
});
};
/**
* Sets single value User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValue Property value
*/
UserProfileQuery.prototype.setSingleValueProfileProperty = function (accountName, propertyName, propertyValue) {
var postBody = JSON.stringify({
accountName: accountName,
propertyName: propertyName,
propertyValue: propertyValue,
});
return this.clone(UserProfileQuery, "SetSingleValueProfileProperty")
.postCore({ body: postBody });
};
/**
* Sets multi valued User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValues Property values
*/
UserProfileQuery.prototype.setMultiValuedProfileProperty = function (accountName, propertyName, propertyValues) {
var postBody = JSON.stringify({
accountName: accountName,
propertyName: propertyName,
propertyValues: propertyValues,
});
return this.clone(UserProfileQuery, "SetMultiValuedProfileProperty")
.postCore({ body: postBody });
};
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only)
*
* @param emails The email addresses of the users to provision sites for
*/
UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () {
var emails = [];
for (var _i = 0; _i < arguments.length; _i++) {
emails[_i] = arguments[_i];
}
return this.profileLoader.createPersonalSiteEnqueueBulk(emails);
};
Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner
*
*/
get: function () {
return this.profileLoader.ownerUserProfile;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "userProfile", {
/**
* Gets the user profile for the current user
*/
get: function () {
return this.profileLoader.userProfile;
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.profileLoader.createPersonalSite(interactiveRequest);
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private
*/
UserProfileQuery.prototype.shareAllSocialData = function (share) {
return this.profileLoader.shareAllSocialData(share);
};
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
UserProfileQuery.prototype.clientPeoplePickerResolveUser = function (queryParams) {
return this.clientPeoplePickerQuery.clientPeoplePickerResolveUser(queryParams);
};
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
UserProfileQuery.prototype.clientPeoplePickerSearchUser = function (queryParams) {
return this.clientPeoplePickerQuery.clientPeoplePickerSearchUser(queryParams);
};
return UserProfileQuery;
}(SharePointQueryableInstance));
var ProfileLoader = /** @class */ (function (_super) {
tslib_1.__extends(ProfileLoader, _super);
/**
* Creates a new instance of the ProfileLoader class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this profile loader
*/
function ProfileLoader(baseUrl, path) {
if (path === void 0) { path = "_api/sp.userprofiles.profileloader.getprofileloader"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) Doesn't support batching
*
* @param emails The email addresses of the users to provision sites for
*/
ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) {
return this.clone(ProfileLoader, "createpersonalsiteenqueuebulk", false).postCore({
body: JSON.stringify({ "emailIDs": emails }),
});
};
Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner.
*
*/
get: function () {
var q = this.getParent(ProfileLoader, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile");
if (this.hasBatch) {
q = q.inBatch(this.batch);
}
return q.postCore();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProfileLoader.prototype, "userProfile", {
/**
* Gets the user profile of the current user.
*
*/
get: function () {
return this.clone(ProfileLoader, "getuserprofile").postCore();
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files.
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.clone(ProfileLoader, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")").postCore();
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private.
*/
ProfileLoader.prototype.shareAllSocialData = function (share) {
return this.clone(ProfileLoader, "getuserprofile/shareallsocialdata(" + share + ")").postCore();
};
return ProfileLoader;
}(SharePointQueryable));
var ClientPeoplePickerQuery = /** @class */ (function (_super) {
tslib_1.__extends(ClientPeoplePickerQuery, _super);
/**
* Creates a new instance of the PeoplePickerQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this people picker query
*/
function ClientPeoplePickerQuery(baseUrl, path) {
if (path === void 0) { path = "_api/sp.ui.applicationpages.clientpeoplepickerwebserviceinterface"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
ClientPeoplePickerQuery.prototype.clientPeoplePickerResolveUser = function (queryParams) {
var q = this.clone(ClientPeoplePickerQuery, null);
q.concat(".clientpeoplepickerresolveuser");
return q.postCore({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
}).then(function (json) { return JSON.parse(json); });
};
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
ClientPeoplePickerQuery.prototype.clientPeoplePickerSearchUser = function (queryParams) {
var q = this.clone(ClientPeoplePickerQuery, null);
q.concat(".clientpeoplepickersearchuser");
return q.postCore({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
}).then(function (json) { return JSON.parse(json); });
};
/**
* Creates ClientPeoplePickerQueryParameters request body
*
* @param queryParams The query parameters to create request body
*/
ClientPeoplePickerQuery.prototype.createClientPeoplePickerQueryParametersRequestBody = function (queryParams) {
return JSON.stringify({
"queryParams": common.extend({
"__metadata": { "type": "SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters" },
}, queryParams),
});
};
return ClientPeoplePickerQuery;
}(SharePointQueryable));
/**
* Exposes social following methods
*/
var SocialQuery = /** @class */ (function (_super) {
tslib_1.__extends(SocialQuery, _super);
/**
* Creates a new instance of the SocialQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this social query
*/
function SocialQuery(baseUrl, path) {
if (path === void 0) { path = "_api/social.following"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(SocialQuery.prototype, "my", {
get: function () {
return new MySocialQuery(this);
},
enumerable: true,
configurable: true
});
/**
* Gets a URI to a site that lists the current user's followed sites.
*/
SocialQuery.prototype.getFollowedSitesUri = function () {
return this.clone(SocialQuery, "FollowedSitesUri").get().then(function (r) {
return r.FollowedSitesUri || r;
});
};
/**
* Gets a URI to a site that lists the current user's followed documents.
*/
SocialQuery.prototype.getFollowedDocumentsUri = function () {
return this.clone(SocialQuery, "FollowedDocumentsUri").get().then(function (r) {
return r.FollowedDocumentsUri || r;
});
};
/**
* Makes the current user start following a user, document, site, or tag
*
* @param actorInfo The actor to start following
*/
SocialQuery.prototype.follow = function (actorInfo) {
return this.clone(SocialQuery, "follow").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Indicates whether the current user is following a specified user, document, site, or tag
*
* @param actorInfo The actor to find the following status for
*/
SocialQuery.prototype.isFollowed = function (actorInfo) {
return this.clone(SocialQuery, "isfollowed").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Makes the current user stop following a user, document, site, or tag
*
* @param actorInfo The actor to stop following
*/
SocialQuery.prototype.stopFollowing = function (actorInfo) {
return this.clone(SocialQuery, "stopfollowing").postCore({ body: this.createSocialActorInfoRequestBody(actorInfo) });
};
/**
* Creates SocialActorInfo request body
*
* @param actorInfo The actor to create request body
*/
SocialQuery.prototype.createSocialActorInfoRequestBody = function (actorInfo) {
return JSON.stringify({
"actor": common.extend({
Id: null,
"__metadata": { "type": "SP.Social.SocialActorInfo" },
}, actorInfo),
});
};
return SocialQuery;
}(SharePointQueryableInstance));
var MySocialQuery = /** @class */ (function (_super) {
tslib_1.__extends(MySocialQuery, _super);
/**
* Creates a new instance of the SocialQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this social query
*/
function MySocialQuery(baseUrl, path) {
if (path === void 0) { path = "my"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
MySocialQuery.prototype.followed = function (types) {
return this.clone(MySocialQuery, "followed(types=" + types + ")").get().then(function (r) {
return r.hasOwnProperty("Followed") ? r.Followed.results : r;
});
};
/**
* Gets the count of users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
MySocialQuery.prototype.followedCount = function (types) {
return this.clone(MySocialQuery, "followedcount(types=" + types + ")").get().then(function (r) {
return r.FollowedCount || r;
});
};
/**
* Gets the users who are following the current user.
*/
MySocialQuery.prototype.followers = function () {
return this.clone(MySocialQuery, "followers").get().then(function (r) {
return r.hasOwnProperty("Followers") ? r.Followers.results : r;
});
};
/**
* Gets users who the current user might want to follow.
*/
MySocialQuery.prototype.suggestions = function () {
return this.clone(MySocialQuery, "suggestions").get().then(function (r) {
return r.hasOwnProperty("Suggestions") ? r.Suggestions.results : r;
});
};
return MySocialQuery;
}(SharePointQueryableInstance));
/**
* Allows for calling of the static SP.Utilities.Utility methods by supplying the method name
*/
var UtilityMethod = /** @class */ (function (_super) {
tslib_1.__extends(UtilityMethod, _super);
/**
* Creates a new instance of the Utility method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function UtilityMethod(baseUrl, methodName) {
return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this;
}
UtilityMethod.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
UtilityMethod.prototype.excute = function (props) {
return this.postCore({
body: JSON.stringify(props),
});
};
/**
* Sends an email based on the supplied properties
*
* @param props The properties of the email to send
*/
UtilityMethod.prototype.sendEmail = function (props) {
var params = {
properties: {
Body: props.Body,
From: props.From,
Subject: props.Subject,
"__metadata": { "type": "SP.Utilities.EmailProperties" },
},
};
if (props.To && props.To.length > 0) {
params.properties = common.extend(params.properties, {
To: { results: props.To },
});
}
if (props.CC && props.CC.length > 0) {
params.properties = common.extend(params.properties, {
CC: { results: props.CC },
});
}
if (props.BCC && props.BCC.length > 0) {
params.properties = common.extend(params.properties, {
BCC: { results: props.BCC },
});
}
if (props.AdditionalHeaders) {
params.properties = common.extend(params.properties, {
AdditionalHeaders: props.AdditionalHeaders,
});
}
return this.clone(UtilityMethod, "SendEmail", true).excute(params);
};
UtilityMethod.prototype.getCurrentUserEmailAddresses = function () {
return this.clone(UtilityMethod, "GetCurrentUserEmailAddresses", true).excute({});
};
UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) {
if (matchUserInfoList === void 0) { matchUserInfoList = false; }
var params = {
addToUserInfoList: addToUserInfoList,
input: input,
inputIsEmailOnly: inputIsEmailOnly,
matchUserInfoList: matchUserInfoList,
scopes: scopes,
sources: sources,
};
return this.clone(UtilityMethod, "ResolvePrincipalInCurrentContext", true).excute(params);
};
UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) {
var params = {
groupName: groupName,
input: input,
maxCount: maxCount,
scopes: scopes,
sources: sources,
};
return this.clone(UtilityMethod, "SearchPrincipalsUsingContextWeb", true).excute(params);
};
UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) {
var params = {
pageAddress: pageAddress,
};
return this.clone(UtilityMethod, "CreateEmailBodyForInvitation", true).excute(params);
};
UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) {
if (maxCount === void 0) { maxCount = 30; }
var params = {
inputs: inputs,
maxCount: maxCount,
};
return this.clone(UtilityMethod, "ExpandGroupsToPrincipals", true).excute(params);
};
UtilityMethod.prototype.createWikiPage = function (info) {
return this.clone(UtilityMethod, "CreateWikiPageInContextWeb", true).excute({
parameters: info,
}).then(function (r) {
return {
data: r,
file: new File(spExtractODataId(r)),
};
});
};
return UtilityMethod;
}(SharePointQueryable));
/**
* Root of the SharePoint REST module
*/
var SPRest = /** @class */ (function () {
/**
* Creates a new instance of the SPRest class
*
* @param options Additional options
* @param baseUrl A string that should form the base part of the url
*/
function SPRest(_options, _baseUrl) {
if (_options === void 0) { _options = {}; }
if (_baseUrl === void 0) { _baseUrl = ""; }
this._options = _options;
this._baseUrl = _baseUrl;
}
/**
* Configures instance with additional options and baseUrl.
* Provided configuration used by other objects in a chain
*
* @param options Additional options
* @param baseUrl A string that should form the base part of the url
*/
SPRest.prototype.configure = function (options, baseUrl) {
if (baseUrl === void 0) { baseUrl = ""; }
return new SPRest(options, baseUrl);
};
/**
* Global SharePoint configuration options
*
* @param config The SharePoint configuration to apply
*/
SPRest.prototype.setup = function (config) {
setup(config);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.searchSuggest = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { querytext: query };
}
else {
finalQuery = query;
}
return this.create(SearchSuggest).execute(finalQuery);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.search = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { Querytext: query };
}
else if (query instanceof SearchQueryBuilder) {
finalQuery = query.toSearchQuery();
}
else {
finalQuery = query;
}
return this.create(Search).execute(finalQuery);
};
Object.defineProperty(SPRest.prototype, "site", {
/**
* Begins a site collection scoped REST request
*
*/
get: function () {
return this.create(Site);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "web", {
/**
* Begins a web scoped REST request
*
*/
get: function () {
return this.create(Web);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "profiles", {
/**
* Access to user profile methods
*
*/
get: function () {
return this.create(UserProfileQuery);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "social", {
/**
* Access to social methods
*/
get: function () {
return this.create(SocialQuery);
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "navigation", {
/**
* Access to the site collection level navigation service
*/
get: function () {
return new NavigationService();
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch object for use with the SharePointQueryable.addToBatch method
*
*/
SPRest.prototype.createBatch = function () {
return this.web.createBatch();
};
Object.defineProperty(SPRest.prototype, "utility", {
/**
* Static utilities methods from SP.Utilities.Utility
*/
get: function () {
return this.create(UtilityMethod, "");
},
enumerable: true,
configurable: true
});
/**
* Handles creating and configuring the objects returned from this class
*
* @param fm The factory method used to create the instance
* @param path Optional additional path information to pass to the factory method
*/
SPRest.prototype.create = function (fm, path) {
return new fm(this._baseUrl, path).configure(this._options);
};
return SPRest;
}());
var sp = new SPRest();
exports.spExtractODataId = spExtractODataId;
exports.spODataEntity = spODataEntity;
exports.spODataEntityArray = spODataEntityArray;
exports.SharePointQueryable = SharePointQueryable;
exports.SharePointQueryableInstance = SharePointQueryableInstance;
exports.SharePointQueryableCollection = SharePointQueryableCollection;
exports.SharePointQueryableSecurable = SharePointQueryableSecurable;
exports.FileFolderShared = FileFolderShared;
exports.SharePointQueryableShareable = SharePointQueryableShareable;
exports.SharePointQueryableShareableFile = SharePointQueryableShareableFile;
exports.SharePointQueryableShareableFolder = SharePointQueryableShareableFolder;
exports.SharePointQueryableShareableItem = SharePointQueryableShareableItem;
exports.SharePointQueryableShareableWeb = SharePointQueryableShareableWeb;
exports.AppCatalog = AppCatalog;
exports.App = App;
exports.ContentType = ContentType;
exports.ContentTypes = ContentTypes;
exports.FieldLink = FieldLink;
exports.FieldLinks = FieldLinks;
exports.Field = Field;
exports.Fields = Fields;
exports.File = File;
exports.Files = Files;
exports.Folder = Folder;
exports.Folders = Folders;
exports.SPHttpClient = SPHttpClient;
exports.Item = Item;
exports.Items = Items;
exports.ItemVersion = ItemVersion;
exports.ItemVersions = ItemVersions;
exports.PagedItemCollection = PagedItemCollection;
exports.NavigationNodes = NavigationNodes;
exports.NavigationNode = NavigationNode;
exports.NavigationService = NavigationService;
exports.List = List;
exports.Lists = Lists;
exports.RegionalSettings = RegionalSettings;
exports.InstalledLanguages = InstalledLanguages;
exports.TimeZone = TimeZone;
exports.TimeZones = TimeZones;
exports.sp = sp;
exports.SPRest = SPRest;
exports.RoleDefinitionBindings = RoleDefinitionBindings;
exports.Search = Search;
exports.SearchQueryBuilder = SearchQueryBuilder;
exports.SearchResults = SearchResults;
exports.SearchBuiltInSourceId = SearchBuiltInSourceId;
exports.SearchSuggest = SearchSuggest;
exports.SearchSuggestResult = SearchSuggestResult;
exports.Site = Site;
exports.UtilityMethod = UtilityMethod;
exports.WebPartDefinitions = WebPartDefinitions;
exports.WebPartDefinition = WebPartDefinition;
exports.WebPart = WebPart;
exports.Web = Web;
exports.ClientSidePage = ClientSidePage;
exports.CanvasSection = CanvasSection;
exports.CanvasControl = CanvasControl;
exports.CanvasColumn = CanvasColumn;
exports.ClientSidePart = ClientSidePart;
exports.ClientSideText = ClientSideText;
exports.ClientSideWebpart = ClientSideWebpart;
exports.SocialQuery = SocialQuery;
exports.MySocialQuery = MySocialQuery;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=sp.es5.umd.js.map
|
CKEDITOR.plugins.setLang("easyimage","tt",{commands:{fullImage:"Full Size Image",sideImage:"Side Image",altText:"Change image alternative text",upload:"Рәсем йөкләргә"},uploadFailed:"Your image could not be uploaded due to a network error."}); |
define(['../../extends', './abstract-simple-constraint'], function(__extends, AbstractSimpleConstraint) {
'use strict';
__extends(EmptyConstraint, AbstractSimpleConstraint);
function EmptyConstraint() {
AbstractSimpleConstraint.apply(this, arguments);
}
Object.defineProperty(EmptyConstraint.prototype, 'recommendedEnd', {
get: function() {
return undefined;
},
enumerable: true,
configurable: true
});
return EmptyConstraint;
});
|
(function (global) {
var closeToc = function() {
$(".tocify-wrapper").removeClass('open');
$("#nav-button").removeClass('open');
};
var makeToc = function() {
global.toc = $("#toc").tocify({
selectors: 'h1, h2',
extendPage: false,
theme: 'none',
smoothScroll: false,
showEffectSpeed: 0,
hideEffectSpeed: 180,
ignoreSelector: '.toc-ignore',
highlightOffset: 60,
scrollTo: 50,
scrollHistory: true,
hashGenerator: function (text, element) {
return element.prop('id');
}
}).data('toc-tocify');
$("#nav-button").click(function() {
$(".tocify-wrapper").toggleClass('open');
$("#nav-button").toggleClass('open');
return false;
});
$(".page-wrapper").click(closeToc);
$(".tocify-item").click(closeToc);
};
// Hack to make already open sections to start opened,
// instead of displaying an ugly animation
function animate () {
setTimeout(function() {
toc.setOption('showEffectSpeed', 180);
}, 50);
}
$(makeToc);
$(animate);
})(window);
|
import path from 'path';
import resolve from '@rollup/plugin-node-resolve';
import filesize from 'rollup-plugin-filesize';
import { terser } from 'rollup-plugin-terser';
import { visualizer } from 'rollup-plugin-visualizer';
import { glconstants, glsl } from '../utils/build/rollup.config';
import chalk from 'chalk';
const statsFile = path.resolve( __dirname, './treeshake/stats.html' );
function logStatsFile() {
return {
writeBundle() {
console.log();
console.log( 'Open the following url in a browser to analyze the tree-shaken bundle.' );
console.log( chalk.blue.bold.underline( statsFile ) );
console.log();
}
};
}
export default [
{
input: 'test/treeshake/index.js',
plugins: [
resolve(),
],
output: [
{
format: 'esm',
file: 'test/treeshake/index.bundle.js'
}
]
},
{
input: 'test/treeshake/index.js',
plugins: [
resolve(),
terser(),
filesize( {
showMinifiedSize: false,
} ),
],
output: [
{
format: 'esm',
file: 'test/treeshake/index.bundle.min.js'
}
]
},
{
input: 'test/treeshake/index-src.js',
plugins: [
glconstants(),
glsl(),
terser(),
visualizer( {
filename: statsFile,
} ),
logStatsFile(),
],
output: [
{
format: 'esm',
file: 'test/treeshake/index-src.bundle.min.js'
}
]
},
];
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v17.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var agCheckbox_1 = require("../../widgets/agCheckbox");
var beanStub_1 = require("../../context/beanStub");
var context_1 = require("../../context/context");
var columnApi_1 = require("../../columnController/columnApi");
var gridApi_1 = require("../../gridApi");
var events_1 = require("../../events");
var eventService_1 = require("../../eventService");
var constants_1 = require("../../constants");
var selectionController_1 = require("../../selectionController");
var gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var SelectAllFeature = (function (_super) {
__extends(SelectAllFeature, _super);
function SelectAllFeature(cbSelectAll, column) {
var _this = _super.call(this) || this;
_this.cbSelectAllVisible = false;
_this.processingEventFromCheckbox = false;
_this.cbSelectAll = cbSelectAll;
_this.column = column;
var colDef = column.getColDef();
_this.filteredOnly = colDef ? !!colDef.headerCheckboxSelectionFilteredOnly : false;
return _this;
}
SelectAllFeature.prototype.postConstruct = function () {
this.showOrHideSelectAll();
this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.showOrHideSelectAll.bind(this));
this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_SELECTION_CHANGED, this.onSelectionChanged.bind(this));
this.addDestroyableEventListener(this.eventService, events_1.Events.EVENT_MODEL_UPDATED, this.onModelChanged.bind(this));
this.addDestroyableEventListener(this.cbSelectAll, agCheckbox_1.AgCheckbox.EVENT_CHANGED, this.onCbSelectAll.bind(this));
};
SelectAllFeature.prototype.showOrHideSelectAll = function () {
this.cbSelectAllVisible = this.isCheckboxSelection();
this.cbSelectAll.setVisible(this.cbSelectAllVisible);
if (this.cbSelectAllVisible) {
// in case user is trying this feature with the wrong model type
this.checkRightRowModelType();
// make sure checkbox is showing the right state
this.updateStateOfCheckbox();
}
};
SelectAllFeature.prototype.onModelChanged = function () {
if (!this.cbSelectAllVisible) {
return;
}
this.updateStateOfCheckbox();
};
SelectAllFeature.prototype.onSelectionChanged = function () {
if (!this.cbSelectAllVisible) {
return;
}
this.updateStateOfCheckbox();
};
SelectAllFeature.prototype.getNextCheckboxState = function (selectionCount) {
if (selectionCount.selected === 0 && selectionCount.notSelected === 0) {
// if no rows, always have it unselected
return false;
}
else if (selectionCount.selected > 0 && selectionCount.notSelected > 0) {
// if mix of selected and unselected, this is the tri-state
return null;
}
else if (selectionCount.selected > 0) {
// only selected
return true;
}
else {
// nothing selected
return false;
}
};
SelectAllFeature.prototype.updateStateOfCheckbox = function () {
if (this.processingEventFromCheckbox) {
return;
}
this.processingEventFromCheckbox = true;
var selectionCount = this.getSelectionCount();
var allSelected = this.getNextCheckboxState(selectionCount);
this.cbSelectAll.setSelected(allSelected);
this.processingEventFromCheckbox = false;
};
SelectAllFeature.prototype.getSelectionCount = function () {
var selectedCount = 0;
var notSelectedCount = 0;
var callback = function (node) {
if (node.isSelected()) {
selectedCount++;
}
else if (!node.selectable) {
// don't count non-selectable nodes!
}
else {
notSelectedCount++;
}
};
if (this.filteredOnly) {
this.gridApi.forEachNodeAfterFilter(callback);
}
else {
this.gridApi.forEachNode(callback);
}
return {
notSelected: notSelectedCount,
selected: selectedCount
};
};
SelectAllFeature.prototype.checkRightRowModelType = function () {
var rowModelType = this.rowModel.getType();
var rowModelMatches = rowModelType === constants_1.Constants.ROW_MODEL_TYPE_IN_MEMORY;
if (!rowModelMatches) {
console.log("ag-Grid: selectAllCheckbox is only available if using normal row model, you are using " + rowModelType);
}
};
SelectAllFeature.prototype.onCbSelectAll = function () {
if (this.processingEventFromCheckbox) {
return;
}
if (!this.cbSelectAllVisible) {
return;
}
var value = this.cbSelectAll.isSelected();
if (value) {
this.selectionController.selectAllRowNodes(this.filteredOnly);
}
else {
this.selectionController.deselectAllRowNodes(this.filteredOnly);
}
};
SelectAllFeature.prototype.isCheckboxSelection = function () {
var result = this.column.getColDef().headerCheckboxSelection;
if (typeof result === 'function') {
var func = result;
result = func({
column: this.column,
colDef: this.column.getColDef(),
columnApi: this.columnApi,
api: this.gridApi
});
}
if (result) {
if (this.gridOptionsWrapper.isRowModelEnterprise()) {
console.warn('headerCheckboxSelection is not supported for Enterprise Row Model');
return false;
}
if (this.gridOptionsWrapper.isRowModelInfinite()) {
console.warn('headerCheckboxSelection is not supported for Infinite Row Model');
return false;
}
if (this.gridOptionsWrapper.isRowModelViewport()) {
console.warn('headerCheckboxSelection is not supported for Viewport Row Model');
return false;
}
// otherwise the row model is compatible, so return true
return true;
}
else {
return false;
}
};
__decorate([
context_1.Autowired('gridApi'),
__metadata("design:type", gridApi_1.GridApi)
], SelectAllFeature.prototype, "gridApi", void 0);
__decorate([
context_1.Autowired('columnApi'),
__metadata("design:type", columnApi_1.ColumnApi)
], SelectAllFeature.prototype, "columnApi", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], SelectAllFeature.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('rowModel'),
__metadata("design:type", Object)
], SelectAllFeature.prototype, "rowModel", void 0);
__decorate([
context_1.Autowired('selectionController'),
__metadata("design:type", selectionController_1.SelectionController)
], SelectAllFeature.prototype, "selectionController", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], SelectAllFeature.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], SelectAllFeature.prototype, "postConstruct", null);
return SelectAllFeature;
}(beanStub_1.BeanStub));
exports.SelectAllFeature = SelectAllFeature;
|
import {inject} from 'aurelia-dependency-injection';
import {BoundViewFactory, ViewSlot, customAttribute, templateController} from 'aurelia-templating';
@customAttribute('with')
@templateController
@inject(BoundViewFactory, ViewSlot)
export class With {
constructor(viewFactory, viewSlot){
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
}
valueChanged(newValue){
if(!this.view){
this.view = this.viewFactory.create(newValue);
this.viewSlot.add(this.view);
}else{
this.view.bind(newValue);
}
}
}
|
/*
* /MathJax/jax/output/PlainSource/config.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax.PlainSource=MathJax.OutputJax({id:"PlainSource",version:"2.7.4",directory:MathJax.OutputJax.directory+"/PlainSource",extensionDir:MathJax.OutputJax.extensionDir+"/PlainSource",config:{styles:{".MathJax_PlainSource_Display":{"text-align":"center",margin:".75em 0px","white-space":"pre"},".MathJax_PlainSource_Display > span":{display:"inline-block","text-align":"left"}}}});if(!MathJax.Hub.config.delayJaxRegistration){MathJax.OutputJax.PlainSource.Register("jax/mml")}MathJax.OutputJax.PlainSource.loadComplete("config.js");
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
separator: ';'
},
dist: {
src: ['lib/**/*.js'],
dest: 'dist/<%= pkg.name %>.js'
}
},
uglify: {
options: {
banner: '/* <%= pkg.name %>.min.js (v<%= pkg.version %>) <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
dist: {
files: {
'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
sass: {
dist: {
files: [
{
expand: true,
cwd: 'lib/sass/',
src: ['**/*.scss'],
dest: 'dist/css/',
ext: '.css',
filter: function (filepath) {
// Don't include variables and utilities
var filename = filepath.slice((filepath.lastIndexOf('/') + 1), filepath.length);
if (filename == '_variables.scss' || filename == '_utilities.scss') return false;
return true;
}
}
]
}
},
cssmin: {
options: {
banner: '/* <%= pkg.name %>.min.css (v<%= pkg.version %>) <%= grunt.template.today("dd-mm-yyyy") %> */\n'
},
combine: {
files: [
{ src: ['dist/css/holo-dark/*.css'], dest: 'dist/themes/holo-dark/holo-dark.min.css' }
/* Add your other themes here */
]
}
},
jshint: {
files: ['Gruntfile.js', 'lib/**/*.js'],
options: {
globals: {
jQuery: false,
console: true,
module: true,
document: true
}
}
},
copy: {
fonts: {
files: [
{
expand: true,
cwd: 'lib/',
src: ['fonts/*'],
dest: 'dist/',
filter: 'isFile'
}
]
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.registerTask('default', ['jshint', 'concat', 'uglify', 'sass', 'cssmin', 'copy']);
grunt.registerTask('dist-js', ['jshint', 'concat', 'uglify']);
grunt.registerTask('dist-css', ['sass', 'cssmin', 'copy']);
}; |
/**
* @license Angulartics v0.17.0
* (c) 2013 Luis Farzati http://luisfarzati.github.io/angulartics
* Google Tag Manager Plugin Contributed by http://github.com/danrowe49
* License: MIT
*/
(function(angular){
'use strict';
/**
* @ngdoc overview
* @name angulartics.google.analytics
* Enables analytics support for Google Tag Manager (http://google.com/tagmanager)
*/
angular.module('angulartics.google.tagmanager', ['angulartics'])
.config(['$analyticsProvider', function($analyticsProvider){
/**
* Send content views to the dataLayer
*
* @param {string} path Required 'content name' (string) describes the content loaded
*/
$analyticsProvider.registerPageTrack(function(path){
var dataLayer = window.dataLayer = window.dataLayer || [];
dataLayer.push({
'event': 'content-view',
'content-name': path
});
});
/**
* Send interactions to the dataLayer, i.e. for event tracking in Google Analytics
* @name eventTrack
*
* @param {string} action Required 'action' (string) associated with the event
* @param {object} properties Comprised of the mandatory field 'category' (string) and optional fields 'label' (string), 'value' (integer) and 'noninteraction' (boolean)
*/
$analyticsProvider.registerEventTrack(function(action, properties){
var dataLayer = window.dataLayer = window.dataLayer || [];
dataLayer.push({
'event': 'interaction',
'target': properties.category,
'action': action,
'target-properties': properties.label,
'value': properties.value,
'interaction-type': properties.noninteraction
});
});
}]);
})(angular);
|
var React = require('react/addons');
var Lab = require('lab');
var Code = require('code');
var ControlGroup = require('../../../../client/components/form/ControlGroup');
var lab = exports.lab = Lab.script();
var TestUtils = React.addons.TestUtils;
lab.experiment('ControlGroup', function () {
lab.test('it renders normally', function (done) {
var props = {
children: 'Hi'
};
var ControlGroupEl = React.createElement(ControlGroup, props);
var controlGroup = TestUtils.renderIntoDocument(ControlGroupEl);
Code.expect(controlGroup.getDOMNode().textContent).to.equal('Hi');
done();
});
lab.test('it renders without label or help elements', function (done) {
var props = {
children: 'Hi',
hideLabel: true,
hideHelp: true
};
var ControlGroupEl = React.createElement(ControlGroup, props);
var controlGroup = TestUtils.renderIntoDocument(ControlGroupEl);
var labelEls = TestUtils.scryRenderedDOMComponentsWithTag(controlGroup, 'label');
var helpEls = TestUtils.scryRenderedDOMComponentsWithClass(controlGroup, 'help-block');
Code.expect(labelEls.length).to.equal(0);
Code.expect(helpEls.length).to.equal(0);
done();
});
});
|
'use strict';
var document = require('global/document');
var hg = require('../index.js');
var h = require('../index.js').h;
var SafeHook = require('./lib/safe-hook.js');
function App() {
return hg.state({
height: hg.value(180),
weight: hg.value(80),
bmi: hg.value(calcBmi(180, 80)),
channels: {
heightChange: updateData.bind(null, 'height'),
weightChange: updateData.bind(null, 'weight'),
bmiChange: updateData.bind(null, 'bmi')
}
});
}
function updateData(type, state, data) {
state[type].set(Number(data.slider));
if (type !== 'bmi') {
state.bmi.set(calcBmi(state.height(), state.weight()));
} else {
state.weight.set(calcWeight(state.height(), state.bmi()));
}
}
function calcWeight(height, bmi) {
var meterz = height / 100;
return meterz * meterz * bmi;
}
function calcBmi(height, weight) {
var meterz = height / 100;
return weight / (meterz * meterz);
}
App.render = function render(state) {
var channels = state.channels;
var color = state.bmi < 18.5 ? 'orange' :
state.bmi < 25 ? 'inherit' :
state.bmi < 30 ? 'orange' : 'red';
var diagnose = state.bmi < 18.5 ? 'underweight' :
state.bmi < 25 ? 'normal' :
state.bmi < 30 ? 'overweight' : 'obese';
return h('div', [
h('h3', 'BMI calculator'),
h('div.weight', [
'Weight: ' + ~~state.weight + 'kg',
slider(state.weight, channels.weightChange, 30, 150)
]),
h('div.height', [
'Height: ' + ~~state.height + 'cm',
slider(state.height, channels.heightChange, 100, 220)
]),
h('div.bmi', [
'BMI: ' + ~~state.bmi + ' ',
h('span.diagnose', {
style: { color: color }
}, diagnose),
slider(state.bmi, channels.bmiChange, 10, 50)
])
]);
};
function slider(value, channel, min, max) {
return h('input.slider', {
type: SafeHook('range'), // SafeHook for IE9 + type='range'
min: min, max: max, value: String(value),
style: { width: '100%' }, name: 'slider',
'ev-event': hg.sendChange(channel)
});
}
hg.app(document.body, App(), App.render);
|
/**
* +--------------------------------------------------------------------+
* | This HTML_CodeSniffer file is Copyright (c) |
* | Squiz Pty Ltd (ABN 77 084 670 600) |
* +--------------------------------------------------------------------+
* | IMPORTANT: Your use of this Software is subject to the terms of |
* | the Licence provided in the file licence.txt. If you cannot find |
* | this file please contact Squiz (www.squiz.com.au) so we may |
* | provide you a copy. |
* +--------------------------------------------------------------------+
*
*/
var HTMLCS_WCAG2AAA_Sniffs_Principle1_Guideline1_2_1_2_7 = {
/**
* Determines the elements to register for processing.
*
* Each element of the returned array can either be an element name, or "_top"
* which is the top element of the tested code.
*
* @returns {Array} The list of elements.
*/
register: function()
{
return [
'object',
'embed',
'applet',
'video'
];
},
/**
* Process the registered element.
*
* @param {DOMNode} element The element registered.
* @param {DOMNode} top The top element of the tested code.
*/
process: function(element, top)
{
// Check for elements that could potentially contain video.
HTMLCS.addMessage(HTMLCS.NOTICE, element, 'If this embedded object contains synchronised media, and where pauses in foreground audio is not sufficient to allow audio descriptions to convey the sense of pre-recorded video, check that an extended audio description is provided, either through scripting or an alternate version.', 'G8');
}
};
|
/*
Copyright ©2014 Esri. All rights reserved.
TRADE SECRETS: ESRI PROPRIETARY AND CONFIDENTIAL
Unpublished material - all rights reserved under the
Copyright Laws of the United States and applicable international
laws, treaties, and conventions.
For additional information, contact:
Attn: Contracts and Legal Department
Environmental Systems Research Institute, Inc.
380 New York Street
Redlands, California, 92373
USA
email: contracts@esri.com
*/
define([
'dojo/_base/array',
'jimu/LayerInfos/LayerInfos'
], function(array, LayerInfos) {
var mo = {};
mo.getLayerInfosParam = function() {
// summary:
// get layerInfos parameter for create/refresh/settingPage in legend dijit.
// description:
var layerInfosParamFromCurrentMap = getLayerInfosParamFromCurrentMap();
return layerInfosParamFromCurrentMap;
};
mo.getLayerInfosParamByConfig = function(legendConfig) {
var layerInfosParam = [];
var layerInfosParamFromCurrentMap;
if(legendConfig.layerInfos && legendConfig.layerInfos.length) {
layerInfosParamFromCurrentMap = getLayerInfosParamFromCurrentMap();
// respect config
array.forEach(layerInfosParamFromCurrentMap, function(layerInfoParam) {
var layerInfoConfig = getLayerInfoConfigById(legendConfig, layerInfoParam.jimuLayerInfo.id);
if(layerInfoConfig) {
layerInfoParam.hideLayers = layerInfoConfig.hideLayers;
layerInfosParam.push(layerInfoParam);
}
});
}
return layerInfosParam;
};
var getLayerInfosParamFromCurrentMap = function() {
var layerInfosParam = [];
var jimuLayerInfos = LayerInfos.getInstanceSync();
var jimuLayerInfoArray = jimuLayerInfos.getLayerInfoArray();
array.forEach(jimuLayerInfoArray, function(topLayerInfo) {
var hideLayers = [];
if(topLayerInfo.getShowLegendOfWebmap()) {
// temporary code.
if(topLayerInfo.layerObject &&
(topLayerInfo.layerObject.declaredClass === 'esri.layers.ArcGISDynamicMapServiceLayer' ||
topLayerInfo.layerObject.declaredClass === 'esri.layers.ArcGISTiledMapServiceLayer')) {
topLayerInfo.traversal(function(layerInfo) {
if(layerInfo.isLeaf() && !layerInfo.getShowLegendOfWebmap()) {
hideLayers.push(layerInfo.originOperLayer.mapService.subId);
}
});
}
// add to layerInfosparam
if(topLayerInfo.isMapNotesLayerInfo()) {
array.forEach(topLayerInfo.getSubLayers(), function(mapNotesSubLayerInfo) {
var layerInfoParam = {
layer: mapNotesSubLayerInfo.layerObject,
title: "Map Notes - " + mapNotesSubLayerInfo.title
};
layerInfosParam.push(layerInfoParam);
});
} else {
var layerInfoParam = {
hideLayers: hideLayers,
layer: topLayerInfo.layerObject,
title: topLayerInfo.title
};
layerInfosParam.push(layerInfoParam);
}
}
});
return layerInfosParam.reverse();
};
var getLayerInfoConfigById = function(legendConfig, id) {
var layerInfoConfig = array.filter(legendConfig.layerInfos, function(layerInfoConfig) {
var result = false;
if(layerInfoConfig.id === id) {
result = true;
}
return result;
});
return layerInfoConfig[0];
};
return mo;
});
|
/*
* Sphinx builder specific JS code.
*/
var rtddata = require('./rtd-data'),
sphinx_theme = require('sphinx-rtd-theme');
function init() {
var rtd = rtddata.get();
/// Click tracking on flyout
$(document).on('click', "[data-toggle='rst-current-version']", function() {
var flyout_state = $("[data-toggle='rst-versions']").hasClass('shift-up') ? 'was_open' : 'was_closed'
if (_gaq) {
_gaq.push(
['rtfd._setAccount', 'UA-17997319-1'],
['rtfd._trackEvent', 'Flyout', 'Click', flyout_state]
);
}
});
/// Read the Docs Sphinx theme code
if (!("builder" in rtd) || "builder" in rtd && rtd["builder"] != "mkdocs") {
var theme = sphinx_theme.ThemeNav;
// TODO dont do this, the theme should explicitly check when it has be
// already enabled. See:
// https://github.com/snide/sphinx_rtd_theme/issues/250
$(document).ready(function () {
setTimeout(function() {
if (!theme.navBar) {
theme.enable();
}
}, 1000);
});
if (rtd.is_rtd_theme()) {
// Because generated HTML will not immediately have the new
// scroll element, gracefully handle failover by adding it
// dynamically.
var navBar = jquery('div.wy-side-scroll:first');
if (! navBar.length) {
var navInner = jquery('nav.wy-nav-side:first'),
navScroll = $('<div />')
.addClass('wy-side-scroll');
navInner
.children()
.detach()
.appendTo(navScroll);
navScroll.prependTo(navInner);
theme.navBar = navScroll;
}
}
}
}
module.exports = {
init: init
};
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
function reframe(target, cName) {
var frames = typeof target === 'string' ? document.querySelectorAll(target) : target;
var c = cName || 'js-reframe';
if (!('length' in frames)) frames = [frames];
for (var i = 0; i < frames.length; i += 1) {
var frame = frames[i];
var hasClass = frame.className.split(' ').indexOf(c) !== -1;
if (hasClass) continue;
var hAttr = frame.getAttribute('height');
var wAttr = frame.getAttribute('width');
if (wAttr.indexOf('%') > -1 || frame.style.width.indexOf('%') > -1) continue;
var h = hAttr || frame.offsetHeight;
var w = wAttr || frame.offsetWidth;
var padding = h / w * 100;
var div = document.createElement('div');
div.className = c;
var divStyles = div.style;
divStyles.position = 'relative';
divStyles.width = '100%';
divStyles.paddingTop = padding + "%";
var frameStyle = frame.style;
frameStyle.position = 'absolute';
frameStyle.width = '100%';
frameStyle.height = '100%';
frameStyle.left = '0';
frameStyle.top = '0';
frame.parentNode.insertBefore(div, frame);
frame.parentNode.removeChild(frame);
div.appendChild(frame);
}
}
if (typeof window !== 'undefined') {
var plugin = window.$ || window.jQuery || window.Zepto;
if (plugin) {
plugin.fn.reframe = function reframePlugin(cName) {
reframe(this, cName);
};
}
}
})));
|
/* line 1 "ragel/i18n/pa.js.rl" */
;(function() {
/* line 126 "ragel/i18n/pa.js.rl" */
/* line 11 "js/lib/gherkin/lexer/pa.js" */
var _lexer_actions = [
0, 1, 0, 1, 1, 1, 2, 1,
3, 1, 4, 1, 5, 1, 6, 1,
7, 1, 8, 1, 9, 1, 10, 1,
11, 1, 12, 1, 13, 1, 16, 1,
17, 1, 18, 1, 19, 1, 20, 1,
21, 1, 22, 1, 23, 2, 2, 18,
2, 3, 4, 2, 13, 0, 2, 14,
15, 2, 17, 0, 2, 17, 1, 2,
17, 16, 2, 17, 19, 2, 18, 6,
2, 18, 7, 2, 18, 8, 2, 18,
9, 2, 18, 10, 2, 18, 16, 2,
20, 21, 2, 22, 0, 2, 22, 1,
2, 22, 16, 2, 22, 19, 3, 4,
14, 15, 3, 5, 14, 15, 3, 11,
14, 15, 3, 12, 14, 15, 3, 13,
14, 15, 3, 14, 15, 18, 3, 17,
0, 11, 3, 17, 14, 15, 4, 2,
14, 15, 18, 4, 3, 4, 14, 15,
4, 17, 0, 14, 15, 5, 17, 0,
11, 14, 15
];
var _lexer_key_offsets = [
0, 0, 12, 13, 21, 22, 23, 24,
25, 26, 27, 28, 30, 32, 43, 44,
45, 47, 49, 54, 59, 64, 69, 73,
77, 79, 80, 81, 82, 83, 84, 85,
86, 87, 88, 89, 90, 91, 92, 93,
94, 99, 106, 111, 115, 121, 124, 126,
132, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 161, 162, 163, 164, 165,
166, 167, 174, 176, 180, 182, 184, 186,
188, 190, 192, 194, 196, 198, 200, 202,
204, 206, 208, 210, 212, 223, 225, 227,
229, 231, 233, 235, 237, 239, 241, 243,
245, 247, 249, 251, 253, 255, 257, 259,
261, 263, 265, 267, 269, 271, 273, 275,
277, 279, 281, 283, 285, 287, 289, 291,
293, 295, 297, 299, 301, 303, 305, 307,
309, 310, 311, 312, 313, 314, 315, 316,
317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 335, 337, 343, 345, 347,
349, 351, 353, 355, 357, 359, 361, 363,
365, 367, 369, 371, 373, 375, 377, 379,
381, 383, 385, 387, 389, 391, 393, 395,
397, 399, 401, 403, 405, 407, 409, 411,
413, 415, 417, 419, 421, 423, 425, 427,
429, 431, 433, 435, 437, 439, 441, 443,
445, 447, 449, 451, 453, 455, 457, 459,
461, 463, 465, 468, 470, 472, 474, 476,
478, 480, 482, 484, 486, 489, 491, 493,
496, 498, 500, 502, 504, 506, 508, 510,
512, 514, 516, 518, 520, 522, 524, 526,
528, 530, 532, 534, 536, 538, 540, 542,
544, 546, 548, 550, 552, 554, 556, 558,
560, 562, 564, 566, 568, 570, 572, 574,
576, 578, 580, 582, 584, 586, 588, 590,
592, 594, 596, 598, 600, 602, 604, 606,
608, 610, 612, 614, 616, 618, 620, 622,
624, 626, 628, 630, 632, 634, 636, 638,
640, 641, 643, 645, 646, 647, 648, 649,
650, 651, 652, 653, 654, 655, 656, 657,
658, 659, 660, 661, 662, 663, 664, 665,
666, 667, 668, 669, 670, 671, 672, 673,
674, 675, 676, 677, 678, 679, 680, 681,
682, 683, 684, 685, 686, 687, 688, 689,
690, 691, 692, 693, 694, 695, 696, 697,
698, 699, 700, 701, 704, 705, 706, 707,
708, 709, 710, 711, 712, 713, 715, 716,
717, 719, 720, 721, 722, 723, 724, 725,
726, 727, 728, 729, 730, 731, 732, 733,
734, 743, 745, 753, 755, 757, 759, 761,
763, 765, 767, 769, 771, 773, 775, 777,
779, 781, 783, 785, 787, 789, 791, 793,
795, 797, 799, 801, 804, 807, 809, 811,
813, 815, 817, 819, 821, 823, 825, 827,
829, 831, 833, 835, 837, 839, 841, 843,
845, 847, 849, 851, 853, 855, 857, 859,
861, 863, 865, 867, 869, 871, 873, 875,
877, 879, 881, 883, 885, 887, 889, 891,
893, 895, 897, 899, 901, 903, 905, 907,
909, 911, 913, 915, 917, 919, 922, 924,
926, 928, 930, 932, 934, 936, 938, 940,
942, 944, 946, 948, 950, 952, 954, 956,
958, 960, 962, 964, 966, 968, 970, 972,
974, 976, 978, 980, 982, 984, 986, 988,
990, 992, 994, 996, 998, 1000, 1002, 1004,
1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012,
1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020,
1021, 1022, 1031, 1033, 1041, 1043, 1045, 1047,
1049, 1051, 1053, 1055, 1057, 1059, 1061, 1063,
1065, 1067, 1069, 1071, 1073, 1075, 1077, 1079,
1081, 1083, 1085, 1087, 1089, 1092, 1095, 1097,
1099, 1101, 1103, 1105, 1107, 1109, 1111, 1113,
1115, 1117, 1119, 1121, 1123, 1125, 1127, 1129,
1131, 1133, 1135, 1137, 1139, 1141, 1143, 1145,
1147, 1149, 1151, 1153, 1155, 1157, 1159, 1161,
1163, 1165, 1167, 1169, 1171, 1173, 1175, 1177,
1179, 1181, 1183, 1185, 1187, 1189, 1191, 1193,
1195, 1197, 1199, 1201, 1203, 1205, 1207, 1211,
1213, 1215, 1217, 1219, 1221, 1223, 1225, 1227,
1229, 1232, 1234, 1236, 1239, 1241, 1243, 1245,
1247, 1249, 1251, 1253, 1255, 1257, 1259, 1261,
1263, 1265, 1267, 1269, 1271, 1273, 1275, 1277,
1279, 1281, 1283, 1285, 1287, 1289, 1291, 1293,
1295, 1297, 1299, 1301, 1303, 1305, 1307, 1309,
1311, 1313, 1315, 1317, 1319, 1321, 1323, 1325,
1327, 1329, 1331, 1333, 1335, 1337, 1339, 1341,
1343, 1345, 1347, 1349, 1351, 1353, 1355, 1357,
1359, 1361, 1363, 1365, 1367, 1369, 1371, 1373,
1375, 1377, 1379, 1381, 1383, 1384, 1385, 1386,
1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394,
1395, 1396, 1397, 1398, 1407, 1409, 1417, 1419,
1421, 1423, 1425, 1427, 1429, 1431, 1433, 1435,
1437, 1439, 1441, 1443, 1445, 1447, 1449, 1451,
1453, 1455, 1457, 1459, 1461, 1463, 1465, 1468,
1471, 1473, 1475, 1477, 1479, 1481, 1483, 1485,
1487, 1489, 1491, 1493, 1495, 1497, 1499, 1501,
1503, 1505, 1507, 1509, 1511, 1513, 1515, 1517,
1519, 1521, 1523, 1525, 1527, 1529, 1531, 1533,
1535, 1537, 1539, 1541, 1543, 1545, 1547, 1549,
1551, 1553, 1555, 1557, 1559, 1561, 1563, 1565,
1567, 1569, 1571, 1573, 1575, 1577, 1579, 1581,
1583, 1586, 1588, 1590, 1592, 1594, 1596, 1598,
1600, 1602, 1604, 1607, 1609, 1611, 1614, 1616,
1618, 1620, 1622, 1624, 1626, 1628, 1630, 1632,
1634, 1636, 1638, 1640, 1642, 1644, 1646, 1648,
1650, 1652, 1654, 1656, 1658, 1660, 1662, 1664,
1666, 1668, 1670, 1672, 1674, 1676, 1678, 1680,
1682, 1684, 1686, 1688, 1690, 1692, 1694, 1696,
1698, 1700, 1702, 1704, 1706, 1708, 1710, 1712,
1714, 1716, 1718, 1720, 1722, 1724, 1726, 1728,
1730, 1732, 1734, 1735, 1736, 1737, 1738, 1739,
1740, 1741, 1742, 1743, 1744, 1745, 1746, 1747,
1748, 1749, 1750, 1751, 1752, 1753, 1754, 1755,
1756, 1757
];
var _lexer_trans_keys = [
-32, 10, 32, 34, 35, 37, 42, 64,
124, 239, 9, 13, -88, -123, -119, -106,
-100, -92, -88, -86, -82, -32, -88, -92,
-32, -87, -121, 32, 10, 13, 10, 13,
-32, 10, 32, 34, 35, 37, 42, 64,
124, 9, 13, 34, 34, 10, 13, 10,
13, 10, 32, 34, 9, 13, 10, 32,
34, 9, 13, 10, 32, 34, 9, 13,
10, 32, 34, 9, 13, 10, 32, 9,
13, 10, 32, 9, 13, 10, 13, 10,
95, 70, 69, 65, 84, 85, 82, 69,
95, 69, 78, 68, 95, 37, 13, 32,
64, 9, 10, 9, 10, 13, 32, 64,
11, 12, 10, 32, 64, 9, 13, 32,
124, 9, 13, 10, 32, 92, 124, 9,
13, 10, 92, 124, 10, 92, 10, 32,
92, 124, 9, 13, -32, 10, 32, 34,
35, 37, 42, 64, 124, 9, 13, -32,
-88, -90, -32, -88, -66, -32, -88, -71,
-32, -88, -80, -32, -88, -88, -32, -88,
-66, -32, -88, -126, 58, 10, 10, -32,
10, 32, 35, 124, 9, 13, -88, 10,
-106, -88, -82, 10, -32, 10, -88, 10,
-66, 10, -32, 10, -88, 10, -72, 10,
-32, 10, -87, 10, -128, 10, -32, 10,
-88, 10, -123, 10, -32, 10, -88, 10,
-92, 10, 10, 58, -32, 10, 32, 34,
35, 37, 42, 64, 124, 9, 13, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -74, 10, 10, 32, -32, 10, -88,
10, -88, 10, -32, 10, -87, 10, -127,
10, -32, 10, -88, 10, -71, 10, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -80, 10, -32, 10, -87, 10, -127,
10, -32, 10, -88, 10, -71, 10, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -126, 10, -32, 10, -88, 10, -90,
10, -32, 10, -88, 10, -80, 10, -32,
10, -88, 10, -66, 10, -32, -88, -66,
-32, -88, -72, -32, -87, -128, -32, -88,
-123, -32, -88, -92, 58, 10, 10, -32,
10, 32, 35, 37, 64, 9, 13, -88,
10, -119, -106, -88, -86, -82, 10, -32,
10, -88, 10, -90, 10, -32, 10, -88,
10, -66, 10, -32, 10, -88, 10, -71,
10, -32, 10, -88, 10, -80, 10, -32,
10, -88, 10, -88, 10, -32, 10, -88,
10, -66, 10, -32, 10, -88, 10, -126,
10, 10, 58, -32, 10, -88, 10, -66,
10, -32, 10, -88, 10, -72, 10, -32,
10, -87, 10, -128, 10, -32, 10, -88,
10, -123, 10, -32, 10, -88, 10, -92,
10, -32, 10, -88, 10, -107, 10, -32,
10, -88, 10, -74, 10, 10, 32, -32,
10, -88, 10, -88, 10, -32, 10, -87,
10, -127, 10, -32, 10, -88, 10, -71,
10, -32, 10, -88, 10, -66, 10, -32,
10, -88, 10, -80, 10, -32, 10, -88,
10, -97, -65, 10, -32, 10, -88, 10,
-107, 10, -32, 10, -88, 10, -91, 10,
-32, 10, -88, 10, -66, 10, 10, 32,
58, -32, 10, -88, 10, -94, -80, 10,
-32, 10, -88, 10, -66, 10, -32, 10,
-88, 10, -126, 10, -32, 10, -88, 10,
-102, 10, -32, 10, -88, 10, -66, 10,
-32, 10, -87, 10, -126, 10, -32, 10,
-88, 10, -86, 10, 10, 32, -32, 10,
-88, 10, -80, 10, -32, 10, -87, 10,
-121, 10, -32, 10, -88, 10, -106, 10,
-32, 10, -88, 10, -101, 10, -32, 10,
-87, 10, -117, 10, -32, 10, -88, 10,
-107, 10, -32, 10, -87, 10, -100, 10,
-32, 10, -87, 10, -127, 10, -32, 10,
-88, 10, -71, 10, -32, 10, -88, 10,
-66, 10, -32, 10, -88, 10, -126, 10,
-32, 10, -88, 10, -90, 10, -32, 10,
-88, 10, -80, 10, 10, 95, 10, 70,
10, 69, 10, 65, 10, 84, 10, 85,
10, 82, 10, 69, 10, 95, 10, 69,
10, 78, 10, 68, 10, 95, 10, 37,
-32, -88, -87, -90, -65, -32, -87, -117,
-32, -88, -126, -32, -88, -75, -32, -87,
-121, -32, -88, -126, 32, -32, -88, -107,
-32, -88, -65, -121, -32, -88, -107, -32,
-88, -80, -32, -88, -90, -32, -88, -107,
-32, -88, -74, 32, -32, -88, -88, -32,
-87, -127, -32, -88, -71, -32, -88, -66,
-32, -88, -80, -32, -88, -97, -80, -65,
-32, -88, -107, -32, -88, -91, -32, -88,
-66, 32, 58, -32, -88, -94, -80, -32,
-88, -66, -32, -88, -126, -32, -88, -102,
-32, -88, -66, 58, 10, 10, -32, 10,
32, 35, 37, 42, 64, 9, 13, -88,
10, -123, -106, -100, -92, -88, -86, -82,
10, -32, 10, -88, 10, -92, 10, -32,
10, -87, 10, -121, 10, 10, 32, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -72, 10, -32, 10, -87, 10, -128,
10, -32, 10, -88, 10, -123, 10, -32,
10, -88, 10, -92, 10, 10, 58, -32,
10, -88, -87, 10, -90, -65, 10, -32,
10, -87, 10, -117, 10, -32, 10, -88,
10, -126, 10, -32, 10, -88, 10, -75,
10, -32, 10, -87, 10, -121, 10, -32,
10, -88, 10, -126, 10, 10, 32, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -65, 10, -121, 10, -32, 10, -88,
10, -107, 10, -32, 10, -88, 10, -80,
10, -32, 10, -88, 10, -90, 10, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -74, 10, 10, 32, -32, 10, -88,
10, -88, 10, -32, 10, -87, 10, -127,
10, -32, 10, -88, 10, -71, 10, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -80, 10, -32, 10, -88, 10, -97,
-80, 10, -32, 10, -88, 10, -107, 10,
-32, 10, -88, 10, -91, 10, -32, 10,
-88, 10, -66, 10, -32, 10, -87, 10,
-127, 10, -32, 10, -88, 10, -71, 10,
-32, 10, -88, 10, -66, 10, -32, 10,
-88, 10, -126, 10, -32, 10, -88, 10,
-90, 10, -32, 10, -88, 10, -80, 10,
10, 95, 10, 70, 10, 69, 10, 65,
10, 84, 10, 85, 10, 82, 10, 69,
10, 95, 10, 69, 10, 78, 10, 68,
10, 95, 10, 37, -32, -87, -126, -32,
-88, -86, 32, -32, -88, -80, -32, -87,
-121, -32, -88, -106, 10, 10, -32, 10,
32, 35, 37, 42, 64, 9, 13, -88,
10, -123, -106, -100, -92, -88, -86, -82,
10, -32, 10, -88, 10, -92, 10, -32,
10, -87, 10, -121, 10, 10, 32, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -72, 10, -32, 10, -87, 10, -128,
10, -32, 10, -88, 10, -123, 10, -32,
10, -88, 10, -92, 10, 10, 58, -32,
10, -88, -87, 10, -90, -65, 10, -32,
10, -87, 10, -117, 10, -32, 10, -88,
10, -126, 10, -32, 10, -88, 10, -75,
10, -32, 10, -87, 10, -121, 10, -32,
10, -88, 10, -126, 10, 10, 32, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -65, 10, -121, 10, -32, 10, -88,
10, -107, 10, -32, 10, -88, 10, -80,
10, -32, 10, -88, 10, -90, 10, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -74, 10, 10, 32, -32, 10, -88,
10, -88, 10, -32, 10, -87, 10, -127,
10, -32, 10, -88, 10, -71, 10, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -80, 10, -32, 10, -88, 10, -97,
-80, -65, 10, -32, 10, -88, 10, -107,
10, -32, 10, -88, 10, -91, 10, -32,
10, -88, 10, -66, 10, 10, 32, 58,
-32, 10, -88, 10, -94, -80, 10, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -126, 10, -32, 10, -88, 10, -102,
10, -32, 10, -88, 10, -66, 10, -32,
10, -87, 10, -126, 10, -32, 10, -88,
10, -86, 10, 10, 32, -32, 10, -88,
10, -80, 10, -32, 10, -87, 10, -121,
10, -32, 10, -88, 10, -106, 10, -32,
10, -88, 10, -101, 10, -32, 10, -87,
10, -117, 10, -32, 10, -88, 10, -107,
10, -32, 10, -87, 10, -100, 10, -32,
10, -87, 10, -127, 10, -32, 10, -88,
10, -71, 10, -32, 10, -88, 10, -66,
10, -32, 10, -88, 10, -126, 10, -32,
10, -88, 10, -90, 10, -32, 10, -88,
10, -80, 10, 10, 95, 10, 70, 10,
69, 10, 65, 10, 84, 10, 85, 10,
82, 10, 69, 10, 95, 10, 69, 10,
78, 10, 68, 10, 95, 10, 37, -32,
-88, -101, -32, -87, -117, -32, -88, -107,
-32, -87, -100, 58, 10, 10, -32, 10,
32, 35, 37, 42, 64, 9, 13, -88,
10, -123, -106, -100, -92, -88, -86, -82,
10, -32, 10, -88, 10, -92, 10, -32,
10, -87, 10, -121, 10, 10, 32, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -72, 10, -32, 10, -87, 10, -128,
10, -32, 10, -88, 10, -123, 10, -32,
10, -88, 10, -92, 10, 10, 58, -32,
10, -88, -87, 10, -90, -65, 10, -32,
10, -87, 10, -117, 10, -32, 10, -88,
10, -126, 10, -32, 10, -88, 10, -75,
10, -32, 10, -87, 10, -121, 10, -32,
10, -88, 10, -126, 10, 10, 32, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -65, 10, -121, 10, -32, 10, -88,
10, -107, 10, -32, 10, -88, 10, -80,
10, -32, 10, -88, 10, -90, 10, -32,
10, -88, 10, -107, 10, -32, 10, -88,
10, -74, 10, 10, 32, -32, 10, -88,
10, -88, 10, -32, 10, -87, 10, -127,
10, -32, 10, -88, 10, -71, 10, -32,
10, -88, 10, -66, 10, -32, 10, -88,
10, -80, 10, -32, 10, -88, 10, -97,
-80, 10, -32, 10, -88, 10, -107, 10,
-32, 10, -88, 10, -91, 10, -32, 10,
-88, 10, -66, 10, 10, 32, 58, -32,
10, -88, 10, -94, -80, 10, -32, 10,
-88, 10, -66, 10, -32, 10, -88, 10,
-126, 10, -32, 10, -88, 10, -102, 10,
-32, 10, -88, 10, -66, 10, -32, 10,
-87, 10, -126, 10, -32, 10, -88, 10,
-86, 10, 10, 32, -32, 10, -88, 10,
-80, 10, -32, 10, -87, 10, -121, 10,
-32, 10, -88, 10, -106, 10, -32, 10,
-87, 10, -127, 10, -32, 10, -88, 10,
-71, 10, -32, 10, -88, 10, -66, 10,
-32, 10, -88, 10, -126, 10, -32, 10,
-88, 10, -90, 10, -32, 10, -88, 10,
-80, 10, 10, 95, 10, 70, 10, 69,
10, 65, 10, 84, 10, 85, 10, 82,
10, 69, 10, 95, 10, 69, 10, 78,
10, 68, 10, 95, 10, 37, -32, -87,
-127, -32, -88, -71, -32, -88, -66, -32,
-88, -126, -32, -88, -90, -32, -88, -80,
-32, -88, -66, 187, 191, 0
];
var _lexer_single_lengths = [
0, 10, 1, 8, 1, 1, 1, 1,
1, 1, 1, 2, 2, 9, 1, 1,
2, 2, 3, 3, 3, 3, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
3, 5, 3, 2, 4, 3, 2, 4,
9, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 5, 2, 4, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 9, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 6, 2, 6, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 3, 2, 2, 2, 2, 2,
2, 2, 2, 2, 3, 2, 2, 3,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 2, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 3, 1, 1, 1, 1,
1, 1, 1, 1, 1, 2, 1, 1,
2, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
7, 2, 8, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 3, 3, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 3, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 7, 2, 8, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 3, 3, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 4, 2,
2, 2, 2, 2, 2, 2, 2, 2,
3, 2, 2, 3, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 7, 2, 8, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
3, 2, 2, 2, 2, 2, 2, 2,
2, 2, 3, 2, 2, 3, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1,
1, 0
];
var _lexer_range_lengths = [
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 1, 1, 1, 1, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 0, 0, 1,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0
];
var _lexer_index_offsets = [
0, 0, 12, 14, 23, 25, 27, 29,
31, 33, 35, 37, 40, 43, 54, 56,
58, 61, 64, 69, 74, 79, 84, 88,
92, 95, 97, 99, 101, 103, 105, 107,
109, 111, 113, 115, 117, 119, 121, 123,
125, 130, 137, 142, 146, 152, 156, 159,
165, 176, 178, 180, 182, 184, 186, 188,
190, 192, 194, 196, 198, 200, 202, 204,
206, 208, 210, 212, 214, 216, 218, 220,
222, 224, 231, 234, 239, 242, 245, 248,
251, 254, 257, 260, 263, 266, 269, 272,
275, 278, 281, 284, 287, 298, 301, 304,
307, 310, 313, 316, 319, 322, 325, 328,
331, 334, 337, 340, 343, 346, 349, 352,
355, 358, 361, 364, 367, 370, 373, 376,
379, 382, 385, 388, 391, 394, 397, 400,
403, 406, 409, 412, 415, 418, 421, 424,
427, 429, 431, 433, 435, 437, 439, 441,
443, 445, 447, 449, 451, 453, 455, 457,
459, 461, 463, 471, 474, 481, 484, 487,
490, 493, 496, 499, 502, 505, 508, 511,
514, 517, 520, 523, 526, 529, 532, 535,
538, 541, 544, 547, 550, 553, 556, 559,
562, 565, 568, 571, 574, 577, 580, 583,
586, 589, 592, 595, 598, 601, 604, 607,
610, 613, 616, 619, 622, 625, 628, 631,
634, 637, 640, 643, 646, 649, 652, 655,
658, 661, 664, 668, 671, 674, 677, 680,
683, 686, 689, 692, 695, 699, 702, 705,
709, 712, 715, 718, 721, 724, 727, 730,
733, 736, 739, 742, 745, 748, 751, 754,
757, 760, 763, 766, 769, 772, 775, 778,
781, 784, 787, 790, 793, 796, 799, 802,
805, 808, 811, 814, 817, 820, 823, 826,
829, 832, 835, 838, 841, 844, 847, 850,
853, 856, 859, 862, 865, 868, 871, 874,
877, 880, 883, 886, 889, 892, 895, 898,
901, 904, 907, 910, 913, 916, 919, 922,
925, 927, 930, 933, 935, 937, 939, 941,
943, 945, 947, 949, 951, 953, 955, 957,
959, 961, 963, 965, 967, 969, 971, 973,
975, 977, 979, 981, 983, 985, 987, 989,
991, 993, 995, 997, 999, 1001, 1003, 1005,
1007, 1009, 1011, 1013, 1015, 1017, 1019, 1021,
1023, 1025, 1027, 1029, 1031, 1033, 1035, 1037,
1039, 1041, 1043, 1045, 1049, 1051, 1053, 1055,
1057, 1059, 1061, 1063, 1065, 1067, 1070, 1072,
1074, 1077, 1079, 1081, 1083, 1085, 1087, 1089,
1091, 1093, 1095, 1097, 1099, 1101, 1103, 1105,
1107, 1116, 1119, 1128, 1131, 1134, 1137, 1140,
1143, 1146, 1149, 1152, 1155, 1158, 1161, 1164,
1167, 1170, 1173, 1176, 1179, 1182, 1185, 1188,
1191, 1194, 1197, 1200, 1204, 1208, 1211, 1214,
1217, 1220, 1223, 1226, 1229, 1232, 1235, 1238,
1241, 1244, 1247, 1250, 1253, 1256, 1259, 1262,
1265, 1268, 1271, 1274, 1277, 1280, 1283, 1286,
1289, 1292, 1295, 1298, 1301, 1304, 1307, 1310,
1313, 1316, 1319, 1322, 1325, 1328, 1331, 1334,
1337, 1340, 1343, 1346, 1349, 1352, 1355, 1358,
1361, 1364, 1367, 1370, 1373, 1376, 1380, 1383,
1386, 1389, 1392, 1395, 1398, 1401, 1404, 1407,
1410, 1413, 1416, 1419, 1422, 1425, 1428, 1431,
1434, 1437, 1440, 1443, 1446, 1449, 1452, 1455,
1458, 1461, 1464, 1467, 1470, 1473, 1476, 1479,
1482, 1485, 1488, 1491, 1494, 1497, 1500, 1503,
1505, 1507, 1509, 1511, 1513, 1515, 1517, 1519,
1521, 1523, 1525, 1527, 1529, 1531, 1533, 1535,
1537, 1539, 1548, 1551, 1560, 1563, 1566, 1569,
1572, 1575, 1578, 1581, 1584, 1587, 1590, 1593,
1596, 1599, 1602, 1605, 1608, 1611, 1614, 1617,
1620, 1623, 1626, 1629, 1632, 1636, 1640, 1643,
1646, 1649, 1652, 1655, 1658, 1661, 1664, 1667,
1670, 1673, 1676, 1679, 1682, 1685, 1688, 1691,
1694, 1697, 1700, 1703, 1706, 1709, 1712, 1715,
1718, 1721, 1724, 1727, 1730, 1733, 1736, 1739,
1742, 1745, 1748, 1751, 1754, 1757, 1760, 1763,
1766, 1769, 1772, 1775, 1778, 1781, 1784, 1787,
1790, 1793, 1796, 1799, 1802, 1805, 1808, 1813,
1816, 1819, 1822, 1825, 1828, 1831, 1834, 1837,
1840, 1844, 1847, 1850, 1854, 1857, 1860, 1863,
1866, 1869, 1872, 1875, 1878, 1881, 1884, 1887,
1890, 1893, 1896, 1899, 1902, 1905, 1908, 1911,
1914, 1917, 1920, 1923, 1926, 1929, 1932, 1935,
1938, 1941, 1944, 1947, 1950, 1953, 1956, 1959,
1962, 1965, 1968, 1971, 1974, 1977, 1980, 1983,
1986, 1989, 1992, 1995, 1998, 2001, 2004, 2007,
2010, 2013, 2016, 2019, 2022, 2025, 2028, 2031,
2034, 2037, 2040, 2043, 2046, 2049, 2052, 2055,
2058, 2061, 2064, 2067, 2070, 2072, 2074, 2076,
2078, 2080, 2082, 2084, 2086, 2088, 2090, 2092,
2094, 2096, 2098, 2100, 2109, 2112, 2121, 2124,
2127, 2130, 2133, 2136, 2139, 2142, 2145, 2148,
2151, 2154, 2157, 2160, 2163, 2166, 2169, 2172,
2175, 2178, 2181, 2184, 2187, 2190, 2193, 2197,
2201, 2204, 2207, 2210, 2213, 2216, 2219, 2222,
2225, 2228, 2231, 2234, 2237, 2240, 2243, 2246,
2249, 2252, 2255, 2258, 2261, 2264, 2267, 2270,
2273, 2276, 2279, 2282, 2285, 2288, 2291, 2294,
2297, 2300, 2303, 2306, 2309, 2312, 2315, 2318,
2321, 2324, 2327, 2330, 2333, 2336, 2339, 2342,
2345, 2348, 2351, 2354, 2357, 2360, 2363, 2366,
2369, 2373, 2376, 2379, 2382, 2385, 2388, 2391,
2394, 2397, 2400, 2404, 2407, 2410, 2414, 2417,
2420, 2423, 2426, 2429, 2432, 2435, 2438, 2441,
2444, 2447, 2450, 2453, 2456, 2459, 2462, 2465,
2468, 2471, 2474, 2477, 2480, 2483, 2486, 2489,
2492, 2495, 2498, 2501, 2504, 2507, 2510, 2513,
2516, 2519, 2522, 2525, 2528, 2531, 2534, 2537,
2540, 2543, 2546, 2549, 2552, 2555, 2558, 2561,
2564, 2567, 2570, 2573, 2576, 2579, 2582, 2585,
2588, 2591, 2594, 2596, 2598, 2600, 2602, 2604,
2606, 2608, 2610, 2612, 2614, 2616, 2618, 2620,
2622, 2624, 2626, 2628, 2630, 2632, 2634, 2636,
2638, 2640
];
var _lexer_indicies = [
1, 3, 2, 4, 5, 6, 7, 8,
9, 10, 2, 0, 11, 0, 12, 13,
14, 15, 16, 17, 18, 19, 0, 20,
0, 21, 0, 22, 0, 23, 0, 24,
0, 25, 0, 26, 0, 28, 29, 27,
31, 32, 30, 1, 3, 2, 4, 5,
6, 7, 8, 9, 2, 0, 33, 0,
34, 0, 36, 37, 35, 39, 40, 38,
43, 42, 44, 42, 41, 47, 46, 48,
46, 45, 47, 46, 49, 46, 45, 47,
46, 50, 46, 45, 52, 51, 51, 0,
3, 53, 53, 0, 55, 56, 54, 3,
0, 57, 0, 58, 0, 59, 0, 60,
0, 61, 0, 62, 0, 63, 0, 64,
0, 65, 0, 66, 0, 67, 0, 68,
0, 69, 0, 70, 0, 0, 0, 0,
0, 71, 72, 73, 72, 72, 75, 74,
71, 3, 76, 8, 76, 0, 77, 78,
77, 0, 81, 80, 82, 83, 80, 79,
0, 85, 86, 84, 0, 85, 84, 81,
87, 85, 86, 87, 84, 88, 81, 89,
90, 91, 92, 93, 94, 95, 89, 0,
96, 0, 97, 0, 98, 0, 99, 0,
100, 0, 101, 0, 102, 0, 103, 0,
104, 0, 105, 0, 106, 0, 107, 0,
108, 0, 109, 0, 110, 0, 111, 0,
112, 0, 113, 0, 114, 0, 115, 0,
116, 0, 117, 0, 119, 118, 121, 120,
122, 121, 123, 124, 124, 123, 120, 125,
121, 120, 126, 127, 128, 121, 120, 129,
121, 120, 130, 121, 120, 131, 121, 120,
132, 121, 120, 133, 121, 120, 134, 121,
120, 135, 121, 120, 136, 121, 120, 137,
121, 120, 138, 121, 120, 139, 121, 120,
140, 121, 120, 141, 121, 120, 142, 121,
120, 143, 121, 120, 121, 144, 120, 145,
147, 146, 148, 149, 150, 151, 152, 153,
146, 0, 154, 121, 120, 155, 121, 120,
156, 121, 120, 157, 121, 120, 158, 121,
120, 159, 121, 120, 121, 160, 120, 161,
121, 120, 162, 121, 120, 163, 121, 120,
164, 121, 120, 165, 121, 120, 166, 121,
120, 167, 121, 120, 168, 121, 120, 169,
121, 120, 170, 121, 120, 171, 121, 120,
172, 121, 120, 173, 121, 120, 174, 121,
120, 143, 121, 120, 175, 121, 120, 176,
121, 120, 177, 121, 120, 178, 121, 120,
179, 121, 120, 180, 121, 120, 181, 121,
120, 182, 121, 120, 183, 121, 120, 184,
121, 120, 185, 121, 120, 186, 121, 120,
187, 121, 120, 188, 121, 120, 189, 121,
120, 190, 121, 120, 191, 121, 120, 192,
121, 120, 193, 121, 120, 194, 121, 120,
143, 121, 120, 195, 0, 196, 0, 197,
0, 198, 0, 199, 0, 200, 0, 201,
0, 202, 0, 203, 0, 204, 0, 205,
0, 206, 0, 207, 0, 208, 0, 209,
0, 210, 0, 212, 211, 214, 213, 215,
214, 216, 217, 218, 217, 216, 213, 219,
214, 213, 220, 221, 222, 223, 224, 214,
213, 225, 214, 213, 226, 214, 213, 227,
214, 213, 228, 214, 213, 229, 214, 213,
230, 214, 213, 231, 214, 213, 232, 214,
213, 233, 214, 213, 234, 214, 213, 235,
214, 213, 236, 214, 213, 237, 214, 213,
238, 214, 213, 239, 214, 213, 240, 214,
213, 241, 214, 213, 242, 214, 213, 243,
214, 213, 244, 214, 213, 245, 214, 213,
214, 246, 213, 247, 214, 213, 248, 214,
213, 249, 214, 213, 250, 214, 213, 251,
214, 213, 252, 214, 213, 253, 214, 213,
254, 214, 213, 255, 214, 213, 256, 214,
213, 257, 214, 213, 258, 214, 213, 259,
214, 213, 260, 214, 213, 245, 214, 213,
261, 214, 213, 262, 214, 213, 263, 214,
213, 264, 214, 213, 265, 214, 213, 266,
214, 213, 214, 267, 213, 268, 214, 213,
269, 214, 213, 270, 214, 213, 271, 214,
213, 272, 214, 213, 273, 214, 213, 274,
214, 213, 275, 214, 213, 276, 214, 213,
277, 214, 213, 278, 214, 213, 279, 214,
213, 280, 214, 213, 281, 214, 213, 245,
214, 213, 282, 214, 213, 283, 214, 213,
284, 285, 214, 213, 286, 214, 213, 287,
214, 213, 288, 214, 213, 289, 214, 213,
290, 214, 213, 291, 214, 213, 292, 214,
213, 293, 214, 213, 294, 214, 213, 214,
295, 246, 213, 296, 214, 213, 297, 214,
213, 298, 299, 214, 213, 300, 214, 213,
301, 214, 213, 302, 214, 213, 303, 214,
213, 304, 214, 213, 305, 214, 213, 306,
214, 213, 307, 214, 213, 308, 214, 213,
309, 214, 213, 310, 214, 213, 245, 214,
213, 311, 214, 213, 312, 214, 213, 313,
214, 213, 314, 214, 213, 315, 214, 213,
316, 214, 213, 214, 317, 213, 318, 214,
213, 319, 214, 213, 320, 214, 213, 321,
214, 213, 322, 214, 213, 323, 214, 213,
324, 214, 213, 325, 214, 213, 308, 214,
213, 326, 214, 213, 327, 214, 213, 328,
214, 213, 329, 214, 213, 330, 214, 213,
331, 214, 213, 332, 214, 213, 333, 214,
213, 334, 214, 213, 335, 214, 213, 336,
214, 213, 245, 214, 213, 337, 214, 213,
338, 214, 213, 339, 214, 213, 340, 214,
213, 341, 214, 213, 342, 214, 213, 343,
214, 213, 344, 214, 213, 345, 214, 213,
346, 214, 213, 347, 214, 213, 348, 214,
213, 349, 214, 213, 350, 214, 213, 351,
214, 213, 352, 214, 213, 353, 214, 213,
308, 214, 213, 214, 354, 213, 214, 355,
213, 214, 356, 213, 214, 357, 213, 214,
358, 213, 214, 359, 213, 214, 360, 213,
214, 361, 213, 214, 362, 213, 214, 363,
213, 214, 364, 213, 214, 365, 213, 214,
366, 213, 214, 367, 213, 368, 0, 369,
370, 0, 371, 372, 0, 373, 0, 374,
0, 375, 0, 376, 0, 377, 0, 25,
0, 378, 0, 379, 0, 380, 0, 381,
0, 382, 0, 383, 0, 384, 0, 385,
0, 386, 0, 387, 0, 388, 0, 389,
0, 390, 0, 391, 0, 392, 0, 25,
0, 393, 0, 394, 0, 395, 0, 396,
0, 397, 0, 398, 0, 25, 0, 399,
0, 400, 0, 25, 0, 401, 0, 402,
0, 403, 0, 404, 0, 405, 0, 406,
0, 407, 0, 408, 0, 409, 0, 410,
0, 411, 0, 412, 0, 413, 0, 414,
0, 415, 0, 416, 0, 417, 0, 418,
0, 419, 0, 420, 0, 421, 0, 209,
0, 422, 0, 423, 0, 424, 25, 425,
0, 426, 0, 427, 0, 428, 0, 429,
0, 430, 0, 431, 0, 432, 0, 433,
0, 434, 0, 435, 436, 0, 437, 0,
438, 0, 439, 440, 0, 441, 0, 442,
0, 443, 0, 444, 0, 445, 0, 446,
0, 447, 0, 448, 0, 449, 0, 450,
0, 451, 0, 452, 0, 453, 0, 455,
454, 457, 456, 458, 457, 459, 460, 461,
462, 460, 459, 456, 463, 457, 456, 464,
465, 466, 467, 468, 469, 470, 457, 456,
471, 457, 456, 472, 457, 456, 473, 457,
456, 474, 457, 456, 475, 457, 456, 476,
457, 456, 457, 477, 456, 478, 457, 456,
479, 457, 456, 480, 457, 456, 481, 457,
456, 482, 457, 456, 483, 457, 456, 484,
457, 456, 485, 457, 456, 486, 457, 456,
487, 457, 456, 488, 457, 456, 489, 457,
456, 490, 457, 456, 491, 457, 456, 492,
457, 456, 457, 477, 456, 493, 457, 456,
494, 495, 457, 456, 496, 497, 457, 456,
498, 457, 456, 499, 457, 456, 500, 457,
456, 501, 457, 456, 502, 457, 456, 476,
457, 456, 503, 457, 456, 504, 457, 456,
505, 457, 456, 506, 457, 456, 507, 457,
456, 508, 457, 456, 509, 457, 456, 510,
457, 456, 511, 457, 456, 457, 512, 456,
513, 457, 456, 514, 457, 456, 515, 457,
456, 516, 457, 456, 517, 457, 456, 476,
457, 456, 518, 457, 456, 519, 457, 456,
520, 457, 456, 521, 457, 456, 522, 457,
456, 523, 457, 456, 476, 457, 456, 524,
457, 456, 525, 457, 456, 476, 457, 456,
526, 457, 456, 527, 457, 456, 528, 457,
456, 529, 457, 456, 530, 457, 456, 531,
457, 456, 457, 532, 456, 533, 457, 456,
534, 457, 456, 535, 457, 456, 536, 457,
456, 537, 457, 456, 538, 457, 456, 539,
457, 456, 540, 457, 456, 541, 457, 456,
542, 457, 456, 543, 457, 456, 544, 457,
456, 545, 457, 456, 546, 457, 456, 492,
457, 456, 547, 457, 456, 548, 457, 456,
549, 476, 457, 456, 550, 457, 456, 551,
457, 456, 552, 457, 456, 553, 457, 456,
554, 457, 456, 555, 457, 456, 556, 457,
456, 557, 457, 456, 492, 457, 456, 558,
457, 456, 559, 457, 456, 560, 457, 456,
561, 457, 456, 562, 457, 456, 563, 457,
456, 564, 457, 456, 565, 457, 456, 566,
457, 456, 567, 457, 456, 568, 457, 456,
569, 457, 456, 570, 457, 456, 571, 457,
456, 572, 457, 456, 573, 457, 456, 574,
457, 456, 555, 457, 456, 457, 575, 456,
457, 576, 456, 457, 577, 456, 457, 578,
456, 457, 579, 456, 457, 580, 456, 457,
581, 456, 457, 582, 456, 457, 583, 456,
457, 584, 456, 457, 585, 456, 457, 586,
456, 457, 587, 456, 457, 588, 456, 589,
0, 590, 0, 591, 0, 592, 0, 593,
0, 594, 0, 595, 0, 596, 0, 597,
0, 598, 0, 599, 0, 600, 0, 601,
0, 602, 0, 603, 0, 449, 0, 605,
604, 607, 606, 608, 607, 609, 610, 611,
612, 610, 609, 606, 613, 607, 606, 614,
615, 616, 617, 618, 619, 620, 607, 606,
621, 607, 606, 622, 607, 606, 623, 607,
606, 624, 607, 606, 625, 607, 606, 626,
607, 606, 607, 627, 606, 628, 607, 606,
629, 607, 606, 630, 607, 606, 631, 607,
606, 632, 607, 606, 633, 607, 606, 634,
607, 606, 635, 607, 606, 636, 607, 606,
637, 607, 606, 638, 607, 606, 639, 607,
606, 640, 607, 606, 641, 607, 606, 642,
607, 606, 607, 627, 606, 643, 607, 606,
644, 645, 607, 606, 646, 647, 607, 606,
648, 607, 606, 649, 607, 606, 650, 607,
606, 651, 607, 606, 652, 607, 606, 626,
607, 606, 653, 607, 606, 654, 607, 606,
655, 607, 606, 656, 607, 606, 657, 607,
606, 658, 607, 606, 659, 607, 606, 660,
607, 606, 661, 607, 606, 607, 662, 606,
663, 607, 606, 664, 607, 606, 665, 607,
606, 666, 607, 606, 667, 607, 606, 626,
607, 606, 668, 607, 606, 669, 607, 606,
670, 607, 606, 671, 607, 606, 672, 607,
606, 673, 607, 606, 626, 607, 606, 674,
607, 606, 675, 607, 606, 626, 607, 606,
676, 607, 606, 677, 607, 606, 678, 607,
606, 679, 607, 606, 680, 607, 606, 681,
607, 606, 607, 682, 606, 683, 607, 606,
684, 607, 606, 685, 607, 606, 686, 607,
606, 687, 607, 606, 688, 607, 606, 689,
607, 606, 690, 607, 606, 691, 607, 606,
692, 607, 606, 693, 607, 606, 694, 607,
606, 695, 607, 606, 696, 607, 606, 642,
607, 606, 697, 607, 606, 698, 607, 606,
699, 626, 700, 607, 606, 701, 607, 606,
702, 607, 606, 703, 607, 606, 704, 607,
606, 705, 607, 606, 706, 607, 606, 707,
607, 606, 708, 607, 606, 709, 607, 606,
607, 710, 627, 606, 711, 607, 606, 712,
607, 606, 713, 714, 607, 606, 715, 607,
606, 716, 607, 606, 717, 607, 606, 718,
607, 606, 719, 607, 606, 720, 607, 606,
721, 607, 606, 722, 607, 606, 723, 607,
606, 724, 607, 606, 725, 607, 606, 642,
607, 606, 726, 607, 606, 727, 607, 606,
728, 607, 606, 729, 607, 606, 730, 607,
606, 731, 607, 606, 607, 732, 606, 733,
607, 606, 734, 607, 606, 735, 607, 606,
736, 607, 606, 737, 607, 606, 738, 607,
606, 739, 607, 606, 740, 607, 606, 723,
607, 606, 741, 607, 606, 742, 607, 606,
743, 607, 606, 744, 607, 606, 745, 607,
606, 746, 607, 606, 747, 607, 606, 748,
607, 606, 749, 607, 606, 750, 607, 606,
751, 607, 606, 642, 607, 606, 752, 607,
606, 753, 607, 606, 754, 607, 606, 755,
607, 606, 756, 607, 606, 757, 607, 606,
758, 607, 606, 759, 607, 606, 760, 607,
606, 761, 607, 606, 762, 607, 606, 763,
607, 606, 764, 607, 606, 765, 607, 606,
766, 607, 606, 767, 607, 606, 768, 607,
606, 723, 607, 606, 607, 769, 606, 607,
770, 606, 607, 771, 606, 607, 772, 606,
607, 773, 606, 607, 774, 606, 607, 775,
606, 607, 776, 606, 607, 777, 606, 607,
778, 606, 607, 779, 606, 607, 780, 606,
607, 781, 606, 607, 782, 606, 783, 0,
784, 0, 785, 0, 786, 0, 787, 0,
788, 0, 789, 0, 790, 0, 791, 0,
792, 0, 793, 0, 794, 0, 795, 0,
797, 796, 799, 798, 800, 799, 801, 802,
803, 804, 802, 801, 798, 805, 799, 798,
806, 807, 808, 809, 810, 811, 812, 799,
798, 813, 799, 798, 814, 799, 798, 815,
799, 798, 816, 799, 798, 817, 799, 798,
818, 799, 798, 799, 819, 798, 820, 799,
798, 821, 799, 798, 822, 799, 798, 823,
799, 798, 824, 799, 798, 825, 799, 798,
826, 799, 798, 827, 799, 798, 828, 799,
798, 829, 799, 798, 830, 799, 798, 831,
799, 798, 832, 799, 798, 833, 799, 798,
834, 799, 798, 799, 819, 798, 835, 799,
798, 836, 837, 799, 798, 838, 839, 799,
798, 840, 799, 798, 841, 799, 798, 842,
799, 798, 843, 799, 798, 844, 799, 798,
818, 799, 798, 845, 799, 798, 846, 799,
798, 847, 799, 798, 848, 799, 798, 849,
799, 798, 850, 799, 798, 851, 799, 798,
852, 799, 798, 853, 799, 798, 799, 854,
798, 855, 799, 798, 856, 799, 798, 857,
799, 798, 858, 799, 798, 859, 799, 798,
818, 799, 798, 860, 799, 798, 861, 799,
798, 862, 799, 798, 863, 799, 798, 864,
799, 798, 865, 799, 798, 818, 799, 798,
866, 799, 798, 867, 799, 798, 818, 799,
798, 868, 799, 798, 869, 799, 798, 870,
799, 798, 871, 799, 798, 872, 799, 798,
873, 799, 798, 799, 874, 798, 875, 799,
798, 876, 799, 798, 877, 799, 798, 878,
799, 798, 879, 799, 798, 880, 799, 798,
881, 799, 798, 882, 799, 798, 883, 799,
798, 884, 799, 798, 885, 799, 798, 886,
799, 798, 887, 799, 798, 888, 799, 798,
834, 799, 798, 889, 799, 798, 890, 799,
798, 891, 818, 799, 798, 892, 799, 798,
893, 799, 798, 894, 799, 798, 895, 799,
798, 896, 799, 798, 897, 799, 798, 898,
799, 798, 899, 799, 798, 900, 799, 798,
799, 901, 819, 798, 902, 799, 798, 903,
799, 798, 904, 905, 799, 798, 906, 799,
798, 907, 799, 798, 908, 799, 798, 909,
799, 798, 910, 799, 798, 911, 799, 798,
912, 799, 798, 913, 799, 798, 914, 799,
798, 915, 799, 798, 916, 799, 798, 834,
799, 798, 917, 799, 798, 918, 799, 798,
919, 799, 798, 920, 799, 798, 921, 799,
798, 922, 799, 798, 799, 923, 798, 924,
799, 798, 925, 799, 798, 926, 799, 798,
927, 799, 798, 928, 799, 798, 929, 799,
798, 930, 799, 798, 931, 799, 798, 914,
799, 798, 932, 799, 798, 933, 799, 798,
934, 799, 798, 935, 799, 798, 936, 799,
798, 937, 799, 798, 938, 799, 798, 939,
799, 798, 940, 799, 798, 941, 799, 798,
942, 799, 798, 943, 799, 798, 944, 799,
798, 945, 799, 798, 946, 799, 798, 947,
799, 798, 948, 799, 798, 914, 799, 798,
799, 949, 798, 799, 950, 798, 799, 951,
798, 799, 952, 798, 799, 953, 798, 799,
954, 798, 799, 955, 798, 799, 956, 798,
799, 957, 798, 799, 958, 798, 799, 959,
798, 799, 960, 798, 799, 961, 798, 799,
962, 798, 963, 0, 964, 0, 965, 0,
966, 0, 967, 0, 968, 0, 969, 0,
970, 0, 971, 0, 972, 0, 973, 0,
974, 0, 975, 0, 976, 0, 977, 0,
978, 0, 979, 0, 980, 0, 981, 0,
982, 0, 209, 0, 983, 0, 2, 0,
984, 0
];
var _lexer_trans_targs = [
0, 2, 13, 13, 14, 24, 26, 10,
40, 43, 903, 3, 4, 49, 136, 304,
336, 339, 361, 882, 5, 6, 7, 8,
9, 10, 11, 12, 13, 25, 12, 13,
25, 15, 16, 17, 18, 17, 17, 18,
17, 19, 19, 19, 20, 19, 19, 19,
20, 21, 22, 23, 13, 23, 24, 13,
25, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 905, 41,
42, 13, 41, 40, 42, 43, 44, 45,
47, 48, 46, 44, 45, 46, 44, 47,
2, 48, 14, 24, 26, 10, 40, 43,
50, 51, 52, 53, 54, 55, 56, 57,
58, 59, 60, 61, 62, 63, 64, 65,
66, 67, 68, 69, 70, 71, 72, 73,
72, 73, 74, 73, 13, 75, 76, 93,
115, 77, 78, 79, 80, 81, 82, 83,
84, 85, 86, 87, 88, 89, 90, 91,
92, 2, 13, 13, 14, 24, 26, 10,
40, 43, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 116,
117, 118, 119, 120, 121, 122, 123, 124,
125, 126, 127, 128, 129, 130, 131, 132,
133, 134, 135, 137, 138, 139, 140, 141,
142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 153, 154, 155,
154, 13, 290, 156, 157, 179, 194, 216,
272, 158, 159, 160, 161, 162, 163, 164,
165, 166, 167, 168, 169, 170, 171, 172,
173, 174, 175, 176, 177, 178, 92, 180,
181, 182, 183, 184, 185, 186, 187, 188,
189, 190, 191, 192, 193, 195, 196, 197,
198, 199, 200, 201, 202, 203, 204, 205,
206, 207, 208, 209, 210, 211, 212, 213,
214, 215, 217, 218, 219, 260, 220, 221,
222, 223, 224, 225, 226, 227, 228, 229,
230, 231, 232, 244, 233, 234, 235, 236,
237, 238, 239, 240, 241, 242, 243, 245,
246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 261, 262,
263, 264, 265, 266, 267, 268, 269, 270,
271, 273, 274, 275, 276, 277, 278, 279,
280, 281, 282, 283, 284, 285, 286, 287,
288, 289, 291, 292, 293, 294, 295, 296,
297, 298, 299, 300, 301, 302, 303, 13,
305, 306, 329, 307, 313, 308, 309, 310,
311, 312, 314, 315, 316, 317, 318, 319,
320, 321, 322, 323, 324, 325, 326, 327,
328, 330, 331, 332, 333, 334, 335, 337,
338, 340, 341, 342, 343, 344, 345, 346,
347, 348, 349, 350, 351, 352, 353, 354,
355, 356, 357, 358, 359, 360, 362, 363,
364, 708, 365, 366, 367, 368, 369, 370,
371, 372, 373, 374, 535, 375, 376, 377,
519, 378, 379, 380, 381, 382, 383, 384,
385, 386, 387, 388, 389, 390, 391, 392,
391, 392, 393, 392, 13, 505, 401, 394,
395, 402, 418, 450, 453, 475, 487, 396,
397, 398, 399, 400, 401, 92, 403, 404,
405, 406, 407, 408, 409, 410, 411, 412,
413, 414, 415, 416, 417, 419, 420, 443,
421, 427, 422, 423, 424, 425, 426, 428,
429, 430, 431, 432, 433, 434, 435, 436,
437, 438, 439, 440, 441, 442, 444, 445,
446, 447, 448, 449, 451, 452, 454, 455,
456, 457, 458, 459, 460, 461, 462, 463,
464, 465, 466, 467, 468, 469, 470, 471,
472, 473, 474, 476, 477, 478, 479, 480,
481, 482, 483, 484, 485, 486, 488, 489,
490, 491, 492, 493, 494, 495, 496, 497,
498, 499, 500, 501, 502, 503, 504, 506,
507, 508, 509, 510, 511, 512, 513, 514,
515, 516, 517, 518, 13, 520, 521, 522,
523, 524, 525, 526, 527, 528, 529, 530,
531, 532, 533, 534, 536, 537, 536, 537,
538, 537, 13, 694, 546, 539, 540, 547,
563, 595, 598, 620, 676, 541, 542, 543,
544, 545, 546, 92, 548, 549, 550, 551,
552, 553, 554, 555, 556, 557, 558, 559,
560, 561, 562, 564, 565, 588, 566, 572,
567, 568, 569, 570, 571, 573, 574, 575,
576, 577, 578, 579, 580, 581, 582, 583,
584, 585, 586, 587, 589, 590, 591, 592,
593, 594, 596, 597, 599, 600, 601, 602,
603, 604, 605, 606, 607, 608, 609, 610,
611, 612, 613, 614, 615, 616, 617, 618,
619, 621, 622, 623, 664, 624, 625, 626,
627, 628, 629, 630, 631, 632, 633, 634,
635, 636, 648, 637, 638, 639, 640, 641,
642, 643, 644, 645, 646, 647, 649, 650,
651, 652, 653, 654, 655, 656, 657, 658,
659, 660, 661, 662, 663, 665, 666, 667,
668, 669, 670, 671, 672, 673, 674, 675,
677, 678, 679, 680, 681, 682, 683, 684,
685, 686, 687, 688, 689, 690, 691, 692,
693, 695, 696, 697, 698, 699, 700, 701,
702, 703, 704, 705, 706, 707, 13, 709,
710, 711, 712, 713, 714, 715, 716, 717,
718, 719, 720, 721, 722, 723, 722, 723,
724, 723, 13, 868, 732, 725, 726, 733,
749, 781, 784, 806, 850, 727, 728, 729,
730, 731, 732, 92, 734, 735, 736, 737,
738, 739, 740, 741, 742, 743, 744, 745,
746, 747, 748, 750, 751, 774, 752, 758,
753, 754, 755, 756, 757, 759, 760, 761,
762, 763, 764, 765, 766, 767, 768, 769,
770, 771, 772, 773, 775, 776, 777, 778,
779, 780, 782, 783, 785, 786, 787, 788,
789, 790, 791, 792, 793, 794, 795, 796,
797, 798, 799, 800, 801, 802, 803, 804,
805, 807, 808, 809, 810, 811, 812, 813,
814, 815, 816, 817, 818, 819, 820, 821,
822, 834, 823, 824, 825, 826, 827, 828,
829, 830, 831, 832, 833, 835, 836, 837,
838, 839, 840, 841, 842, 843, 844, 845,
846, 847, 848, 849, 851, 852, 853, 854,
855, 856, 857, 858, 859, 860, 861, 862,
863, 864, 865, 866, 867, 869, 870, 871,
872, 873, 874, 875, 876, 877, 878, 879,
880, 881, 13, 883, 884, 885, 886, 887,
888, 889, 890, 891, 892, 893, 894, 895,
896, 897, 898, 899, 900, 901, 902, 904,
0
];
var _lexer_trans_actions = [
43, 29, 0, 54, 3, 1, 0, 29,
1, 35, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 57, 149, 126, 0, 110,
23, 0, 0, 7, 139, 48, 0, 102,
9, 5, 45, 134, 45, 0, 33, 122,
33, 33, 0, 11, 106, 0, 0, 114,
25, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
27, 118, 27, 51, 0, 0, 0, 37,
37, 54, 37, 87, 0, 0, 39, 0,
96, 0, 93, 90, 41, 96, 90, 99,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 57, 144,
0, 54, 84, 0, 81, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
21, 63, 31, 130, 60, 57, 31, 63,
57, 66, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 57, 144, 0, 54, 84,
0, 69, 33, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 13, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 13,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 57, 144,
0, 54, 84, 0, 78, 33, 84, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 19, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 19, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 57, 144, 0, 54,
84, 0, 75, 33, 84, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 17, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 17, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 57, 144, 0, 54,
84, 0, 72, 33, 84, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 15, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 15, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0
];
var _lexer_eof_actions = [
0, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43, 43, 43, 43, 43, 43, 43,
43, 43
];
var lexer_start = 1;
var lexer_first_final = 905;
var lexer_error = 0;
var lexer_en_main = 1;
/* line 129 "ragel/i18n/pa.js.rl" */
/* line 130 "ragel/i18n/pa.js.rl" */
/* line 131 "ragel/i18n/pa.js.rl" */
/* line 132 "ragel/i18n/pa.js.rl" */
var Lexer = function(listener) {
// Check that listener has the required functions
var events = ['comment', 'tag', 'feature', 'background', 'scenario', 'scenario_outline', 'examples', 'step', 'doc_string', 'row', 'eof'];
for(var i=0, len=events.length; i<len; i++) {
var event = events[i];
if(typeof listener[event] != 'function') {
throw new Error("Error. No " + event + " function exists on " + JSON.stringify(listener));
}
}
this.listener = listener;
};
Lexer.prototype.scan = function(data) {
var ending = "\n%_FEATURE_END_%";
if(typeof data == 'string') {
data = this.stringToBytes(data + ending);
} else if(typeof Buffer != 'undefined' && Buffer.isBuffer(data)) {
// Node.js
var buf = new Buffer(data.length + ending.length);
data.copy(buf, 0, 0);
new Buffer(ending).copy(buf, data.length, 0);
data = buf;
}
var eof = pe = data.length;
var p = 0;
this.line_number = 1;
this.last_newline = 0;
var signedCharValue=function(v){return v > 127 ? v-256 : v; };
/* line 1477 "js/lib/gherkin/lexer/pa.js" */
{
this.cs = lexer_start;
} /* JSCodeGen::writeInit */
/* line 164 "ragel/i18n/pa.js.rl" */
/* line 1484 "js/lib/gherkin/lexer/pa.js" */
{
var _klen, _trans, _keys, _ps, _widec, _acts, _nacts;
var _goto_level, _resume, _eof_trans, _again, _test_eof;
var _out;
_klen = _trans = _keys = _acts = _nacts = null;
_goto_level = 0;
_resume = 10;
_eof_trans = 15;
_again = 20;
_test_eof = 30;
_out = 40;
while (true) {
_trigger_goto = false;
if (_goto_level <= 0) {
if (p == pe) {
_goto_level = _test_eof;
continue;
}
if ( this.cs == 0) {
_goto_level = _out;
continue;
}
}
if (_goto_level <= _resume) {
_keys = _lexer_key_offsets[ this.cs];
_trans = _lexer_index_offsets[ this.cs];
_klen = _lexer_single_lengths[ this.cs];
_break_match = false;
do {
if (_klen > 0) {
_lower = _keys;
_upper = _keys + _klen - 1;
while (true) {
if (_upper < _lower) { break; }
_mid = _lower + ( (_upper - _lower) >> 1 );
if (( signedCharValue(data[p])) < _lexer_trans_keys[_mid]) {
_upper = _mid - 1;
} else if (( signedCharValue(data[p])) > _lexer_trans_keys[_mid]) {
_lower = _mid + 1;
} else {
_trans += (_mid - _keys);
_break_match = true;
break;
};
} /* while */
if (_break_match) { break; }
_keys += _klen;
_trans += _klen;
}
_klen = _lexer_range_lengths[ this.cs];
if (_klen > 0) {
_lower = _keys;
_upper = _keys + (_klen << 1) - 2;
while (true) {
if (_upper < _lower) { break; }
_mid = _lower + (((_upper-_lower) >> 1) & ~1);
if (( signedCharValue(data[p])) < _lexer_trans_keys[_mid]) {
_upper = _mid - 2;
} else if (( signedCharValue(data[p])) > _lexer_trans_keys[_mid+1]) {
_lower = _mid + 2;
} else {
_trans += ((_mid - _keys) >> 1);
_break_match = true;
break;
}
} /* while */
if (_break_match) { break; }
_trans += _klen
}
} while (false);
_trans = _lexer_indicies[_trans];
this.cs = _lexer_trans_targs[_trans];
if (_lexer_trans_actions[_trans] != 0) {
_acts = _lexer_trans_actions[_trans];
_nacts = _lexer_actions[_acts];
_acts += 1;
while (_nacts > 0) {
_nacts -= 1;
_acts += 1;
switch (_lexer_actions[_acts - 1]) {
case 0:
/* line 6 "ragel/i18n/pa.js.rl" */
this.content_start = p;
this.current_line = this.line_number;
this.start_col = p - this.last_newline - (this.keyword+':').length;
break;
case 1:
/* line 12 "ragel/i18n/pa.js.rl" */
this.current_line = this.line_number;
this.start_col = p - this.last_newline;
break;
case 2:
/* line 17 "ragel/i18n/pa.js.rl" */
this.content_start = p;
break;
case 3:
/* line 21 "ragel/i18n/pa.js.rl" */
this.docstring_content_type_start = p;
break;
case 4:
/* line 25 "ragel/i18n/pa.js.rl" */
this.docstring_content_type_end = p;
break;
case 5:
/* line 29 "ragel/i18n/pa.js.rl" */
var con = this.unindent(
this.start_col,
this.bytesToString(data.slice(this.content_start, this.next_keyword_start-1)).replace(/(\r?\n)?([\t ])*$/, '').replace(/\\\"\\\"\\\"/mg, '"""')
);
var con_type = this.bytesToString(data.slice(this.docstring_content_type_start, this.docstring_content_type_end)).trim();
this.listener.doc_string(con_type, con, this.current_line);
break;
case 6:
/* line 38 "ragel/i18n/pa.js.rl" */
p = this.store_keyword_content('feature', data, p, eof);
break;
case 7:
/* line 42 "ragel/i18n/pa.js.rl" */
p = this.store_keyword_content('background', data, p, eof);
break;
case 8:
/* line 46 "ragel/i18n/pa.js.rl" */
p = this.store_keyword_content('scenario', data, p, eof);
break;
case 9:
/* line 50 "ragel/i18n/pa.js.rl" */
p = this.store_keyword_content('scenario_outline', data, p, eof);
break;
case 10:
/* line 54 "ragel/i18n/pa.js.rl" */
p = this.store_keyword_content('examples', data, p, eof);
break;
case 11:
/* line 58 "ragel/i18n/pa.js.rl" */
var con = this.bytesToString(data.slice(this.content_start, p)).trim();
this.listener.step(this.keyword, con, this.current_line);
break;
case 12:
/* line 63 "ragel/i18n/pa.js.rl" */
var con = this.bytesToString(data.slice(this.content_start, p)).trim();
this.listener.comment(con, this.line_number);
this.keyword_start = null;
break;
case 13:
/* line 69 "ragel/i18n/pa.js.rl" */
var con = this.bytesToString(data.slice(this.content_start, p)).trim();
this.listener.tag(con, this.line_number);
this.keyword_start = null;
break;
case 14:
/* line 75 "ragel/i18n/pa.js.rl" */
this.line_number++;
break;
case 15:
/* line 79 "ragel/i18n/pa.js.rl" */
this.last_newline = p + 1;
break;
case 16:
/* line 83 "ragel/i18n/pa.js.rl" */
this.keyword_start = this.keyword_start || p;
break;
case 17:
/* line 87 "ragel/i18n/pa.js.rl" */
this.keyword = this.bytesToString(data.slice(this.keyword_start, p)).replace(/:$/, '');
this.keyword_start = null;
break;
case 18:
/* line 92 "ragel/i18n/pa.js.rl" */
this.next_keyword_start = p;
break;
case 19:
/* line 96 "ragel/i18n/pa.js.rl" */
p = p - 1;
current_row = [];
this.current_line = this.line_number;
break;
case 20:
/* line 102 "ragel/i18n/pa.js.rl" */
this.content_start = p;
break;
case 21:
/* line 106 "ragel/i18n/pa.js.rl" */
var con = this.bytesToString(data.slice(this.content_start, p)).trim();
current_row.push(con.replace(/\\\|/, "|").replace(/\\n/, "\n").replace(/\\\\/, "\\"));
break;
case 22:
/* line 111 "ragel/i18n/pa.js.rl" */
this.listener.row(current_row, this.current_line);
break;
case 23:
/* line 115 "ragel/i18n/pa.js.rl" */
if(this.cs < lexer_first_final) {
var content = this.current_line_content(data, p);
throw new Error("Lexing error on line " + this.line_number + ": '" + content + "'. See http://wiki.github.com/cucumber/gherkin/lexingerror for more information.");
} else {
this.listener.eof();
}
break;
/* line 1711 "js/lib/gherkin/lexer/pa.js" */
} /* action switch */
}
}
if (_trigger_goto) {
continue;
}
}
if (_goto_level <= _again) {
if ( this.cs == 0) {
_goto_level = _out;
continue;
}
p += 1;
if (p != pe) {
_goto_level = _resume;
continue;
}
}
if (_goto_level <= _test_eof) {
if (p == eof) {
__acts = _lexer_eof_actions[ this.cs];
__nacts = _lexer_actions[__acts];
__acts += 1;
while (__nacts > 0) {
__nacts -= 1;
__acts += 1;
switch (_lexer_actions[__acts - 1]) {
case 23:
/* line 115 "ragel/i18n/pa.js.rl" */
if(this.cs < lexer_first_final) {
var content = this.current_line_content(data, p);
throw new Error("Lexing error on line " + this.line_number + ": '" + content + "'. See http://wiki.github.com/cucumber/gherkin/lexingerror for more information.");
} else {
this.listener.eof();
}
break;
/* line 1750 "js/lib/gherkin/lexer/pa.js" */
} /* eof action switch */
}
if (_trigger_goto) {
continue;
}
}
}
if (_goto_level <= _out) {
break;
}
}
}
/* line 165 "ragel/i18n/pa.js.rl" */
};
/*
* Decode utf-8 byte sequence to string.
*/
var decodeUtf8 = function(bytes) {
var result = "";
var i = 0;
var wc;
var c;
while (i < bytes.length) {
/* parse as UTF-8 lead byte */
wc = bytes[i++];
if (wc < 0x80) {
count = 0;
} else if (wc < 0xC2 || wc >= 0xF8) {
throw new Error("input is not a valid UTF-8 lead octet");
} else if (wc < 0xE0) {
count = 1;
wc = (wc & 0x1F) << 6;
} else if (wc < 0xF0) {
count = 2;
wc = (wc & 0x0F) << 12;
} else /* wc < 0xF8 */ {
count = 3;
wc = (wc & 0x07) << 18;
}
/* parse trail bytes, if any */
while (count) {
if (!(i < bytes.length)) {
throw new Error("short read");
}
if ((c = bytes[i++] ^ 0x80) > 0x3F) {
throw new Error("input is not a valid UTF-8 trail octet");
}
wc |= c << (6 * --count);
if (wc < (1 << (5 * count + 6))) {
throw new Error("invalid non-minimal encoded input");
}
}
/* handle conversion to UTF-16 if needed */
if (wc > 0xFFFF) {
wc -= 0x10000;
result += String.fromCharCode(0xD800 + (wc >> 10));
wc = 0xDC00 + (wc & 0x3FF);
}
result += String.fromCharCode(wc);
}
return result;
};
/*
* Encode string to an array of bytes using utf8 encoding.
*
* Javascript internally stores character data as utf16 (like java).
* String.charCodeAt() does *not* produce unicode points, but simply
* reflects this internal representation. Thus, it is necessary
* to first decode the utf-16 representation before encoding to
* utf-8.
*/
var encodeUtf8 = function(string) {
var bytes = [];
var i = 0;
var j = 0;
var wc;
while (i < string.length) {
wc = string.charCodeAt(i++);
if (wc >= 0xD800 && wc <= 0xDBFF && i < string.length && string.charCodeAt(i) >= 0xDC00 && string.charCodeAt(i) <= 0xDFFF) {
/* decode UTF-16 */
wc = 0x10000 + ((wc & 0x3FF) << 10) + (string.charCodeAt(i++) & 0x3FF);
}
/* emit lead byte */
if (wc < 0x80) {
bytes[j++] = wc;
count = 0;
} else if (wc < 0x800) {
bytes[j++] = 0xC0 | (wc >> 6);
count = 1;
} else if (wc < 0x10000) {
bytes[j++] = 0xE0 | (wc >> 12);
count = 2;
} else {
/* SMP: 21-bit Unicode */
bytes[j++] = 0xF0 | (wc >> 18);
count = 3;
}
/* emit trail bytes, if any */
while (count) {
bytes[j++] = 0x80 | ((wc >> (6 * --count)) & 0x3F);
}
}
return bytes;
};
Lexer.prototype.bytesToString = function(bytes) {
if(typeof bytes.write == 'function') {
// Node.js
return bytes.toString('utf-8');
}
return decodeUtf8(bytes);
};
Lexer.prototype.stringToBytes = function(string) {
return encodeUtf8(string);
};
Lexer.prototype.unindent = function(startcol, text) {
startcol = startcol || 0;
return text.replace(new RegExp('^[\t ]{0,' + startcol + '}', 'gm'), '');
};
Lexer.prototype.store_keyword_content = function(event, data, p, eof) {
var end_point = (!this.next_keyword_start || (p == eof)) ? p : this.next_keyword_start;
var content = this.unindent(this.start_col + 2, this.bytesToString(data.slice(this.content_start, end_point))).replace(/\s+$/,"");
var content_lines = content.split("\n")
var name = content_lines.shift() || "";
name = name.trim();
var description = content_lines.join("\n");
this.listener[event](this.keyword, name, description, this.current_line);
var nks = this.next_keyword_start;
this.next_keyword_start = null;
return nks ? nks - 1 : p;
};
Lexer.prototype.current_line_content = function(data, p) {
var rest = Array.prototype.slice.call(data,this.last_newline, -1);
var end = rest.indexOf(10) || -1;
return this.bytesToString(rest.slice(0, end)).trim();
};
// Node.js export
if(typeof module !== 'undefined') {
module.exports = Lexer;
}
// Require.js export
if (typeof define !== 'undefined') {
if(define.amd) {
define('gherkin/lexer/pa', [], function() {
return Lexer;
});
} else {
define('gherkin/lexer/pa', function(require, exports, module) {
exports.Lexer = Lexer;
});
}
}
})();
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Circle = void 0;
const Range_1 = require("./Range");
class Circle extends Range_1.Range {
constructor(x, y, radius) {
super(x, y);
this.radius = radius;
}
contains(point) {
const d = Math.pow(point.x - this.position.x, 2) + Math.pow(point.y - this.position.y, 2);
return d <= this.radius * this.radius;
}
intersects(range) {
const rect = range;
const circle = range;
const pos1 = this.position;
const pos2 = range.position;
const xDist = Math.abs(pos2.x - pos1.x);
const yDist = Math.abs(pos2.y - pos1.y);
const r = this.radius;
if (circle.radius !== undefined) {
const rSum = r + circle.radius;
const dist = Math.sqrt(xDist * xDist + yDist + yDist);
return rSum > dist;
}
else if (rect.size !== undefined) {
const w = rect.size.width;
const h = rect.size.height;
const edges = Math.pow(xDist - w, 2) + Math.pow(yDist - h, 2);
if (xDist > r + w || yDist > r + h) {
return false;
}
if (xDist <= w || yDist <= h) {
return true;
}
return edges <= r * r;
}
return false;
}
}
exports.Circle = Circle;
|
'use strict';
var Tokenizer = require('../tokenization/tokenizer'),
TokenizerProxy = require('./tokenizer_proxy');
//Skipping handler
function skip() {
//NOTE: do nothing =)
}
//SimpleApiParser
var SimpleApiParser = module.exports = function (handlers) {
this.handlers = {
doctype: handlers.doctype || skip,
startTag: handlers.startTag || skip,
endTag: handlers.endTag || skip,
text: handlers.text || skip,
comment: handlers.comment || skip
};
};
//API
SimpleApiParser.prototype.parse = function (html) {
var token = null;
this._reset(html);
do {
token = this.tokenizerProxy.getNextToken();
if (token.type === Tokenizer.CHARACTER_TOKEN ||
token.type === Tokenizer.WHITESPACE_CHARACTER_TOKEN ||
token.type === Tokenizer.NULL_CHARACTER_TOKEN) {
this.pendingText = (this.pendingText || '') + token.chars;
}
else {
this._emitPendingText();
this._handleToken(token);
}
} while (token.type !== Tokenizer.EOF_TOKEN)
};
//Internals
SimpleApiParser.prototype._handleToken = function (token) {
if (token.type === Tokenizer.START_TAG_TOKEN)
this.handlers.startTag(token.tagName, token.attrs, token.selfClosing);
else if (token.type === Tokenizer.END_TAG_TOKEN)
this.handlers.endTag(token.tagName);
else if (token.type === Tokenizer.COMMENT_TOKEN)
this.handlers.comment(token.data);
else if (token.type === Tokenizer.DOCTYPE_TOKEN)
this.handlers.doctype(token.name, token.publicId, token.systemId);
};
SimpleApiParser.prototype._reset = function (html) {
this.tokenizerProxy = new TokenizerProxy(html);
this.pendingText = null;
};
SimpleApiParser.prototype._emitPendingText = function () {
if (this.pendingText !== null) {
this.handlers.text(this.pendingText);
this.pendingText = null;
}
};
|
'use strict';
module.exports = function (t, a, d) {
var x = {}, y = {}, z = {}, p, r;
t.call(function (arg1, arg2) {
return [this, arg1, arg2];
}, 100).call(x, y, z)(function (arg) {
p = y;
r = arg;
}).end();
a.not(p, y, "Not yet");
setTimeout(function () {
a.not(p, y, "After a while");
setTimeout(function () {
a(p, y, "Timed");
a.deep(r, [x, y, z], "Result");
d();
}, 70);
}, 50);
};
|
'use strict';
var React = require('react');
var classNames = require('classnames');
var ClassNameMixin = require('./mixins/ClassNameMixin');
var PanelGroup = React.createClass({
mixins: [ClassNameMixin],
propTypes: {
amStyle: React.PropTypes.string,
activeKey: React.PropTypes.any,
defaultActiveKey: React.PropTypes.any,
onSelect: React.PropTypes.func,
accordion: React.PropTypes.bool
},
getDefaultProps: function() {
return {
classPrefix: 'panel-group'
};
},
getInitialState: function() {
return {
activeKey: this.props.defaultActiveKey
};
},
shouldComponentUpdate: function() {
// Defer any updates to this component during the `onSelect` handler.
return !this._isChanging;
},
handleSelect: function(e, key) {
e.preventDefault();
if (this.props.onSelect) {
this._isChanging = true;
this.props.onSelect(key);
this._isChanging = false;
}
if (this.state.activeKey === key) {
key = null;
}
this.setState({
activeKey: key
});
},
renderPanel: function(child, index) {
var activeKey = this.props.activeKey != null ?
this.props.activeKey : this.state.activeKey;
var props = {
amStyle: child.props.amStyle || this.props.amStyle,
key: child.key ? child.key : index,
ref: child.ref
};
if (this.props.accordion) {
props.collapsible = true;
props.expanded = (child.props.eventKey === activeKey);
props.onSelect = this.handleSelect;
}
return React.cloneElement(child, props);
},
render: function() {
var classes = this.getClassSet();
return (
<div
{...this.props}
className={classNames(classes, this.props.className)}>
{React.Children.map(this.props.children, this.renderPanel)}
</div>
);
}
});
module.exports = PanelGroup;
|
describe('taExecCommand', function(){
'use strict';
var $element;
beforeEach(module('textAngular'));
//mock for easier testing
describe('handles formatBlock BLOCKQUOTE correctly', function(){
beforeEach(function(){
module(function($provide){
$provide.value('taSelection', {
element: undefined,
getSelectionElement: function (){ return this.element; },
getOnlySelectedElements: function(){ return [].slice.call(this.element.childNodes); },
setSelectionToElementStart: function (){ return; },
setSelectionToElementEnd: function (){ return; }
});
});
});
// in li element
// in non-block element, ie <b>
// in block element, <p>
// multiple selected including text elements
// only text selected (collapsed range selection)
// all wrap and unwrap
describe('wraps elements', function(){
describe('doesn\'t split lists', function(){
it('li selected', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><ul><li>Test</li></ul></div>');
taSelection.element = $element.find('li')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><ul><li>Test</li></ul></blockquote>');
}));
it('ul selected', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><ul><li>Test</li></ul></div>');
taSelection.element = $element.find('ul')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><ul><li>Test</li></ul></blockquote>');
}));
it('ol selected', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><ol><li>Test</li></ol></div>');
taSelection.element = $element.find('ol')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><ol><li>Test</li></ol></blockquote>');
}));
});
describe('wraps non-list elements', function(){
it('no selection - single space', inject(function($document, taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><p><b>Test</b></p></div>');
$document.find('body').append($element);
taSelection.element = $element.find('b')[0];
taSelection.getOnlySelectedElements = function(){ return []; };
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><p><b>Test</b></p></blockquote>');
$element.remove();
}));
it('nested selection', inject(function($document, taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><p><i><b>Test</b></i></p></div>');
$document.find('body').append($element);
taSelection.element = $element.find('b')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><p><i><b>Test</b></i></p></blockquote>');
$element.remove();
}));
it('selection with mixed nodes', inject(function($document, taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><p>Some <b>test</b> content</p></div>');
$document.find('body').append($element);
taSelection.element = $element.find('b')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><p>Some <b>test</b> content</p></blockquote>');
$element.remove();
}));
it('selection with multiple nodes', inject(function($document, taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><p>Some <b>test</b> content</p><p><br/></p><p>Some <b>test</b> content</p></div>');
$document.find('body').append($element);
taSelection.element = $element[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<blockquote><p>Some <b>test</b> content</p><p><br></p><p>Some <b>test</b> content</p></blockquote>');
$element.remove();
}));
});
});
describe('unwraps elements', function(){
describe('doesn\'t split lists', function(){
it('li selected', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><blockquote><ul><li>Test</li></ul></blockquote></div>');
taSelection.element = $element.find('li')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<ul><li>Test</li></ul>');
}));
it('ul selected', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><blockquote><ul><li>Test</li></ul></blockquote></div>');
taSelection.element = $element.find('ul')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<ul><li>Test</li></ul>');
}));
it('ol selected', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><blockquote><ol><li>Test</li></ol></blockquote></div>');
taSelection.element = $element.find('ol')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<ol><li>Test</li></ol>');
}));
});
describe('unwraps non-list elements', function(){
beforeEach(inject(function($document){
$element = angular.element('<div class="ta-bind"><blockquote><p><b>Test</b></p></blockquote></div>');
$document.find('body').append($element);
}));
afterEach(inject(function($document){
$element.remove();
}));
it('no selection - single space', inject(function(taExecCommand, taSelection){
taSelection.element = $element.find('b')[0];
taSelection.getOnlySelectedElements = function(){ return []; };
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<p><b>Test</b></p>');
}));
it('inline selected', inject(function(taExecCommand, taSelection){
taSelection.element = $element.find('b')[0];
taSelection.getOnlySelectedElements = function(){ return taSelection.element.childNodes; };
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<p><b>Test</b></p>');
}));
it('block selected', inject(function(taExecCommand, taSelection){
taSelection.element = $element.find('blockquote')[0];
taSelection.getOnlySelectedElements = function(){ return taSelection.element; };
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<p><b>Test</b></p>');
}));
});
describe('unwraps inline elements', function(){
it('just inline element', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><blockquote><b>Test</b></blockquote></div>');
taSelection.element = $element.find('b')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<p><b>Test</b></p>');
}));
it('inline and text element', inject(function(taExecCommand, taSelection){
$element = angular.element('<div class="ta-bind"><blockquote>Other <b>Test</b></blockquote></div>');
taSelection.element = $element.find('blockquote')[0];
taExecCommand()('formatBlock', false, '<BLOCKQUOTE>');
expect($element.html()).toBe('<p>Other <b>Test</b></p>');
}));
});
});
});
describe('handles formatBlock correctly for other elements', function(){
var $document, taExecCommand, taSelection;
beforeEach(function(){
module(function($provide){
$provide.value('taSelection', {
element: undefined,
getSelectionElement: function (){ return this.element; },
getOnlySelectedElements: function(){ return [].slice.call(this.element.childNodes); },
setSelectionToElementStart: function (){ return; },
setSelectionToElementEnd: function (){ return; }
});
});
});
beforeEach(inject(function(_$document_, _taExecCommand_, _taSelection_){
$document = _$document_;
taExecCommand = _taExecCommand_;
taSelection = _taSelection_;
}));
function setupElement(html){
$element = angular.element(html);
$document.find('body').append($element);
}
afterEach(function(){
$element.remove();
});
it('default string should insert default wrap', function(){
setupElement('<div class="ta-bind"><h1><b>Test</b></h1></div>');
taSelection.element = $element.find('b')[0];
taExecCommand('def')('formatBlock', false, 'default');
expect($element.html()).toBe('<def><b>Test</b></def>');
});
describe('heading tags', function(){
it('can be unwrapped', function(){
setupElement('<div class="ta-bind"><h1><b>Test</b></h1></div>');
taSelection.element = $element.find('b')[0];
taExecCommand()('formatBlock', false, '<H1>');
expect($element.html()).toBe('<p><b>Test</b></p>');
});
describe('wrapping', function(){
it('single block element', function(){
setupElement('<div class="ta-bind"><p>Test</p></div>');
taSelection.element = $element.find('p')[0];
taExecCommand()('formatBlock', false, '<H1>');
expect($element.html()).toBe('<h1>Test</h1>');
});
it('single block element with an inline element', function(){
setupElement('<div class="ta-bind"><p><b>Test</b></p></div>');
taSelection.element = $element.find('p')[0];
taExecCommand()('formatBlock', false, '<H1>');
expect($element.html()).toBe('<h1><b>Test</b></h1>');
});
it('replaces each selected block element', function(){
setupElement('<div class="ta-bind"><p><b>Test</b></p><p>Line two</p><p>Line three</p></div>');
taSelection.element = $element[0];
// Select the first two p elements
taSelection.getOnlySelectedElements = function(){ return [].slice.call(this.element.childNodes, 0, 2); };
taExecCommand()('formatBlock', false, '<H1>');
expect($element.html()).toBe('<h1><b>Test</b></h1><h1>Line two</h1><p>Line three</p>');
});
it('wraps all nodes for mixed nodes', function(){
setupElement('<div class="ta-bind"><em>Italic</em>text<p><b>Test</b> content</p>In between<p>Line two</p></div>');
taSelection.element = $element[0];
taExecCommand()('formatBlock', false, '<H1>');
expect($element.html()).toBe('<h1><em>Italic</em>text<p><b>Test</b> content</p>In between<p>Line two</p></h1>');
});
});
});
});
}); |
(function(global) {
'use strict';
var fabric = global.fabric || (global.fabric = { }),
extend = fabric.util.object.extend,
min = fabric.util.array.min,
max = fabric.util.array.max,
invoke = fabric.util.array.invoke;
if (fabric.Group) {
return;
}
// lock-related properties, for use in fabric.Group#get
// to enable locking behavior on group
// when one of its objects has lock-related properties set
var _lockProperties = {
lockMovementX: true,
lockMovementY: true,
lockRotation: true,
lockScalingX: true,
lockScalingY: true,
lockUniScaling: true
};
/**
* Group class
* @class fabric.Group
* @extends fabric.Object
* @mixes fabric.Collection
* @tutorial {@link http://fabricjs.com/fabric-intro-part-3/#groups}
* @see {@link fabric.Group#initialize} for constructor definition
*/
fabric.Group = fabric.util.createClass(fabric.Object, fabric.Collection, /** @lends fabric.Group.prototype */ {
/**
* Type of an object
* @type String
* @default
*/
type: 'group',
/**
* Width of stroke
* @type Number
* @default
*/
strokeWidth: 0,
/**
* Constructor
* @param {Object} objects Group objects
* @param {Object} [options] Options object
* @param {Boolean} [isAlreadyGrouped] if true, objects have been grouped already.
* @return {Object} thisArg
*/
initialize: function(objects, options, isAlreadyGrouped) {
options = options || { };
this._objects = [];
// if objects enclosed in a group have been grouped already,
// we cannot change properties of objects.
// Thus we need to set options to group without objects,
// because delegatedProperties propagate to objects.
isAlreadyGrouped && this.callSuper('initialize', options);
this._objects = objects || [];
for (var i = this._objects.length; i--; ) {
this._objects[i].group = this;
}
this.originalState = { };
if (options.originX) {
this.originX = options.originX;
}
if (options.originY) {
this.originY = options.originY;
}
if (isAlreadyGrouped) {
// do not change coordinate of objects enclosed in a group,
// because objects coordinate system have been group coodinate system already.
this._updateObjectsCoords(true);
}
else {
this._calcBounds();
this._updateObjectsCoords();
this.callSuper('initialize', options);
}
this.setCoords();
this.saveCoords();
},
/**
* @private
* @param {Boolean} [skipCoordsChange] if true, coordinates of objects enclosed in a group do not change
*/
_updateObjectsCoords: function(skipCoordsChange) {
for (var i = this._objects.length; i--; ){
this._updateObjectCoords(this._objects[i], skipCoordsChange);
}
},
/**
* @private
* @param {Object} object
* @param {Boolean} [skipCoordsChange] if true, coordinates of object dose not change
*/
_updateObjectCoords: function(object, skipCoordsChange) {
// do not display corners of objects enclosed in a group
object.__origHasControls = object.hasControls;
object.hasControls = false;
if (skipCoordsChange) {
return;
}
var objectLeft = object.getLeft(),
objectTop = object.getTop(),
center = this.getCenterPoint();
object.set({
originalLeft: objectLeft,
originalTop: objectTop,
left: objectLeft - center.x,
top: objectTop - center.y
});
object.setCoords();
},
/**
* Returns string represenation of a group
* @return {String}
*/
toString: function() {
return '#<fabric.Group: (' + this.complexity() + ')>';
},
/**
* Adds an object to a group; Then recalculates group's dimension, position.
* @param {Object} object
* @return {fabric.Group} thisArg
* @chainable
*/
addWithUpdate: function(object) {
this._restoreObjectsState();
if (object) {
this._objects.push(object);
object.group = this;
object._set('canvas', this.canvas);
}
// since _restoreObjectsState set objects inactive
this.forEachObject(this._setObjectActive, this);
this._calcBounds();
this._updateObjectsCoords();
return this;
},
/**
* @private
*/
_setObjectActive: function(object) {
object.set('active', true);
object.group = this;
},
/**
* Removes an object from a group; Then recalculates group's dimension, position.
* @param {Object} object
* @return {fabric.Group} thisArg
* @chainable
*/
removeWithUpdate: function(object) {
this._moveFlippedObject(object);
this._restoreObjectsState();
// since _restoreObjectsState set objects inactive
this.forEachObject(this._setObjectActive, this);
this.remove(object);
this._calcBounds();
this._updateObjectsCoords();
return this;
},
/**
* @private
*/
_onObjectAdded: function(object) {
object.group = this;
object._set('canvas', this.canvas);
},
/**
* @private
*/
_onObjectRemoved: function(object) {
delete object.group;
object.set('active', false);
},
/**
* Properties that are delegated to group objects when reading/writing
* @param {Object} delegatedProperties
*/
delegatedProperties: {
fill: true,
opacity: true,
fontFamily: true,
fontWeight: true,
fontSize: true,
fontStyle: true,
lineHeight: true,
textDecoration: true,
textAlign: true,
backgroundColor: true
},
/**
* @private
*/
_set: function(key, value) {
var i = this._objects.length;
if (this.delegatedProperties[key] || key === 'canvas') {
while (i--) {
this._objects[i].set(key, value);
}
}
else {
while (i--) {
this._objects[i].setOnGroup(key, value);
}
}
this.callSuper('_set', key, value);
},
/**
* Returns object representation of an instance
* @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output
* @return {Object} object representation of an instance
*/
toObject: function(propertiesToInclude) {
return extend(this.callSuper('toObject', propertiesToInclude), {
objects: invoke(this._objects, 'toObject', propertiesToInclude)
});
},
/**
* Renders instance on a given context
* @param {CanvasRenderingContext2D} ctx context to render instance on
*/
render: function(ctx) {
// do not render if object is not visible
if (!this.visible) {
return;
}
ctx.save();
if (this.transformMatrix) {
ctx.transform.apply(ctx, this.transformMatrix);
}
this.transform(ctx);
this.clipTo && fabric.util.clipContext(this, ctx);
// the array is now sorted in order of highest first, so start from end
for (var i = 0, len = this._objects.length; i < len; i++) {
this._renderObject(this._objects[i], ctx);
}
this.clipTo && ctx.restore();
ctx.restore();
},
/**
* Renders controls and borders for the object
* @param {CanvasRenderingContext2D} ctx Context to render on
* @param {Boolean} [noTransform] When true, context is not transformed
*/
_renderControls: function(ctx, noTransform) {
this.callSuper('_renderControls', ctx, noTransform);
for (var i = 0, len = this._objects.length; i < len; i++) {
this._objects[i]._renderControls(ctx);
}
},
/**
* @private
*/
_renderObject: function(object, ctx) {
// do not render if object is not visible
if (!object.visible) {
return;
}
var originalHasRotatingPoint = object.hasRotatingPoint;
object.hasRotatingPoint = false;
object.render(ctx);
object.hasRotatingPoint = originalHasRotatingPoint;
},
/**
* Retores original state of each of group objects (original state is that which was before group was created).
* @private
* @return {fabric.Group} thisArg
* @chainable
*/
_restoreObjectsState: function() {
this._objects.forEach(this._restoreObjectState, this);
return this;
},
/**
* Realises the transform from this group onto the supplied object
* i.e. it tells you what would happen if the supplied object was in
* the group, and then the group was destroyed. It mutates the supplied
* object.
* @param {fabric.Object} object
* @return {fabric.Object} transformedObject
*/
realizeTransform: function(object) {
this._moveFlippedObject(object);
this._setObjectPosition(object);
return object;
},
/**
* Moves a flipped object to the position where it's displayed
* @private
* @param {fabric.Object} object
* @return {fabric.Group} thisArg
*/
_moveFlippedObject: function(object) {
var oldOriginX = object.get('originX'),
oldOriginY = object.get('originY'),
center = object.getCenterPoint();
object.set({
originX: 'center',
originY: 'center',
left: center.x,
top: center.y
});
this._toggleFlipping(object);
var newOrigin = object.getPointByOrigin(oldOriginX, oldOriginY);
object.set({
originX: oldOriginX,
originY: oldOriginY,
left: newOrigin.x,
top: newOrigin.y
});
return this;
},
/**
* @private
*/
_toggleFlipping: function(object) {
if (this.flipX) {
object.toggle('flipX');
object.set('left', -object.get('left'));
object.setAngle(-object.getAngle());
}
if (this.flipY) {
object.toggle('flipY');
object.set('top', -object.get('top'));
object.setAngle(-object.getAngle());
}
},
/**
* Restores original state of a specified object in group
* @private
* @param {fabric.Object} object
* @return {fabric.Group} thisArg
*/
_restoreObjectState: function(object) {
this._setObjectPosition(object);
object.setCoords();
object.hasControls = object.__origHasControls;
delete object.__origHasControls;
object.set('active', false);
object.setCoords();
delete object.group;
return this;
},
/**
* @private
*/
_setObjectPosition: function(object) {
var center = this.getCenterPoint(),
rotated = this._getRotatedLeftTop(object);
object.set({
angle: object.getAngle() + this.getAngle(),
left: center.x + rotated.left,
top: center.y + rotated.top,
scaleX: object.get('scaleX') * this.get('scaleX'),
scaleY: object.get('scaleY') * this.get('scaleY')
});
},
/**
* @private
*/
_getRotatedLeftTop: function(object) {
var groupAngle = this.getAngle() * (Math.PI / 180);
return {
left: (-Math.sin(groupAngle) * object.getTop() * this.get('scaleY') +
Math.cos(groupAngle) * object.getLeft() * this.get('scaleX')),
top: (Math.cos(groupAngle) * object.getTop() * this.get('scaleY') +
Math.sin(groupAngle) * object.getLeft() * this.get('scaleX'))
};
},
/**
* Destroys a group (restoring state of its objects)
* @return {fabric.Group} thisArg
* @chainable
*/
destroy: function() {
this._objects.forEach(this._moveFlippedObject, this);
return this._restoreObjectsState();
},
/**
* Saves coordinates of this instance (to be used together with `hasMoved`)
* @saveCoords
* @return {fabric.Group} thisArg
* @chainable
*/
saveCoords: function() {
this._originalLeft = this.get('left');
this._originalTop = this.get('top');
return this;
},
/**
* Checks whether this group was moved (since `saveCoords` was called last)
* @return {Boolean} true if an object was moved (since fabric.Group#saveCoords was called)
*/
hasMoved: function() {
return this._originalLeft !== this.get('left') ||
this._originalTop !== this.get('top');
},
/**
* Sets coordinates of all group objects
* @return {fabric.Group} thisArg
* @chainable
*/
setObjectsCoords: function() {
this.forEachObject(function(object) {
object.setCoords();
});
return this;
},
/**
* @private
*/
_calcBounds: function(onlyWidthHeight) {
var aX = [],
aY = [],
o, prop,
props = ['tr', 'br', 'bl', 'tl'],
i = 0, iLen = this._objects.length,
j, jLen = props.length;
for ( ; i < iLen; ++i) {
o = this._objects[i];
o.setCoords();
for (j = 0; j < jLen; j++) {
prop = props[j];
aX.push(o.oCoords[prop].x);
aY.push(o.oCoords[prop].y);
}
}
this.set(this._getBounds(aX, aY, onlyWidthHeight));
},
/**
* @private
*/
_getBounds: function(aX, aY, onlyWidthHeight) {
var ivt = fabric.util.invertTransform(this.getViewportTransform()),
minXY = fabric.util.transformPoint(new fabric.Point(min(aX), min(aY)), ivt),
maxXY = fabric.util.transformPoint(new fabric.Point(max(aX), max(aY)), ivt),
obj = {
width: (maxXY.x - minXY.x) || 0,
height: (maxXY.y - minXY.y) || 0
};
if (!onlyWidthHeight) {
obj.left = minXY.x || 0;
obj.top = minXY.y || 0;
if (this.originX === 'center') {
obj.left += obj.width / 2;
}
if (this.originX === 'right') {
obj.left += obj.width;
}
if (this.originY === 'center') {
obj.top += obj.height / 2;
}
if (this.originY === 'bottom') {
obj.top += obj.height;
}
}
return obj;
},
/* _TO_SVG_START_ */
/**
* Returns svg representation of an instance
* @param {Function} [reviver] Method for further parsing of svg representation.
* @return {String} svg representation of an instance
*/
toSVG: function(reviver) {
var markup = [
//jscs:disable validateIndentation
'<g ',
'transform="', this.getSvgTransform(),
'">\n'
//jscs:enable validateIndentation
];
for (var i = 0, len = this._objects.length; i < len; i++) {
markup.push(this._objects[i].toSVG(reviver));
}
markup.push('</g>\n');
return reviver ? reviver(markup.join('')) : markup.join('');
},
/* _TO_SVG_END_ */
/**
* Returns requested property
* @param {String} prop Property to get
* @return {Any}
*/
get: function(prop) {
if (prop in _lockProperties) {
if (this[prop]) {
return this[prop];
}
else {
for (var i = 0, len = this._objects.length; i < len; i++) {
if (this._objects[i][prop]) {
return true;
}
}
return false;
}
}
else {
if (prop in this.delegatedProperties) {
return this._objects[0] && this._objects[0].get(prop);
}
return this[prop];
}
}
});
/**
* Returns {@link fabric.Group} instance from an object representation
* @static
* @memberOf fabric.Group
* @param {Object} object Object to create a group from
* @param {Function} [callback] Callback to invoke when an group instance is created
* @return {fabric.Group} An instance of fabric.Group
*/
fabric.Group.fromObject = function(object, callback) {
fabric.util.enlivenObjects(object.objects, function(enlivenedObjects) {
delete object.objects;
callback && callback(new fabric.Group(enlivenedObjects, object, true));
});
};
/**
* Indicates that instances of this type are async
* @static
* @memberOf fabric.Group
* @type Boolean
* @default
*/
fabric.Group.async = true;
})(typeof exports !== 'undefined' ? exports : this);
|
/**
* @license
* Copyright 2015 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var ts = require("typescript");
var Lint = require("../index");
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
return _super.apply(this, arguments) || this;
}
Rule.prototype.apply = function (sourceFile) {
var walker = new NoConditionalAssignmentWalker(sourceFile, this.getOptions());
return this.applyWithWalker(walker);
};
return Rule;
}(Lint.Rules.AbstractRule));
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "no-conditional-assignment",
description: "Disallows any type of assignment in conditionals.",
descriptionDetails: "This applies to `do-while`, `for`, `if`, and `while` statements.",
rationale: (_a = ["\n Assignments in conditionals are often typos:\n for example `if (var1 = var2)` instead of `if (var1 == var2)`.\n They also can be an indicator of overly clever code which decreases maintainability."], _a.raw = ["\n Assignments in conditionals are often typos:\n for example \\`if (var1 = var2)\\` instead of \\`if (var1 == var2)\\`.\n They also can be an indicator of overly clever code which decreases maintainability."], Lint.Utils.dedent(_a)),
optionsDescription: "Not configurable.",
options: null,
optionExamples: ["true"],
type: "functionality",
typescriptOnly: false,
};
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING = "Assignments in conditional expressions are forbidden";
exports.Rule = Rule;
var NoConditionalAssignmentWalker = (function (_super) {
__extends(NoConditionalAssignmentWalker, _super);
function NoConditionalAssignmentWalker() {
var _this = _super.apply(this, arguments) || this;
_this.isInConditional = false;
return _this;
}
NoConditionalAssignmentWalker.prototype.visitIfStatement = function (node) {
this.validateConditionalExpression(node.expression);
_super.prototype.visitIfStatement.call(this, node);
};
NoConditionalAssignmentWalker.prototype.visitWhileStatement = function (node) {
this.validateConditionalExpression(node.expression);
_super.prototype.visitWhileStatement.call(this, node);
};
NoConditionalAssignmentWalker.prototype.visitDoStatement = function (node) {
this.validateConditionalExpression(node.expression);
_super.prototype.visitDoStatement.call(this, node);
};
NoConditionalAssignmentWalker.prototype.visitForStatement = function (node) {
if (node.condition != null) {
this.validateConditionalExpression(node.condition);
}
_super.prototype.visitForStatement.call(this, node);
};
NoConditionalAssignmentWalker.prototype.visitBinaryExpression = function (expression) {
if (this.isInConditional) {
this.checkForAssignment(expression);
}
_super.prototype.visitBinaryExpression.call(this, expression);
};
NoConditionalAssignmentWalker.prototype.validateConditionalExpression = function (expression) {
this.isInConditional = true;
if (expression.kind === ts.SyntaxKind.BinaryExpression) {
// check for simple assignment in a conditional, like `if (a = 1) {`
this.checkForAssignment(expression);
}
// walk the children of the conditional expression for nested assignments, like `if ((a = 1) && (b == 1)) {`
this.walkChildren(expression);
this.isInConditional = false;
};
NoConditionalAssignmentWalker.prototype.checkForAssignment = function (expression) {
if (isAssignmentToken(expression.operatorToken)) {
this.addFailureAtNode(expression, Rule.FAILURE_STRING);
}
};
return NoConditionalAssignmentWalker;
}(Lint.RuleWalker));
function isAssignmentToken(token) {
return token.kind >= ts.SyntaxKind.FirstAssignment && token.kind <= ts.SyntaxKind.LastAssignment;
}
var _a;
|
module.exports={A:{A:{"16":"WB","644":"C B A","2308":"H E G"},B:{"1":"u g I J","16":"D"},C:{"1":"0 1 2 3 4 5 6 C B A D u g I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t y K","2":"UB x F L H E G SB RB"},D:{"1":"0 1 2 3 4 5 6 V W X v Z a b c d N f M h i j k l m n o p q r s t y K GB AB CB VB DB EB","16":"F L H E G C B A D u g I J Y O e P Q R S T U"},E:{"1":"E G C B A IB JB KB LB MB","16":"9 F L H FB","1668":"HB"},F:{"1":"I J Y O e P Q R S T U V W X v Z a b c d N f M h i j k l m n o p q r s t w","16":"7 8 C A D NB OB PB QB","132":"TB"},G:{"1":"G A ZB aB bB cB dB eB","16":"9 BB z XB YB"},H:{"16":"fB"},I:{"1":"K kB lB","16":"x gB hB iB","1668":"F jB z"},J:{"16":"E B"},K:{"16":"7 8 B A D M w"},L:{"1":"AB"},M:{"1":"K"},N:{"16":"B A"},O:{"16":"mB"},P:{"1":"L","16":"F"},Q:{"1":"nB"},R:{"1":"oB"}},B:1,C:"Node.contains()"};
|
var _ = require("lodash");
module.exports = function(network, chan, cmd, args) {
if (cmd !== "say" && cmd !== "msg") {
return;
}
if (args.length === 0 || args[0] === "") {
return;
}
var irc = network.irc;
var target = "";
if (cmd === "msg") {
target = args.shift();
if (args.length === 0) {
return;
}
} else {
target = chan.name;
}
var msg = args.join(" ");
irc.send(target, msg);
var channel = _.find(network.channels, {name: target});
if (typeof channel !== "undefined") {
irc.emit("message", {
from: irc.me,
to: channel.name,
message: msg
});
}
};
|
module.exports={A:{A:{"2":"I C G E A B SB"},B:{"2":"D g q K"},C:{"2":"0 1 2 3 QB F H I C G E A B D g q K L M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p u v w t y r W OB NB"},D:{"2":"F H I C","33":"0 1 2 6 9 g q K L M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p u v w t y r W CB RB AB","36":"G E A B D"},E:{"2":"7 F H I C G E A BB DB EB FB GB HB IB"},F:{"2":"4 5 E B D JB KB LB MB PB z","33":"K L M N O P Q R S T U V s X Y Z a b c d e f J h i j k l m n o p"},G:{"2":"7 8 G x TB UB VB WB XB YB ZB aB"},H:{"2":"bB"},I:{"2":"3 F W cB dB eB fB x gB hB"},J:{"2":"C","33":"A"},K:{"2":"4 5 A B D z","33":"J"},L:{"33":"6"},M:{"2":"r"},N:{"2":"A B"},O:{"2":"iB"},P:{"2":"F","33":"H"},Q:{"2":"jB"},R:{"2":"kB"}},B:7,C:"Filesystem & FileWriter API"};
|
/**
* @ngdoc model
* @name DeleteCustomerDialogData
* @function
*
* @description
* A dialog data object for deleting CustomerDisplay objects
*/
var DeleteCustomerDialogData = function() {
var self = this;
self.customer = {};
self.name = '';
};
angular.module('merchello.models').constant('DeleteCustomerDialogData', DeleteCustomerDialogData);
|
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var bufrw = require('bufrw');
var inherits = require('util').inherits;
var IterStream = require('./iter_stream');
function CountStream(options) {
if (!(this instanceof CountStream)) {
return new CountStream(options);
}
var self = this;
// TODO: allow to change rw
IterStream.call(self, bufrw.UInt32BE, options);
self._max = Math.pow(2, 8 * self._rw.width);
self._n = 0;
}
inherits(CountStream, IterStream);
CountStream.prototype._next = function _read() {
var self = this;
var n = self._n;
self._n = (self._n + 1) % self._max;
return n;
};
module.exports = CountStream;
|
///<reference path='../typings/tsd.d.ts'/>
var path = require('path');
var tsApi = require('./tsapi');
var utils = require('./utils');
(function (FileChangeState) {
FileChangeState[FileChangeState["New"] = 0] = "New";
FileChangeState[FileChangeState["Equal"] = 1] = "Equal";
FileChangeState[FileChangeState["Modified"] = 2] = "Modified";
FileChangeState[FileChangeState["Deleted"] = 3] = "Deleted";
FileChangeState[FileChangeState["NotFound"] = 4] = "NotFound";
})(exports.FileChangeState || (exports.FileChangeState = {}));
var FileChangeState = exports.FileChangeState;
(function (FileKind) {
FileKind[FileKind["Source"] = 0] = "Source";
FileKind[FileKind["Config"] = 1] = "Config";
})(exports.FileKind || (exports.FileKind = {}));
var FileKind = exports.FileKind;
var File;
(function (File) {
function fromContent(fileName, content) {
var kind = FileKind.Source;
if (path.extname(fileName).toLowerCase() === 'json')
kind = FileKind.Config;
return {
fileNameNormalized: utils.normalizePath(fileName),
fileNameOriginal: fileName,
content: content,
kind: kind
};
}
File.fromContent = fromContent;
function fromGulp(file) {
var str = file.contents.toString('utf8');
var data = fromContent(file.path, str);
data.gulp = file;
return data;
}
File.fromGulp = fromGulp;
function equal(a, b) {
if (a === undefined || b === undefined)
return a === b; // They could be both undefined.
return (a.fileNameOriginal === b.fileNameOriginal)
&& (a.content === b.content);
}
File.equal = equal;
function getChangeState(previous, current) {
if (previous === undefined) {
return current === undefined ? FileChangeState.NotFound : FileChangeState.New;
}
if (current === undefined) {
return FileChangeState.Deleted;
}
if (equal(previous, current)) {
return FileChangeState.Equal;
}
return FileChangeState.Modified;
}
File.getChangeState = getChangeState;
})(File = exports.File || (exports.File = {}));
/**
* Finds the common base path of two directories
*/
function getCommonBasePath(a, b) {
var aSplit = a.split(/\\|\//); // Split on '/' or '\'.
var bSplit = b.split(/\\|\//);
var commonLength = 0;
for (var i = 0; i < aSplit.length && i < bSplit.length; i++) {
if (aSplit[i] !== bSplit[i])
break;
commonLength += aSplit[i].length + 1;
}
return a.substr(0, commonLength);
}
var FileDictionary = (function () {
function FileDictionary(typescript) {
this.files = {};
this.firstSourceFile = undefined;
this.typescript = typescript;
}
FileDictionary.prototype.addGulp = function (gFile) {
return this.addFile(File.fromGulp(gFile));
};
FileDictionary.prototype.addContent = function (fileName, content) {
return this.addFile(File.fromContent(fileName, content));
};
FileDictionary.prototype.addFile = function (file) {
if (file.kind === FileKind.Source) {
this.initTypeScriptSourceFile(file);
if (!this.firstSourceFile)
this.firstSourceFile = file;
}
this.files[file.fileNameNormalized] = file;
return file;
};
FileDictionary.prototype.getFile = function (name) {
return this.files[utils.normalizePath(name)];
};
FileDictionary.prototype.getFileNames = function (onlyGulp) {
if (onlyGulp === void 0) { onlyGulp = false; }
var fileNames = [];
for (var fileName in this.files) {
if (!this.files.hasOwnProperty(fileName))
continue;
var file = this.files[fileName];
if (onlyGulp && !file.gulp)
continue;
fileNames.push(file.fileNameOriginal);
}
return fileNames;
};
FileDictionary.prototype.getSourceFileNames = function (onlyGulp) {
var fileNames = this.getFileNames(onlyGulp);
var sourceFileNames = fileNames
.filter(function (fileName) { return fileName.substr(fileName.length - 5).toLowerCase() !== '.d.ts'; });
if (sourceFileNames.length === 0) {
// Only definition files, so we will calculate the common base path based on the
// paths of the definition files.
return fileNames;
}
return sourceFileNames;
};
Object.defineProperty(FileDictionary.prototype, "commonBasePath", {
get: function () {
var _this = this;
var fileNames = this.getSourceFileNames(true);
return fileNames
.map(function (fileName) {
var file = _this.files[utils.normalizePath(fileName)];
return path.resolve(file.gulp.cwd, file.gulp.base);
})
.reduce(getCommonBasePath);
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileDictionary.prototype, "commonSourceDirectory", {
get: function () {
var _this = this;
var fileNames = this.getSourceFileNames();
return fileNames
.map(function (fileName) {
var file = _this.files[utils.normalizePath(fileName)];
return path.dirname(file.fileNameNormalized);
})
.reduce(getCommonBasePath);
},
enumerable: true,
configurable: true
});
return FileDictionary;
})();
exports.FileDictionary = FileDictionary;
var FileCache = (function () {
function FileCache(typescript, options) {
this.previous = undefined;
this.noParse = false; // true when using a file based compiler.
this.version = 0;
this.typescript = typescript;
this.options = options;
this.createDictionary();
}
FileCache.prototype.addGulp = function (gFile) {
return this.current.addGulp(gFile);
};
FileCache.prototype.addContent = function (fileName, content) {
return this.current.addContent(fileName, content);
};
FileCache.prototype.reset = function () {
this.version++;
this.previous = this.current;
this.createDictionary();
};
FileCache.prototype.createDictionary = function () {
var _this = this;
this.current = new FileDictionary(this.typescript);
this.current.initTypeScriptSourceFile = function (file) { return _this.initTypeScriptSourceFile(file); };
};
FileCache.prototype.initTypeScriptSourceFile = function (file) {
if (this.noParse)
return;
if (this.previous) {
var previous = this.previous.getFile(file.fileNameOriginal);
if (File.equal(previous, file)) {
file.ts = previous.ts; // Re-use previous source file.
return;
}
}
file.ts = tsApi.createSourceFile(this.typescript, file.fileNameOriginal, file.content, this.options.target, this.version + '');
};
FileCache.prototype.getFile = function (name) {
return this.current.getFile(name);
};
FileCache.prototype.getFileChange = function (name) {
var previous;
if (this.previous) {
previous = this.previous.getFile(name);
}
var current = this.current.getFile(name);
return {
previous: previous,
current: current,
state: File.getChangeState(previous, current)
};
};
FileCache.prototype.getFileNames = function (onlyGulp) {
if (onlyGulp === void 0) { onlyGulp = false; }
return this.current.getFileNames(onlyGulp);
};
Object.defineProperty(FileCache.prototype, "firstSourceFile", {
get: function () {
return this.current.firstSourceFile;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileCache.prototype, "commonBasePath", {
get: function () {
return this.current.commonBasePath;
},
enumerable: true,
configurable: true
});
Object.defineProperty(FileCache.prototype, "commonSourceDirectory", {
get: function () {
return this.current.commonSourceDirectory;
},
enumerable: true,
configurable: true
});
FileCache.prototype.isChanged = function (onlyGulp) {
if (onlyGulp === void 0) { onlyGulp = false; }
if (!this.previous)
return true;
var files = this.getFileNames(onlyGulp);
var oldFiles = this.previous.getFileNames(onlyGulp);
if (files.length !== oldFiles.length)
return true;
for (var fileName in files) {
if (oldFiles.indexOf(fileName) === -1)
return true;
}
for (var fileName in files) {
var change = this.getFileChange(fileName);
if (change.state !== FileChangeState.Equal)
return true;
}
return false;
};
return FileCache;
})();
exports.FileCache = FileCache;
|
CKEDITOR.plugins.setLang("devtools","es",{title:"Información del Elemento",dialogName:"Nombre de la ventana de diálogo",tabName:"Nombre de la pestaña",elementId:"ID del Elemento",elementType:"Tipo del elemento"}); |
export function LoadingBarConfig (cfpLoadingBarProvider) {
'ngInject'
cfpLoadingBarProvider.includeSpinner = true
}
|
// Expression parser security
//
// Executing arbitrary expressions like enabled by the expression parser of
// mathjs involves a risk in general. When you're using mathjs to let users
// execute arbitrary expressions, it's good to take a moment to think about
// possible security and stability implications, especially when running the
// code server side.
//
// There is a small number of functions which yield the biggest security risk
// in the expression parser of math.js:
//
// - `import` and `createUnit` which alter the built-in functionality and allow
// overriding existing functions and units.
// - `eval`, `parse`, `simplify`, and `derivative` which parse arbitrary input
// into a manipulable expression tree.
//
// To make the expression parser less vulnerable whilst still supporting most
// functionality, these functions can be disabled, as demonstrated in this
// example.
var math = require('../../index');
var limitedEval = math.eval;
math.import({
'import': function () { throw new Error('Function import is disabled') },
'createUnit': function () { throw new Error('Function createUnit is disabled') },
'eval': function () { throw new Error('Function eval is disabled') },
'parse': function () { throw new Error('Function parse is disabled') },
'simplify': function () { throw new Error('Function simplify is disabled') },
'derivative': function () { throw new Error('Function derivative is disabled') }
}, {override: true});
console.log(limitedEval('sqrt(16)')); // Ok, 4
console.log(limitedEval('parse("2+3")')); // Error: Function parse is disabled
|
/**
* Bind the file upload when editing content, so it works and stuff
*
* @param {string} key
*/
function bindFileUpload(key) {
// Since jQuery File Upload's 'paramName' option seems to be ignored,
// it requires the name of the upload input to be "images[]". Which clashes
// with the non-fancy fallback, so we hackishly set it here. :-/
$('#fileupload-' + key)
.fileupload({
dataType: 'json',
dropZone: $('#dropzone-' + key),
done: function (e, data) {
$.each(data.result, function (index, file) {
var filename, message;
if (file.error === undefined) {
filename = decodeURI(file.url).replace('files/', '');
$('#field-' + key).val(filename);
$('#thumbnail-' + key).html('<img src="' + Bolt.conf('paths.root') + 'thumbs/200x150c/' +
encodeURI(filename) + '" width="200" height="150">');
window.setTimeout(function () { $('#progress-' + key).fadeOut('slow'); }, 1500);
// Add the uploaded file to our stack.
Bolt.stack.addToStack(filename);
} else {
message = "Oops! There was an error uploading the file. Make sure the file is not " +
"corrupt, and that the 'files/'-folder is writable." +
"\n\n(error was: " + file.error + ")";
alert(message);
window.setTimeout(function () { $('#progress-' + key).fadeOut('slow'); }, 50);
}
$('#progress-' + key + ' div.bar').css('width', "100%");
$('#progress-' + key).removeClass('progress-striped active');
});
},
add: bindFileUpload.checkFileSize
})
.bind('fileuploadprogress', function (e, data) {
var progress = Math.round(100 * data.loaded / data.total);
$('#progress-' + key).show().addClass('progress-striped active');
$('#progress-' + key + ' div.progress-bar').css('width', progress + "%");
});
}
bindFileUpload.checkFileSize = function checkFileSize (event, data) {
// The jQuery upload doesn't expose an API to cover an entire upload set. So we keep "bad" files
// in the data.originalFiles, which is the same between multiple files in one upload set.
var badFiles = [];
if (typeof data.originalFiles.bad === 'undefined') {
data.originalFiles.bad = [];
}
_.each(data.files, function (file) {
if ((file.size || 0) > Bolt.conf('uploadConfig.maxSize') && Bolt.conf('uploadConfig.maxSize') > 0) {
badFiles.push(file.name);
data.originalFiles.bad.push(file.name);
}
});
if (data.originalFiles.bad.length > 0) {
var filename1 = data.files[data.files.length - 1].name;
var filename2 = data.originalFiles[data.originalFiles.length - 1].name;
if (filename1 === filename2) {
// We're at the end of this upload cycle
var message = 'One or more of the files that you selected was larger than the max size of ' +
Bolt.conf('uploadConfig.maxSizeNice') + ":\n\n" +
data.originalFiles.bad.join("\n");
alert(message);
}
}
if (badFiles.length === 0) {
data.submit();
}
};
|
// Generated by CoffeeScript 1.12.5
(function() {
var CoffeeScript, Module, binary, child_process, ext, findExtension, fork, helpers, i, len, loadFile, path, ref;
CoffeeScript = require('./coffee-script');
child_process = require('child_process');
helpers = require('./helpers');
path = require('path');
loadFile = function(module, filename) {
var answer;
answer = CoffeeScript._compileFile(filename, false, true);
return module._compile(answer, filename);
};
if (require.extensions) {
ref = CoffeeScript.FILE_EXTENSIONS;
for (i = 0, len = ref.length; i < len; i++) {
ext = ref[i];
require.extensions[ext] = loadFile;
}
Module = require('module');
findExtension = function(filename) {
var curExtension, extensions;
extensions = path.basename(filename).split('.');
if (extensions[0] === '') {
extensions.shift();
}
while (extensions.shift()) {
curExtension = '.' + extensions.join('.');
if (Module._extensions[curExtension]) {
return curExtension;
}
}
return '.js';
};
Module.prototype.load = function(filename) {
var extension;
this.filename = filename;
this.paths = Module._nodeModulePaths(path.dirname(filename));
extension = findExtension(filename);
Module._extensions[extension](this, filename);
return this.loaded = true;
};
}
if (child_process) {
fork = child_process.fork;
binary = require.resolve('../../bin/coffee');
child_process.fork = function(path, args, options) {
if (helpers.isCoffee(path)) {
if (!Array.isArray(args)) {
options = args || {};
args = [];
}
args = [path].concat(args);
path = binary;
}
return fork(path, args, options);
};
}
}).call(this);
|
(function() {
/**
*
* Backbone Game Engine - An elementary HTML5 canvas game engine using Backbone.
*
* Copyright (c) 2014 Martin Drapeau
* https://github.com/martindrapeau/backbone-game-engine
*
*/
var sequenceDelay = 300,
animations;
// Mushroom is the base enemie class.
Backbone.Mushroom = Backbone.Character.extend({
defaults: _.extend(_.deepClone(Backbone.Character.prototype.defaults), {
name: "mushroom",
type: "character",
width: 32,
height: 64,
paddingTop: 32,
spriteSheet: "enemies",
state: "idle-left",
velocity: 0,
yVelocity: 0,
collision: true,
aiDelay: 0
}),
animations: _.extend(_.deepClone(Backbone.Character.prototype.animations), {
"squished-left": {
sequences: [2],
velocity: 0,
scaleX: 1,
scaleY: 1
},
"squished-right": {
sequences: [2],
velocity: 0,
scaleX: -1,
scaleY: 1
}
}),
ai: function(dt) {
var cur = this.getStateInfo();
if (cur.mov == "squished" && !this.get("collision")) this.cancelUpdate = true;
return this;
},
isAttacking: function(sprite, dir, dir2) {
if (this.cancelUpdate) return false;
var cur = this.getStateInfo();
return (cur.mov == "walk" || cur.mov == "idle");
},
squish: function(sprite) {
var self = this,
cur = this.getStateInfo();
this.set({
state: this.buildState("squished", cur.dir),
collision: false
});
this.world.setTimeout(function() {
if (self && self.world) self.world.remove(self);
}, 2000);
this.cancelUpdate = true;
return this;
},
hit: function(sprite, dir, dir2) {
if (this._handlingSpriteHit) return this;
this._handlingSpriteHit = sprite;
var cur = this.getStateInfo(),
opo = dir == "left" ? "right" : (dir == "right" ? "left" : (dir == "top" ? "bottom" : "top"));
if (sprite.get("hero")) {
if (dir == "top")
this.squish.apply(this, arguments);
} else if (sprite.get("state").indexOf("slide") != -1 ||
sprite.get("type") == "tile" && dir == "bottom" && sprite.get("state") == "bounce") {
this.knockout.apply(this, arguments);
}
sprite.trigger("hit", this, opo);
this._handlingSpriteHit = undefined;
return this;
}
});
Backbone.Turtle = Backbone.Mushroom.extend({
defaults: _.extend(_.deepClone(Backbone.Mushroom.prototype.defaults), {
name: "turtle"
}),
animations: _.deepClone(Backbone.Mushroom.prototype.animations),
isAttacking: function() {
var cur = this.getStateInfo();
return (cur.mov == "walk" || cur.mov == "idle");
},
slide: function(sprite, dir, dir2) {
if (this.wakeTimerId) {
this.world.clearTimeout(this.wakeTimerId);
this.wakeTimerId = null;
}
var dir = sprite.getCenterX(true) > this.getCenterX(true) ? "left" : "right";
this.set("state", this.buildState("walk", "slide", dir));
this.cancelUpdate = true;
return this;
},
squish: function(sprite, dir, dir2) {
var cur = this.getStateInfo();
if (cur.mov == "squished" || cur.mov == "wake")
return this.slide.apply(this, arguments);
if (this.wakeTimerId) {
this.world.clearTimeout(this.wakeTimerId);
this.wakeTimerId = null;
}
this.set("state", this.buildState("squished", cur.dir));
this.wakeTimerId = this.world.setTimeout(this.wake.bind(this), 5000);
this.cancelUpdate = true;
return this;
},
hit: function(sprite, dir, dir2) {
if (this._handlingSpriteHit) return this;
this._handlingSpriteHit = sprite;
var cur = this.getStateInfo(),
opo = dir == "left" ? "right" : (dir == "right" ? "left" : (dir == "top" ? "bottom" : "top"));
if (cur.mov2 == "slide") this.cancelUpdate = true;
if (dir == "top") {
this.squish.apply(this, arguments);
} else if (sprite.get("hero") && (cur.mov == "squished" || cur.mov == "wake")) {
this.slide.apply(this, arguments);
opo = "bottom";
} else if (sprite.get("state").indexOf("slide") != -1 ||
sprite.get("type") == "tile" && dir == "bottom" && sprite.get("state") == "bounce") {
this.knockout.apply(this, arguments);
}
sprite.trigger("hit", this, opo);
this._handlingSpriteHit = undefined;
return this;
},
wake: function() {
var cur = this.getStateInfo();
if (this.wakeTimerId) {
this.world.clearTimeout(this.wakeTimerId);
this.wakeTimerId = null;
}
if (cur.mov == "squished") {
this.set("state", this.buildState("wake", cur.dir));
this.wakeTimerId = this.world.setTimeout(this.wake.bind(this), 5000);
} else if (cur.mov == "wake") {
this.set("state", this.buildState("walk", cur.dir));
}
return this;
}
});
animations = Backbone.Turtle.prototype.animations;
animations["idle-left"].sequences = animations["idle-right"].sequences =
animations["fall-left"].sequences = animations["fall-right"].sequences =
animations["ko-left"].sequences = animations["ko-right"].sequences = [6];
animations["walk-left"].sequences = animations["walk-right"].sequences = [6, 7];
animations["squished-left"].sequences = animations["squished-right"].sequences = [10];
_.extend(animations, {
"wake-left": {
sequences: [10, 11],
velocity: 0,
scaleX: 1,
scaleY: 1,
delay: sequenceDelay
},
"wake-right": {
sequences: [10, 11],
velocity: 0,
scaleX: -1,
scaleY: 1,
delay: sequenceDelay
},
"walk-slide-left": {
sequences: [10],
velocity: -300,
scaleX: 1,
scaleY: 1
},
"walk-slide-right": {
sequences: [10],
velocity: 300,
scaleX: -1,
scaleY: 1
},
"fall-slide-left": {
sequences: [10],
velocity: -300,
yVelocity: animations["fall-left"].yVelocity,
yAcceleration: animations["fall-left"].yAcceleration,
scaleX: 1,
scaleY: 1
},
"fall-slide-right": {
sequences: [10],
velocity: 300,
yVelocity: animations["fall-right"].yVelocity,
yAcceleration: animations["fall-right"].yAcceleration,
scaleX: -1,
scaleY: 1
}
});
Backbone.FlyingTurtle = Backbone.Turtle.extend({
defaults: _.extend(_.deepClone(Backbone.Turtle.prototype.defaults), {
name: "flying-turtle"
}),
animations: _.deepClone(Backbone.Turtle.prototype.animations),
fallbackSprite: Backbone.Turtle,
onUpdate: function(dt) {
var cur = this.getStateInfo(),
animation = this.getAnimation(),
attrs = {};
if (cur.mov2 == null && cur.mov == "walk" && this.world.get("state") == "play") {
attrs.state = this.buildState("fall", cur.dir);
attrs.yVelocity = -this.animations["fall-right"].yVelocity;
}
if (!_.isEmpty(attrs)) this.set(attrs);
return true;
},
squish: function(sprite) {
var cur = this.getStateInfo();
var newSprite = new this.fallbackSprite({
x: this.get("x"),
y: this.get("y"),
state: "walk-" + cur.dir
});
newSprite.set("id", this.world.buildIdFromName(newSprite.get("name")));
this.world.add(newSprite);
this.world.remove(this);
this.cancelUpdate = true;
}
});
animations = Backbone.FlyingTurtle.prototype.animations;
animations["idle-left"].sequences = animations["idle-right"].sequences =
animations["fall-left"].sequences = animations["fall-right"].sequences =
animations["ko-left"].sequences = animations["ko-right"].sequences = [8];
animations["walk-left"].sequences = animations["walk-right"].sequences = [8, 9];
Backbone.RedTurtle = Backbone.Turtle.extend({
defaults: _.extend(_.deepClone(Backbone.Turtle.prototype.defaults), {
name: "red-turtle"
}),
animations: _.deepClone(Backbone.Turtle.prototype.animations)
});
animations = Backbone.RedTurtle.prototype.animations;
animations["idle-left"].sequences = animations["idle-right"].sequences =
animations["fall-left"].sequences = animations["fall-right"].sequences =
animations["ko-left"].sequences = animations["ko-right"].sequences = [108];
animations["walk-left"].sequences = animations["walk-right"].sequences = [108, 109];
animations["squished-left"].sequences = animations["squished-right"].sequences =
animations["walk-slide-left"].sequences = animations["walk-slide-right"].sequences =
animations["fall-slide-left"].sequences = animations["fall-slide-right"].sequences = [112];
animations["wake-left"].sequences = animations["wake-right"].sequences = [112, 113];
Backbone.RedFlyingTurtle = Backbone.FlyingTurtle.extend({
defaults: _.extend(_.deepClone(Backbone.FlyingTurtle.prototype.defaults), {
name: "red-flying-turtle"
}),
animations: _.deepClone(Backbone.FlyingTurtle.prototype.animations),
fallbackSprite: Backbone.RedTurtle
});
animations = Backbone.RedFlyingTurtle.prototype.animations;
animations["idle-left"].sequences = animations["idle-right"].sequences =
animations["fall-left"].sequences = animations["fall-right"].sequences =
animations["ko-left"].sequences = animations["ko-right"].sequences = [110];
animations["walk-left"].sequences = animations["walk-right"].sequences = [110, 111];
animations["squished-left"].sequences = animations["squished-right"].sequences =
animations["walk-slide-left"].sequences = animations["walk-slide-right"].sequences =
animations["fall-slide-left"].sequences = animations["fall-slide-right"].sequences = [112];
animations["wake-left"].sequences = animations["wake-right"].sequences = [112, 113];
Backbone.Beetle = Backbone.Turtle.extend({
defaults: _.extend(_.deepClone(Backbone.Turtle.prototype.defaults), {
name: "beetle"
}),
animations: _.deepClone(Backbone.Turtle.prototype.animations)
});
animations = Backbone.Beetle.prototype.animations;
animations["idle-left"].sequences = animations["idle-right"].sequences =
animations["fall-left"].sequences = animations["fall-right"].sequences =
animations["ko-left"].sequences = animations["ko-right"].sequences = [33];
animations["walk-left"].sequences = animations["walk-right"].sequences = [33, 32];
animations["squished-left"].sequences = animations["squished-right"].sequences =
animations["walk-slide-left"].sequences = animations["walk-slide-right"].sequences =
animations["fall-slide-left"].sequences = animations["fall-slide-right"].sequences =
animations["wake-left"].sequences = animations["wake-right"].sequences = [34];
Backbone.Spike = Backbone.Mushroom.extend({
defaults: _.extend(_.deepClone(Backbone.Mushroom.prototype.defaults), {
name: "spike"
}),
animations: _.deepClone(Backbone.Mushroom.prototype.animations),
squish: function() {}
});
animations = Backbone.Spike.prototype.animations;
animations["idle-left"].sequences = animations["idle-right"].sequences =
animations["fall-left"].sequences = animations["fall-right"].sequences =
animations["ko-left"].sequences = animations["ko-right"].sequences = [133];
animations["walk-left"].sequences = animations["walk-right"].sequences = [133, 132];
}).call(this); |
window.gLobal = 42 |
angular.module('app1', ['oc.lazyLoad'])
.config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
modules: [{
name: 'test',
files: []
}]
});
}]);
|
/*! JointJS v2.0.0 (2017-10-23) - JavaScript diagramming library
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
joint.shapes.basic.Generic.define('pn.Place', {
size: { width: 50, height: 50 },
attrs: {
'.root': {
r: 25,
fill: '#ffffff',
stroke: '#000000',
transform: 'translate(25, 25)'
},
'.label': {
'text-anchor': 'middle',
'ref-x': .5,
'ref-y': -20,
ref: '.root',
fill: '#000000',
'font-size': 12
},
'.tokens > circle': {
fill: '#000000',
r: 5
},
'.tokens.one > circle': { transform: 'translate(25, 25)' },
'.tokens.two > circle:nth-child(1)': { transform: 'translate(19, 25)' },
'.tokens.two > circle:nth-child(2)': { transform: 'translate(31, 25)' },
'.tokens.three > circle:nth-child(1)': { transform: 'translate(18, 29)' },
'.tokens.three > circle:nth-child(2)': { transform: 'translate(25, 19)' },
'.tokens.three > circle:nth-child(3)': { transform: 'translate(32, 29)' },
'.tokens.alot > text': {
transform: 'translate(25, 18)',
'text-anchor': 'middle',
fill: '#000000'
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><circle class="root"/><g class="tokens" /></g><text class="label"/></g>',
});
joint.shapes.pn.PlaceView = joint.dia.ElementView.extend({}, {
initialize: function() {
joint.dia.ElementView.prototype.initialize.apply(this, arguments);
this.model.on('change:tokens', function() {
this.renderTokens();
this.update();
}, this);
},
render: function() {
joint.dia.ElementView.prototype.render.apply(this, arguments);
this.renderTokens();
this.update();
},
renderTokens: function() {
var $tokens = this.$('.tokens').empty();
$tokens[0].className.baseVal = 'tokens';
var tokens = this.model.get('tokens');
if (!tokens) return;
switch (tokens) {
case 1:
$tokens[0].className.baseVal += ' one';
$tokens.append(V('<circle/>').node);
break;
case 2:
$tokens[0].className.baseVal += ' two';
$tokens.append(V('<circle/>').node, V('<circle/>').node);
break;
case 3:
$tokens[0].className.baseVal += ' three';
$tokens.append(V('<circle/>').node, V('<circle/>').node, V('<circle/>').node);
break;
default:
$tokens[0].className.baseVal += ' alot';
$tokens.append(V('<text/>').text(tokens + '').node);
break;
}
}
});
joint.shapes.basic.Generic.define('pn.Transition', {
size: { width: 12, height: 50 },
attrs: {
'rect': {
width: 12,
height: 50,
fill: '#000000',
stroke: '#000000'
},
'.label': {
'text-anchor': 'middle',
'ref-x': .5,
'ref-y': -20,
ref: 'rect',
fill: '#000000',
'font-size': 12
}
}
}, {
markup: '<g class="rotatable"><g class="scalable"><rect class="root"/></g></g><text class="label"/>',
});
joint.dia.Link.define('pn.Link', {
attrs: { '.marker-target': { d: 'M 10 0 L 0 5 L 10 10 z' } }
});
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules;
var PythonFoldMode = require("./folding/pythonic").FoldMode;
var Range = require("../range").Range;
var Mode = function() {
this.HighlightRules = PythonHighlightRules;
this.foldingRules = new PythonFoldMode("\\:");
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "#";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[\:]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};
var outdents = {
"pass": 1,
"return": 1,
"raise": 1,
"break": 1,
"continue": 1
};
this.checkOutdent = function(state, line, input) {
if (input !== "\r\n" && input !== "\r" && input !== "\n")
return false;
var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens;
if (!tokens)
return false;
// ignore trailing comments
do {
var last = tokens.pop();
} while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/))));
if (!last)
return false;
return (last.type == "keyword" && outdents[last.value]);
};
this.autoOutdent = function(state, doc, row) {
// outdenting in python is slightly different because it always applies
// to the next line and only of a new line is inserted
row += 1;
var indent = this.$getIndent(doc.getLine(row));
var tab = doc.getTabString();
if (indent.slice(-tab.length) == tab)
doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
};
this.$id = "ace/mode/python";
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
// @flow strict
import React from 'react';
import { Link } from 'gatsby';
import styles from './Tags.module.scss';
type Props = {
tags: string[],
tagSlugs: string[]
};
const Tags = ({ tags, tagSlugs }: Props) => (
<div className={styles['tags']}>
<ul className={styles['tags__list']}>
{tagSlugs && tagSlugs.map((slug, i) => (
<li className={styles['tags__list-item']} key={tags[i]}>
<Link to={slug} className={styles['tags__list-item-link']}>
{tags[i]}
</Link>
</li>
))}
</ul>
</div>
);
export default Tags;
|
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v21.2.2
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var columnGroup_1 = require("../entities/columnGroup");
var originalColumnGroup_1 = require("../entities/originalColumnGroup");
var context_1 = require("../context/context");
var context_2 = require("../context/context");
// takes in a list of columns, as specified by the column definitions, and returns column groups
var ColumnUtils = /** @class */ (function () {
function ColumnUtils() {
}
ColumnUtils.prototype.calculateColInitialWidth = function (colDef) {
if (!colDef.width) {
// if no width defined in colDef, use default
return this.gridOptionsWrapper.getColWidth();
}
else if (colDef.width < this.gridOptionsWrapper.getMinColWidth()) {
// if width in col def to small, set to min width
return this.gridOptionsWrapper.getMinColWidth();
}
else {
// otherwise use the provided width
return colDef.width;
}
};
ColumnUtils.prototype.getOriginalPathForColumn = function (column, originalBalancedTree) {
var result = [];
var found = false;
recursePath(originalBalancedTree, 0);
// we should always find the path, but in case there is a bug somewhere, returning null
// will make it fail rather than provide a 'hard to track down' bug
if (found) {
return result;
}
else {
return null;
}
function recursePath(balancedColumnTree, dept) {
for (var i = 0; i < balancedColumnTree.length; i++) {
if (found) {
// quit the search, so 'result' is kept with the found result
return;
}
var node = balancedColumnTree[i];
if (node instanceof originalColumnGroup_1.OriginalColumnGroup) {
var nextNode = node;
recursePath(nextNode.getChildren(), dept + 1);
result[dept] = node;
}
else {
if (node === column) {
found = true;
}
}
}
}
};
/* public getPathForColumn(column: Column, allDisplayedColumnGroups: ColumnGroupChild[]): ColumnGroup[] {
let result: ColumnGroup[] = [];
let found = false;
recursePath(allDisplayedColumnGroups, 0);
// we should always find the path, but in case there is a bug somewhere, returning null
// will make it fail rather than provide a 'hard to track down' bug
if (found) {
return result;
} else {
return null;
}
function recursePath(balancedColumnTree: ColumnGroupChild[], dept: number): void {
for (let i = 0; i<balancedColumnTree.length; i++) {
if (found) {
// quit the search, so 'result' is kept with the found result
return;
}
let node = balancedColumnTree[i];
if (node instanceof ColumnGroup) {
let nextNode = <ColumnGroup> node;
recursePath(nextNode.getChildren(), dept+1);
result[dept] = node;
} else {
if (node === column) {
found = true;
}
}
}
}
}*/
ColumnUtils.prototype.depthFirstOriginalTreeSearch = function (parent, tree, callback) {
var _this = this;
if (!tree) {
return;
}
tree.forEach(function (child) {
if (child instanceof originalColumnGroup_1.OriginalColumnGroup) {
_this.depthFirstOriginalTreeSearch(child, child.getChildren(), callback);
}
callback(child, parent);
});
};
ColumnUtils.prototype.depthFirstAllColumnTreeSearch = function (tree, callback) {
var _this = this;
if (!tree) {
return;
}
tree.forEach(function (child) {
if (child instanceof columnGroup_1.ColumnGroup) {
_this.depthFirstAllColumnTreeSearch(child.getChildren(), callback);
}
callback(child);
});
};
ColumnUtils.prototype.depthFirstDisplayedColumnTreeSearch = function (tree, callback) {
var _this = this;
if (!tree) {
return;
}
tree.forEach(function (child) {
if (child instanceof columnGroup_1.ColumnGroup) {
_this.depthFirstDisplayedColumnTreeSearch(child.getDisplayedChildren(), callback);
}
callback(child);
});
};
__decorate([
context_2.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], ColumnUtils.prototype, "gridOptionsWrapper", void 0);
ColumnUtils = __decorate([
context_1.Bean('columnUtils')
], ColumnUtils);
return ColumnUtils;
}());
exports.ColumnUtils = ColumnUtils;
|
/* http://keith-wood.name/calendars.html
Czech localisation for calendars datepicker for jQuery.
Written by Tomas Muller (tomas@tomas-muller.net). */
(function($) {
'use strict';
$.calendarsPicker.regionalOptions.cs = {
renderer: $.calendarsPicker.defaultRenderer,
prevText: '<Dříve',
prevStatus: 'Přejít na předchozí měsí',
prevJumpText: '<<',
prevJumpStatus: '',
nextText: 'Později>',
nextStatus: 'Přejít na další měsíc',
nextJumpText: '>>',
nextJumpStatus: '',
currentText: 'Nyní',
currentStatus: 'Přejde na aktuální měsíc',
todayText: 'Nyní',
todayStatus: 'Přejde na aktuální měsíc',
clearText: 'Vymazat',
clearStatus: 'Vymaže zadané datum',
closeText: 'Zavřít',
closeStatus: 'Zavře kalendář beze změny',
yearStatus: 'Přejít na jiný rok',
monthStatus: 'Přejít na jiný měsíc',
weekText: 'Týd',
weekStatus: 'Týden v roce',
dayStatus: '\'Vyber\' DD, M d',
defaultStatus: 'Vyberte datum',
isRTL: false
};
$.calendarsPicker.setDefaults($.calendarsPicker.regionalOptions.cs);
})(jQuery);
|
/* http://keith-wood.name/calendars.html
Romansh localisation for Gregorian/Julian calendars for jQuery.
Yvonne Gienal (yvonne.gienal@educa.ch). */
(function($) {
'use strict';
$.calendars.calendars.gregorian.prototype.regionalOptions.rm = {
name: 'Gregorian',
epochs: ['BCE', 'CE'],
monthNames: ['Schaner','Favrer','Mars','Avrigl','Matg','Zercladur',
'Fanadur','Avust','Settember','October','November','December'],
monthNamesShort: ['Scha','Fev','Mar','Avr','Matg','Zer',
'Fan','Avu','Sett','Oct','Nov','Dec'],
dayNames: ['Dumengia','Glindesdi','Mardi','Mesemna','Gievgia','Venderdi','Sonda'],
dayNamesShort: ['Dum','Gli','Mar','Mes','Gie','Ven','Som'],
dayNamesMin: ['Du','Gl','Ma','Me','Gi','Ve','So'],
digits: null,
dateFormat: 'dd/mm/yyyy',
firstDay: 1,
isRTL: false
};
if ($.calendars.calendars.julian) {
$.calendars.calendars.julian.prototype.regionalOptions.rm =
$.calendars.calendars.gregorian.prototype.regionalOptions.rm;
}
})(jQuery);
|
/*globals describe, beforeEach, afterEach, it*/
/*jshint expr:true*/
var path = require('path'),
EventEmitter = require('events').EventEmitter,
should = require('should'),
sinon = require('sinon'),
_ = require('lodash'),
when = require('when'),
helpers = require('../../server/helpers'),
filters = require('../../server/filters'),
// Stuff we are testing
AppProxy = require('../../server/apps/proxy'),
AppSandbox = require('../../server/apps/sandbox'),
AppDependencies = require('../../server/apps/dependencies'),
AppPermissions = require('../../server/apps/permissions');
describe('Apps', function () {
var sandbox,
fakeApi;
beforeEach(function () {
sandbox = sinon.sandbox.create();
fakeApi = {
posts: {
browse: sandbox.stub(),
read: sandbox.stub(),
edit: sandbox.stub(),
add: sandbox.stub(),
destroy: sandbox.stub()
},
users: {
browse: sandbox.stub(),
read: sandbox.stub(),
edit: sandbox.stub()
},
tags: {
all: sandbox.stub()
},
notifications: {
destroy: sandbox.stub(),
add: sandbox.stub()
},
settings: {
browse: sandbox.stub(),
read: sandbox.stub(),
add: sandbox.stub()
}
};
});
afterEach(function () {
sandbox.restore();
});
describe('Proxy', function () {
it('requires a name to be passed', function () {
function makeWithoutName() {
return new AppProxy({});
}
makeWithoutName.should.throw('Must provide an app name for api context');
});
it('requires permissions to be passed', function () {
function makeWithoutPerms() {
return new AppProxy({
name: 'NoPerms'
});
}
makeWithoutPerms.should.throw('Must provide app permissions');
});
it('creates a ghost proxy', function () {
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['prePostRender'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
should.exist(appProxy.filters);
should.exist(appProxy.filters.register);
should.exist(appProxy.filters.deregister);
should.exist(appProxy.helpers);
should.exist(appProxy.helpers.register);
should.exist(appProxy.helpers.registerAsync);
should.exist(appProxy.api);
should.exist(appProxy.api.posts);
should.exist(appProxy.api.posts.browse);
should.exist(appProxy.api.posts.read);
should.exist(appProxy.api.posts.edit);
should.exist(appProxy.api.posts.add);
should.exist(appProxy.api.posts.destroy);
should.not.exist(appProxy.api.users);
should.exist(appProxy.api.tags);
should.exist(appProxy.api.tags.browse);
should.exist(appProxy.api.notifications);
should.exist(appProxy.api.notifications.browse);
should.exist(appProxy.api.notifications.add);
should.exist(appProxy.api.notifications.destroy);
should.exist(appProxy.api.settings);
should.exist(appProxy.api.settings.browse);
should.exist(appProxy.api.settings.read);
should.exist(appProxy.api.settings.edit);
});
it('allows filter registration with permission', function (done) {
var registerSpy = sandbox.spy(filters, 'registerFilter');
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['testFilter'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
var fakePosts = [{ id: 0 }, { id: 1 }];
var filterStub = sandbox.spy(function (val) {
return val;
});
appProxy.filters.register('testFilter', 5, filterStub);
registerSpy.called.should.equal(true);
filterStub.called.should.equal(false);
filters.doFilter('testFilter', fakePosts)
.then(function () {
filterStub.called.should.equal(true);
appProxy.filters.deregister('testFilter', 5, filterStub);
done();
})
.catch(done);
});
it('does not allow filter registration without permission', function () {
var registerSpy = sandbox.spy(filters, 'registerFilter');
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['prePostRender'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
var filterStub = sandbox.stub().returns('test result');
function registerFilterWithoutPermission() {
appProxy.filters.register('superSecretFilter', 5, filterStub);
}
registerFilterWithoutPermission.should.throw('The App "TestApp" attempted to perform an action or access' +
' a resource (filters.superSecretFilter) without permission.');
registerSpy.called.should.equal(false);
});
it('allows filter deregistration with permission', function (done) {
var registerSpy = sandbox.spy(filters, 'deregisterFilter');
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['prePostsRender'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
var fakePosts = [{ id: 0 }, { id: 1 }];
var filterStub = sandbox.stub().returns(fakePosts);
appProxy.filters.deregister('prePostsRender', 5, filterStub);
registerSpy.called.should.equal(true);
filterStub.called.should.equal(false);
filters.doFilter('prePostsRender', fakePosts)
.then(function () {
filterStub.called.should.equal(false);
done();
})
.catch(done);
});
it('does not allow filter deregistration without permission', function () {
var registerSpy = sandbox.spy(filters, 'deregisterFilter');
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['prePostRender'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
var filterStub = sandbox.stub().returns('test result');
function deregisterFilterWithoutPermission() {
appProxy.filters.deregister('superSecretFilter', 5, filterStub);
}
deregisterFilterWithoutPermission.should.throw('The App "TestApp" attempted to perform an action or ' +
'access a resource (filters.superSecretFilter) without permission.');
registerSpy.called.should.equal(false);
});
it('allows helper registration with permission', function () {
var registerSpy = sandbox.spy(helpers, 'registerThemeHelper');
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['prePostRender'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
appProxy.helpers.register('myTestHelper', sandbox.stub().returns('test result'));
registerSpy.called.should.equal(true);
});
it('does not allow helper registration without permission', function () {
var registerSpy = sandbox.spy(helpers, 'registerThemeHelper');
var appProxy = new AppProxy({
name: 'TestApp',
permissions: {
filters: ['prePostRender'],
helpers: ['myTestHelper'],
posts: ['browse', 'read', 'edit', 'add', 'delete']
}
});
function registerWithoutPermissions() {
appProxy.helpers.register('otherHelper', sandbox.stub().returns('test result'));
}
registerWithoutPermissions.should.throw('The App "TestApp" attempted to perform an action or access a ' +
'resource (helpers.otherHelper) without permission.');
registerSpy.called.should.equal(false);
});
});
describe('Sandbox', function () {
it('loads apps in a sandbox', function () {
var appBox = new AppSandbox(),
appPath = path.resolve(__dirname, '..', 'utils', 'fixtures', 'app', 'good.js'),
GoodApp,
appProxy = new AppProxy({
name: 'TestApp',
permissions: {}
}),
app;
GoodApp = appBox.loadApp(appPath);
should.exist(GoodApp);
app = new GoodApp(appProxy);
app.install(appProxy);
app.app.something.should.equal(42);
app.app.util.util().should.equal(42);
app.app.nested.other.should.equal(42);
app.app.path.should.equal(appPath);
});
it('does not allow apps to require blacklisted modules at top level', function () {
var appBox = new AppSandbox(),
badAppPath = path.join(__dirname, '..', 'utils', 'fixtures', 'app', 'badtop.js'),
loadApp = function () {
appBox.loadApp(badAppPath);
};
loadApp.should.throw('Unsafe App require: knex');
});
it('does not allow apps to require blacklisted modules at install', function () {
var appBox = new AppSandbox(),
badAppPath = path.join(__dirname, '..', 'utils', 'fixtures', 'app', 'badinstall.js'),
BadApp,
appProxy = new AppProxy({
name: 'TestApp',
permissions: {}
}),
app,
installApp = function () {
app.install(appProxy);
};
BadApp = appBox.loadApp(badAppPath);
app = new BadApp(appProxy);
installApp.should.throw('Unsafe App require: knex');
});
it('does not allow apps to require blacklisted modules from other requires', function () {
var appBox = new AppSandbox(),
badAppPath = path.join(__dirname, '..', 'utils', 'fixtures', 'app', 'badrequire.js'),
BadApp,
loadApp = function () {
BadApp = appBox.loadApp(badAppPath);
};
loadApp.should.throw('Unsafe App require: knex');
});
it('does not allow apps to require modules relatively outside their directory', function () {
var appBox = new AppSandbox(),
badAppPath = path.join(__dirname, '..', 'utils', 'fixtures', 'app', 'badoutside.js'),
BadApp,
loadApp = function () {
BadApp = appBox.loadApp(badAppPath);
};
loadApp.should.throw(/^Unsafe App require[\w\W]*example$/);
});
});
describe('Dependencies', function () {
it('can install by package.json', function (done) {
var deps = new AppDependencies(process.cwd()),
fakeEmitter = new EventEmitter();
deps.spawnCommand = sandbox.stub().returns(fakeEmitter);
deps.install().then(function () {
deps.spawnCommand.calledWith('npm').should.equal(true);
done();
}).catch(done);
_.delay(function () {
fakeEmitter.emit('exit');
}, 30);
});
it('does not install when no package.json', function (done) {
var deps = new AppDependencies(__dirname),
fakeEmitter = new EventEmitter();
deps.spawnCommand = sandbox.stub().returns(fakeEmitter);
deps.install().then(function () {
deps.spawnCommand.called.should.equal(false);
done();
}).catch(done);
_.defer(function () {
fakeEmitter.emit('exit');
});
});
});
describe('Permissions', function () {
/*jshint quotmark:false*/
var noGhostPackageJson = {
"name": "myapp",
"version": "0.0.1",
"description": "My example app",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Ghost",
"license": "MIT",
"dependencies": {
"ghost-app": "0.0.1"
}
},
validGhostPackageJson = {
"name": "myapp",
"version": "0.0.1",
"description": "My example app",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Ghost",
"license": "MIT",
"dependencies": {
"ghost-app": "0.0.1"
},
"ghost": {
"permissions": {
"posts": ["browse", "read", "edit", "add", "delete"],
"users": ["browse", "read", "edit", "add", "delete"],
"settings": ["browse", "read", "edit", "add", "delete"]
}
}
};
it('has default permissions to read and browse posts', function () {
should.exist(AppPermissions.DefaultPermissions);
should.exist(AppPermissions.DefaultPermissions.posts);
AppPermissions.DefaultPermissions.posts.should.contain('browse');
AppPermissions.DefaultPermissions.posts.should.contain('read');
// Make it hurt to add more so additional checks are added here
_.keys(AppPermissions.DefaultPermissions).length.should.equal(1);
});
it('uses default permissions if no package.json', function (done) {
var perms = new AppPermissions("test");
// No package.json in this directory
sandbox.stub(perms, "checkPackageContentsExists").returns(when.resolve(false));
perms.read().then(function (readPerms) {
should.exist(readPerms);
readPerms.should.equal(AppPermissions.DefaultPermissions);
done();
}).catch(done);
});
it('uses default permissions if no ghost object in package.json', function (done) {
var perms = new AppPermissions("test"),
noGhostPackageJsonContents = JSON.stringify(noGhostPackageJson, null, 2);
// package.json IS in this directory
sandbox.stub(perms, "checkPackageContentsExists").returns(when.resolve(true));
// no ghost property on package
sandbox.stub(perms, "getPackageContents").returns(when.resolve(noGhostPackageJsonContents));
perms.read().then(function (readPerms) {
should.exist(readPerms);
readPerms.should.equal(AppPermissions.DefaultPermissions);
done();
}).catch(done);
});
it('rejects when reading malformed package.json', function (done) {
var perms = new AppPermissions("test");
// package.json IS in this directory
sandbox.stub(perms, "checkPackageContentsExists").returns(when.resolve(true));
// malformed JSON on package
sandbox.stub(perms, "getPackageContents").returns(when.reject(new Error('package.json file is malformed')));
perms.read().then(function (readPerms) {
/*jshint unused:false*/
done(new Error('should not resolve'));
}).catch(function (err) {
err.message.should.equal('package.json file is malformed');
done();
});
});
it('reads from package.json in root of app directory', function (done) {
var perms = new AppPermissions("test"),
validGhostPackageJsonContents = validGhostPackageJson;
// package.json IS in this directory
sandbox.stub(perms, "checkPackageContentsExists").returns(when.resolve(true));
// valid ghost property on package
sandbox.stub(perms, "getPackageContents").returns(when.resolve(validGhostPackageJsonContents));
perms.read().then(function (readPerms) {
should.exist(readPerms);
readPerms.should.not.equal(AppPermissions.DefaultPermissions);
should.exist(readPerms.posts);
readPerms.posts.length.should.equal(5);
should.exist(readPerms.users);
readPerms.users.length.should.equal(5);
should.exist(readPerms.settings);
readPerms.settings.length.should.equal(5);
_.keys(readPerms).length.should.equal(3);
done();
}).catch(done);
});
});
});
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'showblocks', 'th', {
toolbar: 'แสดงบล็อคข้อมูล'
} );
|
var x = React.DOM.div({
foo: "bar"
}, React.DOM["font-face"](null));
|
/*!
Shoelace.css dropdowns 1.0.0-beta21
(c) A Beautiful Site, LLC
Released under the MIT license
Source: https://github.com/claviska/shoelace-css
*/
!function(){"use strict";if("undefined"==typeof jQuery&&"undefined"==typeof Zepto)throw new Error("Shoelace dropdowns require either jQuery or Zepto.");("function"==typeof jQuery?jQuery:Zepto)(function(e){e(document).on("click",function(t){var r,i,o;if(e(t.target).closest(".dropdown-trigger")){if(r=e(t.target).closest(".dropdown"),o=t.target,e(".dropdown.active").not(r).removeClass("active").trigger("hide"),e(o).is(".disabled, :disabled"))return;e(r).toggleClass("active").trigger(e(r).is(".active")?"show":"hide")}else e(t.target).closest(".dropdown-menu").length&&(r=e(t.target).closest(".dropdown"),(i=e(t.target).closest("a").get(0))&&!e(i).is(".disabled")&&e(r).trigger("select",i),t.preventDefault()),e(".dropdown.active").removeClass("active").trigger("hide")}).on("keydown",function(t){27===t.keyCode&&e(".dropdown.active").removeClass("active").trigger("hide")})})}(),/*!
Shoelace.css tabs 1.0.0-beta21
(c) A Beautiful Site, LLC
Released under the MIT license
Source: https://github.com/claviska/shoelace-css
*/
function(){"use strict";if("undefined"==typeof jQuery&&"undefined"==typeof Zepto)throw new Error("Shoelace tabs require either jQuery or Zepto.");(window.jQuery||window.Zepto)(function(e){new MutationObserver(function(t){t.forEach(function(t){if("attributes"===t.type&&"class"===t.attributeName){var r=e(t.target).get(0),i=e(t.target).closest(".tabs").get(0),o=e(t.target).closest(".tabs-nav").get(0),a="A"===r.tagName?e(i).find(r.hash):null;if(!e(r).is("a")||!i||!o)return;if(e(r).is(".disabled.active"))return void e(r).removeClass("active");e(r).is(".active")?(e(r).siblings(".active").removeClass("active"),e(a).addClass("active"),e(i).trigger("show",a)):(e(a).removeClass("active"),e(i).trigger("hide",a))}})}).observe(document.body,{attributes:!0,attributeFilter:["class"],attributeOldValue:!0,subtree:!0}),e(document).on("click",".tabs-nav a",function(t){e(this).addClass("active"),t.preventDefault()})})}(); |
'use strict';
!function($) {
/**
* Equalizer module.
* @module foundation.equalizer
* @requires foundation.util.mediaQuery
* @requires foundation.util.timerAndImageLoader if equalizer contains images
*/
class Equalizer {
/**
* Creates a new instance of Equalizer.
* @class
* @fires Equalizer#init
* @param {Object} element - jQuery object to add the trigger to.
* @param {Object} options - Overrides to the default plugin settings.
*/
constructor(element, options){
this.$element = element;
this.options = $.extend({}, Equalizer.defaults, this.$element.data(), options);
this._init();
Foundation.registerPlugin(this, 'Equalizer');
}
/**
* Initializes the Equalizer plugin and calls functions to get equalizer functioning on load.
* @private
*/
_init() {
var eqId = this.$element.attr('data-equalizer') || '';
var $watched = this.$element.find(`[data-equalizer-watch="${eqId}"]`);
this.$watched = $watched.length ? $watched : this.$element.find('[data-equalizer-watch]');
this.$element.attr('data-resize', (eqId || Foundation.GetYoDigits(6, 'eq')));
this.$element.attr('data-mutate', (eqId || Foundation.GetYoDigits(6, 'eq')));
this.hasNested = this.$element.find('[data-equalizer]').length > 0;
this.isNested = this.$element.parentsUntil(document.body, '[data-equalizer]').length > 0;
this.isOn = false;
this._bindHandler = {
onResizeMeBound: this._onResizeMe.bind(this),
onPostEqualizedBound: this._onPostEqualized.bind(this)
};
var imgs = this.$element.find('img');
var tooSmall;
if(this.options.equalizeOn){
tooSmall = this._checkMQ();
$(window).on('changed.zf.mediaquery', this._checkMQ.bind(this));
}else{
this._events();
}
if((tooSmall !== undefined && tooSmall === false) || tooSmall === undefined){
if(imgs.length){
Foundation.onImagesLoaded(imgs, this._reflow.bind(this));
}else{
this._reflow();
}
}
}
/**
* Removes event listeners if the breakpoint is too small.
* @private
*/
_pauseEvents() {
this.isOn = false;
this.$element.off({
'.zf.equalizer': this._bindHandler.onPostEqualizedBound,
'resizeme.zf.trigger': this._bindHandler.onResizeMeBound,
'mutateme.zf.trigger': this._bindHandler.onResizeMeBound
});
}
/**
* function to handle $elements resizeme.zf.trigger, with bound this on _bindHandler.onResizeMeBound
* @private
*/
_onResizeMe(e) {
this._reflow();
}
/**
* function to handle $elements postequalized.zf.equalizer, with bound this on _bindHandler.onPostEqualizedBound
* @private
*/
_onPostEqualized(e) {
if(e.target !== this.$element[0]){ this._reflow(); }
}
/**
* Initializes events for Equalizer.
* @private
*/
_events() {
var _this = this;
this._pauseEvents();
if(this.hasNested){
this.$element.on('postequalized.zf.equalizer', this._bindHandler.onPostEqualizedBound);
}else{
this.$element.on('resizeme.zf.trigger', this._bindHandler.onResizeMeBound);
this.$element.on('mutateme.zf.trigger', this._bindHandler.onResizeMeBound);
}
this.isOn = true;
}
/**
* Checks the current breakpoint to the minimum required size.
* @private
*/
_checkMQ() {
var tooSmall = !Foundation.MediaQuery.is(this.options.equalizeOn);
if(tooSmall){
if(this.isOn){
this._pauseEvents();
this.$watched.css('height', 'auto');
}
}else{
if(!this.isOn){
this._events();
}
}
return tooSmall;
}
/**
* A noop version for the plugin
* @private
*/
_killswitch() {
return;
}
/**
* Calls necessary functions to update Equalizer upon DOM change
* @private
*/
_reflow() {
if(!this.options.equalizeOnStack){
if(this._isStacked()){
this.$watched.css('height', 'auto');
return false;
}
}
if (this.options.equalizeByRow) {
this.getHeightsByRow(this.applyHeightByRow.bind(this));
}else{
this.getHeights(this.applyHeight.bind(this));
}
}
/**
* Manually determines if the first 2 elements are *NOT* stacked.
* @private
*/
_isStacked() {
if (!this.$watched[0] || !this.$watched[1]) {
return true;
}
return this.$watched[0].getBoundingClientRect().top !== this.$watched[1].getBoundingClientRect().top;
}
/**
* Finds the outer heights of children contained within an Equalizer parent and returns them in an array
* @param {Function} cb - A non-optional callback to return the heights array to.
* @returns {Array} heights - An array of heights of children within Equalizer container
*/
getHeights(cb) {
var heights = [];
for(var i = 0, len = this.$watched.length; i < len; i++){
this.$watched[i].style.height = 'auto';
heights.push(this.$watched[i].offsetHeight);
}
cb(heights);
}
/**
* Finds the outer heights of children contained within an Equalizer parent and returns them in an array
* @param {Function} cb - A non-optional callback to return the heights array to.
* @returns {Array} groups - An array of heights of children within Equalizer container grouped by row with element,height and max as last child
*/
getHeightsByRow(cb) {
var lastElTopOffset = (this.$watched.length ? this.$watched.first().offset().top : 0),
groups = [],
group = 0;
//group by Row
groups[group] = [];
for(var i = 0, len = this.$watched.length; i < len; i++){
this.$watched[i].style.height = 'auto';
//maybe could use this.$watched[i].offsetTop
var elOffsetTop = $(this.$watched[i]).offset().top;
if (elOffsetTop!=lastElTopOffset) {
group++;
groups[group] = [];
lastElTopOffset=elOffsetTop;
}
groups[group].push([this.$watched[i],this.$watched[i].offsetHeight]);
}
for (var j = 0, ln = groups.length; j < ln; j++) {
var heights = $(groups[j]).map(function(){ return this[1]; }).get();
var max = Math.max.apply(null, heights);
groups[j].push(max);
}
cb(groups);
}
/**
* Changes the CSS height property of each child in an Equalizer parent to match the tallest
* @param {array} heights - An array of heights of children within Equalizer container
* @fires Equalizer#preequalized
* @fires Equalizer#postequalized
*/
applyHeight(heights) {
var max = Math.max.apply(null, heights);
/**
* Fires before the heights are applied
* @event Equalizer#preequalized
*/
this.$element.trigger('preequalized.zf.equalizer');
this.$watched.css('height', max);
/**
* Fires when the heights have been applied
* @event Equalizer#postequalized
*/
this.$element.trigger('postequalized.zf.equalizer');
}
/**
* Changes the CSS height property of each child in an Equalizer parent to match the tallest by row
* @param {array} groups - An array of heights of children within Equalizer container grouped by row with element,height and max as last child
* @fires Equalizer#preequalized
* @fires Equalizer#preequalizedrow
* @fires Equalizer#postequalizedrow
* @fires Equalizer#postequalized
*/
applyHeightByRow(groups) {
/**
* Fires before the heights are applied
*/
this.$element.trigger('preequalized.zf.equalizer');
for (var i = 0, len = groups.length; i < len ; i++) {
var groupsILength = groups[i].length,
max = groups[i][groupsILength - 1];
if (groupsILength<=2) {
$(groups[i][0][0]).css({'height':'auto'});
continue;
}
/**
* Fires before the heights per row are applied
* @event Equalizer#preequalizedrow
*/
this.$element.trigger('preequalizedrow.zf.equalizer');
for (var j = 0, lenJ = (groupsILength-1); j < lenJ ; j++) {
$(groups[i][j][0]).css({'height':max});
}
/**
* Fires when the heights per row have been applied
* @event Equalizer#postequalizedrow
*/
this.$element.trigger('postequalizedrow.zf.equalizer');
}
/**
* Fires when the heights have been applied
*/
this.$element.trigger('postequalized.zf.equalizer');
}
/**
* Destroys an instance of Equalizer.
* @function
*/
destroy() {
this._pauseEvents();
this.$watched.css('height', 'auto');
Foundation.unregisterPlugin(this);
}
}
/**
* Default settings for plugin
*/
Equalizer.defaults = {
/**
* Enable height equalization when stacked on smaller screens.
* @option
* @example true
*/
equalizeOnStack: false,
/**
* Enable height equalization row by row.
* @option
* @example false
*/
equalizeByRow: false,
/**
* String representing the minimum breakpoint size the plugin should equalize heights on.
* @option
* @example 'medium'
*/
equalizeOn: ''
};
// Window exports
Foundation.plugin(Equalizer, 'Equalizer');
}(jQuery);
|
/**
* @overview datejs
* @version 1.0.0-rc3
* @author Gregory Wild-Smith <gregory@wild-smith.com>
* @copyright 2014 Gregory Wild-Smith
* @license MIT
* @homepage https://github.com/abritinthebay/datejs
*/
/*
2014 Gregory Wild-Smith
@license MIT
@homepage https://github.com/abritinthebay/datejs
2014 Gregory Wild-Smith
@license MIT
@homepage https://github.com/abritinthebay/datejs
*/
Date.CultureStrings=Date.CultureStrings||{};
Date.CultureStrings["syr-SY"]={name:"syr-SY",englishName:"Syriac (Syria)",nativeName:"\u0723\u0718\u072a\u071d\u071d\u0710 (\u0633\u0648\u0631\u064a\u0627)",Sunday:"\u071a\u0715\u00a0\u0712\u072b\u0712\u0710",Monday:"\u072c\u072a\u071d\u0722\u00a0\u0712\u072b\u0712\u0710",Tuesday:"\u072c\u0720\u072c\u0710\u00a0\u0712\u072b\u0712\u0710",Wednesday:"\u0710\u072a\u0712\u0725\u0710\u00a0\u0712\u072b\u0712\u0710",Thursday:"\u071a\u0721\u072b\u0710\u00a0\u0712\u072b\u0712\u0710",Friday:"\u0725\u072a\u0718\u0712\u072c\u0710",
Saturday:"\u072b\u0712\u072c\u0710",Sun:"\u070f\u0710\u00a0\u070f\u0712\u072b",Mon:"\u070f\u0712\u00a0\u070f\u0712\u072b",Tue:"\u070f\u0713\u00a0\u070f\u0712\u072b",Wed:"\u070f\u0715\u00a0\u070f\u0712\u072b",Thu:"\u070f\u0717\u00a0\u070f\u0712\u072b",Fri:"\u070f\u0725\u072a\u0718\u0712",Sat:"\u070f\u072b\u0712",Su:"\u070f",Mo:"\u070f",Tu:"\u070f",We:"\u070f",Th:"\u070f",Fr:"\u070f",Sa:"\u070f",S_Sun_Initial:"\u070f",M_Mon_Initial:"\u070f",T_Tue_Initial:"\u070f",W_Wed_Initial:"\u070f",T_Thu_Initial:"\u070f",
F_Fri_Initial:"\u070f",S_Sat_Initial:"\u070f",January:"\u071f\u0722\u0718\u0722\u00a0\u0710\u071a\u072a\u071d",February:"\u072b\u0712\u071b",March:"\u0710\u0715\u072a",April:"\u0722\u071d\u0723\u0722",May:"\u0710\u071d\u072a",June:"\u071a\u0719\u071d\u072a\u0722",July:"\u072c\u0721\u0718\u0719",August:"\u0710\u0712",September:"\u0710\u071d\u0720\u0718\u0720",October:"\u072c\u072b\u072a\u071d\u00a0\u0729\u0715\u071d\u0721",November:"\u072c\u072b\u072a\u071d\u00a0\u0710\u071a\u072a\u071d",December:"\u071f\u0722\u0718\u0722\u00a0\u0729\u0715\u071d\u0721",
Jan_Abbr:"\u070f\u071f\u0722\u00a0\u070f\u0712",Feb_Abbr:"\u072b\u0712\u071b",Mar_Abbr:"\u0710\u0715\u072a",Apr_Abbr:"\u0722\u071d\u0723\u0722",May_Abbr:"\u0710\u071d\u072a",Jun_Abbr:"\u071a\u0719\u071d\u072a\u0722",Jul_Abbr:"\u072c\u0721\u0718\u0719",Aug_Abbr:"\u0710\u0712",Sep_Abbr:"\u0710\u071d\u0720\u0718\u0720",Oct_Abbr:"\u070f\u072c\u072b\u00a0\u070f\u0710",Nov_Abbr:"\u070f\u072c\u072b\u00a0\u070f\u0712",Dec_Abbr:"\u070f\u071f\u0722\u00a0\u070f\u0710",AM:"\u0729.\u071b",PM:"\u0712.\u071b",firstDayOfWeek:6,
twoDigitYearMax:2029,mdy:"dmy","M/d/yyyy":"dd/MM/yyyy","dddd, MMMM dd, yyyy":"dd MMMM, yyyy","h:mm tt":"hh:mm tt","h:mm:ss tt":"hh:mm:ss tt","dddd, MMMM dd, yyyy h:mm:ss tt":"dd MMMM, yyyy hh:mm:ss tt","yyyy-MM-ddTHH:mm:ss":"yyyy-MM-ddTHH:mm:ss","yyyy-MM-dd HH:mm:ssZ":"yyyy-MM-dd HH:mm:ssZ","ddd, dd MMM yyyy HH:mm:ss":"ddd, dd MMM yyyy HH:mm:ss","MMMM dd":"dd MMMM","MMMM, yyyy":"MMMM, yyyy","/jan(uary)?/":"\u071f\u0722\u0718\u0722\u00a0\u0710\u071a\u072a\u071d","/feb(ruary)?/":"\u072b\u0712\u071b",
"/mar(ch)?/":"\u0710\u0715\u072a","/apr(il)?/":"\u0722\u071d\u0723\u0722","/may/":"\u0710\u071d\u072a","/jun(e)?/":"\u071a\u0719\u071d\u072a\u0722","/jul(y)?/":"\u072c\u0721\u0718\u0719","/aug(ust)?/":"\u0710\u0712","/sep(t(ember)?)?/":"\u0710\u071d\u0720\u0718\u0720","/oct(ober)?/":"\u072c\u072b\u072a\u071d\u00a0\u0729\u0715\u071d\u0721","/nov(ember)?/":"\u072c\u072b\u072a\u071d\u00a0\u0710\u071a\u072a\u071d","/dec(ember)?/":"\u071f\u0722\u0718\u0722\u00a0\u0729\u0715\u071d\u0721","/^su(n(day)?)?/":"^\u070f(\u0710\u00a0\u070f\u0712\u072b(\u0710)?)?",
"/^mo(n(day)?)?/":"^\u070f(\u0712\u00a0\u070f\u0712\u072b(\u072b\u0712\u0710)?)?","/^tu(e(s(day)?)?)?/":"^\u070f(\u0713\u00a0\u070f\u0712\u072b(\u072b\u0712\u0710)?)?","/^we(d(nesday)?)?/":"^\u070f(\u0715\u00a0\u070f\u0712\u072b(\u0712\u072b\u0712\u0710)?)?","/^th(u(r(s(day)?)?)?)?/":"^\u070f(\u0717\u00a0\u070f\u0712\u072b(\u072b\u0712\u0710)?)?","/^fr(i(day)?)?/":"^\u070f(\u0725\u072a\u0718\u0712(\u0710)?)?","/^sa(t(urday)?)?/":"^\u070f(\u072b\u0712(\u0710)?)?","/^next/":"^next","/^last|past|prev(ious)?/":"^last|past|prev(ious)?",
"/^(\\+|aft(er)?|from|hence)/":"^(\\+|aft(er)?|from|hence)","/^(\\-|bef(ore)?|ago)/":"^(\\-|bef(ore)?|ago)","/^yes(terday)?/":"^yes(terday)?","/^t(od(ay)?)?/":"^t(od(ay)?)?","/^tom(orrow)?/":"^tom(orrow)?","/^n(ow)?/":"^n(ow)?","/^ms|milli(second)?s?/":"^ms|milli(second)?s?","/^sec(ond)?s?/":"^sec(ond)?s?","/^mn|min(ute)?s?/":"^mn|min(ute)?s?","/^h(our)?s?/":"^h(our)?s?","/^w(eek)?s?/":"^w(eek)?s?","/^m(onth)?s?/":"^m(onth)?s?","/^d(ay)?s?/":"^d(ay)?s?","/^y(ear)?s?/":"^y(ear)?s?","/^(a|p)/":"^(a|p)",
"/^(a\\.?m?\\.?|p\\.?m?\\.?)/":"^(a\\.?m?\\.?|p\\.?m?\\.?)","/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/":"^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)","/^\\s*(st|nd|rd|th)/":"^\\s*(st|nd|rd|th)","/^\\s*(\\:|a(?!u|p)|p)/":"^\\s*(\\:|a(?!u|p)|p)",LINT:"LINT",TOT:"TOT",CHAST:"CHAST",NZST:"NZST",NFT:"NFT",SBT:"SBT",AEST:"AEST",ACST:"ACST",JST:"JST",CWST:"CWST",CT:"CT",ICT:"ICT",MMT:"MMT",BIOT:"BST",NPT:"NPT",IST:"IST",
PKT:"PKT",AFT:"AFT",MSK:"MSK",IRST:"IRST",FET:"FET",EET:"EET",CET:"CET",UTC:"UTC",GMT:"GMT",CVT:"CVT",GST:"GST",BRT:"BRT",NST:"NST",AST:"AST",EST:"EST",CST:"CST",MST:"MST",PST:"PST",AKST:"AKST",MIT:"MIT",HST:"HST",SST:"SST",BIT:"BIT",CHADT:"CHADT",NZDT:"NZDT",AEDT:"AEDT",ACDT:"ACDT",AZST:"AZST",IRDT:"IRDT",EEST:"EEST",CEST:"CEST",BST:"BST",PMDT:"PMDT",ADT:"ADT",NDT:"NDT",EDT:"EDT",CDT:"CDT",MDT:"MDT",PDT:"PDT",AKDT:"AKDT",HADT:"HADT"};Date.CultureStrings.lang="syr-SY";
(function(){var h=Date,f=Date.CultureStrings?Date.CultureStrings.lang:null,d={},c={getFromKey:function(a,b){var e;e=Date.CultureStrings&&Date.CultureStrings[b]&&Date.CultureStrings[b][a]?Date.CultureStrings[b][a]:c.buildFromDefault(a);"/"===a.charAt(0)&&(e=c.buildFromRegex(a,b));return e},getFromObjectValues:function(a,b){var e,g={};for(e in a)a.hasOwnProperty(e)&&(g[e]=c.getFromKey(a[e],b));return g},getFromObjectKeys:function(a,b){var e,g={};for(e in a)a.hasOwnProperty(e)&&(g[c.getFromKey(e,b)]=
a[e]);return g},getFromArray:function(a,b){for(var e=[],g=0;g<a.length;g++)g in a&&(e[g]=c.getFromKey(a[g],b));return e},buildFromDefault:function(a){var b,e,g;switch(a){case "name":b="en-US";break;case "englishName":b="English (United States)";break;case "nativeName":b="English (United States)";break;case "twoDigitYearMax":b=2049;break;case "firstDayOfWeek":b=0;break;default:if(b=a,g=a.split("_"),e=g.length,1<e&&"/"!==a.charAt(0)&&(a=g[e-1].toLowerCase(),"initial"===a||"abbr"===a))b=g[0]}return b},
buildFromRegex:function(a,b){return Date.CultureStrings&&Date.CultureStrings[b]&&Date.CultureStrings[b][a]?new RegExp(Date.CultureStrings[b][a],"i"):new RegExp(a.replace(RegExp("/","g"),""),"i")}},a=function(a,b){var e=b?b:f;d[a]=a;return"object"===typeof a?a instanceof Array?c.getFromArray(a,e):c.getFromObjectKeys(a,e):c.getFromKey(a,e)},b=function(a){a=Date.Config.i18n+a+".js";var b=document.getElementsByTagName("head")[0]||document.documentElement,e=document.createElement("script");e.src=a;var g=
{done:function(){}};e.onload=e.onreadystatechange=function(){this.readyState&&"loaded"!==this.readyState&&"complete"!==this.readyState||(g.done(),b.removeChild(e))};setTimeout(function(){b.insertBefore(e,b.firstChild)},0);return{done:function(a){g.done=function(){a&&setTimeout(a,0)}}}},e={buildFromMethodHash:function(a){for(var b in a)a.hasOwnProperty(b)&&(a[b]=e[a[b]]());return a},timeZoneDST:function(){return a({CHADT:"+1345",NZDT:"+1300",AEDT:"+1100",ACDT:"+1030",AZST:"+0500",IRDT:"+0430",EEST:"+0300",
CEST:"+0200",BST:"+0100",PMDT:"-0200",ADT:"-0300",NDT:"-0230",EDT:"-0400",CDT:"-0500",MDT:"-0600",PDT:"-0700",AKDT:"-0800",HADT:"-0900"})},timeZoneStandard:function(){return a({LINT:"+1400",TOT:"+1300",CHAST:"+1245",NZST:"+1200",NFT:"+1130",SBT:"+1100",AEST:"+1000",ACST:"+0930",JST:"+0900",CWST:"+0845",CT:"+0800",ICT:"+0700",MMT:"+0630",BST:"+0600",NPT:"+0545",IST:"+0530",PKT:"+0500",AFT:"+0430",MSK:"+0400",IRST:"+0330",FET:"+0300",EET:"+0200",CET:"+0100",GMT:"+0000",UTC:"+0000",CVT:"-0100",GST:"-0200",
BRT:"-0300",NST:"-0330",AST:"-0400",EST:"-0500",CST:"-0600",MST:"-0700",PST:"-0800",AKST:"-0900",MIT:"-0930",HST:"-1000",SST:"-1100",BIT:"-1200"})},timeZones:function(a){var b;a.timezones=[];for(b in a.abbreviatedTimeZoneStandard)a.abbreviatedTimeZoneStandard.hasOwnProperty(b)&&a.timezones.push({name:b,offset:a.abbreviatedTimeZoneStandard[b]});for(b in a.abbreviatedTimeZoneDST)a.abbreviatedTimeZoneDST.hasOwnProperty(b)&&a.timezones.push({name:b,offset:a.abbreviatedTimeZoneDST[b],dst:!0});return a.timezones},
days:function(){return a("Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "))},dayAbbr:function(){return a("Sun Mon Tue Wed Thu Fri Sat".split(" "))},dayShortNames:function(){return a("Su Mo Tu We Th Fr Sa".split(" "))},dayFirstLetters:function(){return a("S_Sun_Initial M_Mon_Initial T_Tues_Initial W_Wed_Initial T_Thu_Initial F_Fri_Initial S_Sat_Initial".split(" "))},months:function(){return a("January February March April May June July August September October November December".split(" "))},
monthAbbr:function(){return a("Jan_Abbr Feb_Abbr Mar_Abbr Apr_Abbr May_Abbr Jun_Abbr Jul_Abbr Aug_Abbr Sep_Abbr Oct_Abbr Nov_Abbr Dec_Abbr".split(" "))},formatPatterns:function(){return c.getFromObjectValues({shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},
Date.i18n.currentLanguage())},regex:function(){return c.getFromObjectValues({inTheMorning:"/( in the )(morn(ing)?)\\b/",thisMorning:"/(this )(morn(ing)?)\\b/",amThisMorning:"/(\b\\d(am)? )(this )(morn(ing)?)/",inTheEvening:"/( in the )(even(ing)?)\\b/",thisEvening:"/(this )(even(ing)?)\\b/",pmThisEvening:"/(\b\\d(pm)? )(this )(even(ing)?)/",jan:"/jan(uary)?/",feb:"/feb(ruary)?/",mar:"/mar(ch)?/",apr:"/apr(il)?/",may:"/may/",jun:"/jun(e)?/",jul:"/jul(y)?/",aug:"/aug(ust)?/",sep:"/sep(t(ember)?)?/",
oct:"/oct(ober)?/",nov:"/nov(ember)?/",dec:"/dec(ember)?/",sun:"/^su(n(day)?)?/",mon:"/^mo(n(day)?)?/",tue:"/^tu(e(s(day)?)?)?/",wed:"/^we(d(nesday)?)?/",thu:"/^th(u(r(s(day)?)?)?)?/",fri:"/fr(i(day)?)?/",sat:"/^sa(t(urday)?)?/",future:"/^next/",past:"/^last|past|prev(ious)?/",add:"/^(\\+|aft(er)?|from|hence)/",subtract:"/^(\\-|bef(ore)?|ago)/",yesterday:"/^yes(terday)?/",today:"/^t(od(ay)?)?/",tomorrow:"/^tom(orrow)?/",now:"/^n(ow)?/",millisecond:"/^ms|milli(second)?s?/",second:"/^sec(ond)?s?/",
minute:"/^mn|min(ute)?s?/",hour:"/^h(our)?s?/",week:"/^w(eek)?s?/",month:"/^m(onth)?s?/",day:"/^d(ay)?s?/",year:"/^y(ear)?s?/",shortMeridian:"/^(a|p)/",longMeridian:"/^(a\\.?m?\\.?|p\\.?m?\\.?)/",timezone:"/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/",ordinalSuffix:"/^\\s*(st|nd|rd|th)/",timeContext:"/^\\s*(\\:|a(?!u|p)|p)/"},Date.i18n.currentLanguage())}},g=function(){var a=c.getFromObjectValues({name:"name",englishName:"englishName",nativeName:"nativeName",
amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:"firstDayOfWeek",twoDigitYearMax:"twoDigitYearMax",dateElementOrder:"mdy"},Date.i18n.currentLanguage()),b=e.buildFromMethodHash({dayNames:"days",abbreviatedDayNames:"dayAbbr",shortestDayNames:"dayShortNames",firstLetterDayNames:"dayFirstLetters",monthNames:"months",abbreviatedMonthNames:"monthAbbr",formatPatterns:"formatPatterns",regexPatterns:"regex",abbreviatedTimeZoneDST:"timeZoneDST",abbreviatedTimeZoneStandard:"timeZoneStandard"}),g;for(g in b)b.hasOwnProperty(g)&&
(a[g]=b[g]);e.timeZones(a);return a};h.i18n={__:function(m,b){return a(m,b)},currentLanguage:function(){return f||"en-US"},setLanguage:function(a,e,c){var d=!1;if(e||"en-US"===a||Date.CultureStrings&&Date.CultureStrings[a])f=a,Date.CultureStrings=Date.CultureStrings||{},Date.CultureStrings.lang=a,Date.CultureInfo=new g;else if(!Date.CultureStrings||!Date.CultureStrings[a])if("undefined"!==typeof exports&&this.exports!==exports)try{require("../i18n/"+a+".js"),f=a,Date.CultureStrings.lang=a,Date.CultureInfo=
new g}catch(p){throw Error("The DateJS IETF language tag '"+a+"' could not be loaded by Node. It likely does not exist.");}else if(Date.Config&&Date.Config.i18n)d=!0,b(a).done(function(){f=a;Date.CultureStrings=Date.CultureStrings||{};Date.CultureStrings.lang=a;Date.CultureInfo=new g;h.Parsing.Normalizer.buildReplaceData();h.Grammar&&h.Grammar.buildGrammarFormats();c&&setTimeout(c,0)});else return Date.console.error("The DateJS IETF language tag '"+a+"' is not available and has not been loaded."),
!1;h.Parsing.Normalizer.buildReplaceData();h.Grammar&&h.Grammar.buildGrammarFormats();!d&&c&&setTimeout(c,0)},getLoggedKeys:function(){return d},updateCultureInfo:function(){Date.CultureInfo=new g}};h.i18n.updateCultureInfo()})();
(function(){var h=Date,f=h.prototype,d=function(a,b){b||(b=2);return("000"+a).slice(-1*b)};h.console="undefined"!==typeof window&&"undefined"!==typeof window.console&&"undefined"!==typeof window.console.log?console:{log:function(){},error:function(){}};h.Config=h.Config||{};h.initOverloads=function(){h.now?h._now||(h._now=h.now):h._now=function(){return(new Date).getTime()};h.now=function(a){return a?h.present():h._now()};f.toISOString||(f.toISOString=function(){return this.getUTCFullYear()+"-"+d(this.getUTCMonth()+
1)+"-"+d(this.getUTCDate())+"T"+d(this.getUTCHours())+":"+d(this.getUTCMinutes())+":"+d(this.getUTCSeconds())+"."+String((this.getUTCMilliseconds()/1E3).toFixed(3)).slice(2,5)+"Z"});void 0===f._toString&&(f._toString=f.toString)};h.initOverloads();h.today=function(){return(new Date).clearTime()};h.present=function(){return new Date};h.compare=function(a,b){if(isNaN(a)||isNaN(b))throw Error(a+" - "+b);if(a instanceof Date&&b instanceof Date)return a<b?-1:a>b?1:0;throw new TypeError(a+" - "+b);};h.equals=
function(a,b){return 0===a.compareTo(b)};h.getDayName=function(a){return Date.CultureInfo.dayNames[a]};h.getDayNumberFromName=function(a){var b=Date.CultureInfo.dayNames,e=Date.CultureInfo.abbreviatedDayNames,g=Date.CultureInfo.shortestDayNames;a=a.toLowerCase();for(var m=0;m<b.length;m++)if(b[m].toLowerCase()===a||e[m].toLowerCase()===a||g[m].toLowerCase()===a)return m;return-1};h.getMonthNumberFromName=function(a){var b=Date.CultureInfo.monthNames,e=Date.CultureInfo.abbreviatedMonthNames;a=a.toLowerCase();
for(var g=0;g<b.length;g++)if(b[g].toLowerCase()===a||e[g].toLowerCase()===a)return g;return-1};h.getMonthName=function(a){return Date.CultureInfo.monthNames[a]};h.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};h.getDaysInMonth=function(a,b){!b&&h.validateMonth(a)&&(b=a,a=Date.today().getFullYear());return[31,h.isLeapYear(a)?29:28,31,30,31,30,31,31,30,31,30,31][b]};f.getDaysInMonth=function(){return h.getDaysInMonth(this.getFullYear(),this.getMonth())};h.getTimezoneAbbreviation=function(a,
b){var e,g=b?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard;for(e in g)if(g.hasOwnProperty(e)&&g[e]===a)return e;return null};h.getTimezoneOffset=function(a,b){var e,g=[],m=Date.CultureInfo.timezones;a||(a=(new Date).getTimezone());for(e=0;e<m.length;e++)m[e].name===a.toUpperCase()&&g.push(e);if(!m[g[0]])return null;if(1!==g.length&&b)for(e=0;e<g.length;e++){if(m[g[e]].dst)return m[g[e]].offset}else return m[g[0]].offset};h.getQuarter=function(a){a=a||new Date;
return[1,2,3,4][Math.floor(a.getMonth()/3)]};h.getDaysLeftInQuarter=function(a){a=a||new Date;var b=new Date(a);b.setMonth(b.getMonth()+3-b.getMonth()%3,0);return Math.floor((b-a)/864E5)};var c=function(a,b,e,g){if("undefined"===typeof a)return!1;if("number"!==typeof a)throw new TypeError(a+" is not a Number.");return a<b||a>e?!1:!0};h.validateMillisecond=function(a){return c(a,0,999,"millisecond")};h.validateSecond=function(a){return c(a,0,59,"second")};h.validateMinute=function(a){return c(a,0,
59,"minute")};h.validateHour=function(a){return c(a,0,23,"hour")};h.validateDay=function(a,b,e){return void 0===b||null===b||void 0===e||null===e?!1:c(a,1,h.getDaysInMonth(b,e),"day")};h.validateWeek=function(a){return c(a,0,53,"week")};h.validateMonth=function(a){return c(a,0,11,"month")};h.validateYear=function(a){return c(a,-271822,275760,"year")};h.validateTimezone=function(a){return 1==={ACDT:1,ACST:1,ACT:1,ADT:1,AEDT:1,AEST:1,AFT:1,AKDT:1,AKST:1,AMST:1,AMT:1,ART:1,AST:1,AWDT:1,AWST:1,AZOST:1,
AZT:1,BDT:1,BIOT:1,BIT:1,BOT:1,BRT:1,BST:1,BTT:1,CAT:1,CCT:1,CDT:1,CEDT:1,CEST:1,CET:1,CHADT:1,CHAST:1,CHOT:1,ChST:1,CHUT:1,CIST:1,CIT:1,CKT:1,CLST:1,CLT:1,COST:1,COT:1,CST:1,CT:1,CVT:1,CWST:1,CXT:1,DAVT:1,DDUT:1,DFT:1,EASST:1,EAST:1,EAT:1,ECT:1,EDT:1,EEDT:1,EEST:1,EET:1,EGST:1,EGT:1,EIT:1,EST:1,FET:1,FJT:1,FKST:1,FKT:1,FNT:1,GALT:1,GAMT:1,GET:1,GFT:1,GILT:1,GIT:1,GMT:1,GST:1,GYT:1,HADT:1,HAEC:1,HAST:1,HKT:1,HMT:1,HOVT:1,HST:1,ICT:1,IDT:1,IOT:1,IRDT:1,IRKT:1,IRST:1,IST:1,JST:1,KGT:1,KOST:1,KRAT:1,
KST:1,LHST:1,LINT:1,MAGT:1,MART:1,MAWT:1,MDT:1,MET:1,MEST:1,MHT:1,MIST:1,MIT:1,MMT:1,MSK:1,MST:1,MUT:1,MVT:1,MYT:1,NCT:1,NDT:1,NFT:1,NPT:1,NST:1,NT:1,NUT:1,NZDT:1,NZST:1,OMST:1,ORAT:1,PDT:1,PET:1,PETT:1,PGT:1,PHOT:1,PHT:1,PKT:1,PMDT:1,PMST:1,PONT:1,PST:1,PYST:1,PYT:1,RET:1,ROTT:1,SAKT:1,SAMT:1,SAST:1,SBT:1,SCT:1,SGT:1,SLST:1,SRT:1,SST:1,SYOT:1,TAHT:1,THA:1,TFT:1,TJT:1,TKT:1,TLT:1,TMT:1,TOT:1,TVT:1,UCT:1,ULAT:1,UTC:1,UYST:1,UYT:1,UZT:1,VET:1,VLAT:1,VOLT:1,VOST:1,VUT:1,WAKT:1,WAST:1,WAT:1,WEDT:1,WEST:1,
WET:1,WST:1,YAKT:1,YEKT:1,Z:1}[a]};h.validateTimezoneOffset=function(a){return-841<a&&721>a}})();
(function(){var h=Date,f=h.prototype,d=function(a,b){b||(b=2);return("000"+a).slice(-1*b)},c=function(a){var b={},e=this,g,c;c=function(b,g,c){if("day"===b){b=void 0!==a.month?a.month:e.getMonth();var d=void 0!==a.year?a.year:e.getFullYear();return h[g](c,d,b)}return h[g](c)};for(g in a)if(hasOwnProperty.call(a,g)){var d="validate"+g.charAt(0).toUpperCase()+g.slice(1);h[d]&&null!==a[g]&&c(g,d,a[g])&&(b[g]=a[g])}return b};f.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);
this.setMilliseconds(0);return this};f.setTimeToNow=function(){var a=new Date;this.setHours(a.getHours());this.setMinutes(a.getMinutes());this.setSeconds(a.getSeconds());this.setMilliseconds(a.getMilliseconds());return this};f.clone=function(){return new Date(this.getTime())};f.compareTo=function(a){return Date.compare(this,a)};f.equals=function(a){return Date.equals(this,void 0!==a?a:new Date)};f.between=function(a,b){return this.getTime()>=a.getTime()&&this.getTime()<=b.getTime()};f.isAfter=function(a){return 1===
this.compareTo(a||new Date)};f.isBefore=function(a){return-1===this.compareTo(a||new Date)};f.isToday=f.isSameDay=function(a){return this.clone().clearTime().equals((a||new Date).clone().clearTime())};f.addMilliseconds=function(a){if(!a)return this;this.setTime(this.getTime()+1*a);return this};f.addSeconds=function(a){return a?this.addMilliseconds(1E3*a):this};f.addMinutes=function(a){return a?this.addMilliseconds(6E4*a):this};f.addHours=function(a){return a?this.addMilliseconds(36E5*a):this};f.addDays=
function(a){if(!a)return this;this.setDate(this.getDate()+1*a);return this};f.addWeekdays=function(a){if(!a)return this;var b=this.getDay(),e=Math.ceil(Math.abs(a)/7);(0===b||6===b)&&0<a&&(this.next().monday(),this.addDays(-1),b=this.getDay());if(0>a){for(;0>a;)this.addDays(-1),b=this.getDay(),0!==b&&6!==b&&a++;return this}if(5<a||6-b<=a)a+=2*e;return this.addDays(a)};f.addWeeks=function(a){return a?this.addDays(7*a):this};f.addMonths=function(a){if(!a)return this;var b=this.getDate();this.setDate(1);
this.setMonth(this.getMonth()+1*a);this.setDate(Math.min(b,h.getDaysInMonth(this.getFullYear(),this.getMonth())));return this};f.addQuarters=function(a){return a?this.addMonths(3*a):this};f.addYears=function(a){return a?this.addMonths(12*a):this};f.add=function(a){if("number"===typeof a)return this._orient=a,this;a.day&&0!==a.day-this.getDate()&&this.setDate(a.day);a.milliseconds&&this.addMilliseconds(a.milliseconds);a.seconds&&this.addSeconds(a.seconds);a.minutes&&this.addMinutes(a.minutes);a.hours&&
this.addHours(a.hours);a.weeks&&this.addWeeks(a.weeks);a.months&&this.addMonths(a.months);a.years&&this.addYears(a.years);a.days&&this.addDays(a.days);return this};f.getWeek=function(a){var b=new Date(this.valueOf());a?(b.addMinutes(b.getTimezoneOffset()),a=b.clone()):a=this;a=(a.getDay()+6)%7;b.setDate(b.getDate()-a+3);a=b.valueOf();b.setMonth(0,1);4!==b.getDay()&&b.setMonth(0,1+(4-b.getDay()+7)%7);return 1+Math.ceil((a-b)/6048E5)};f.getISOWeek=function(){return d(this.getWeek(!0))};f.setWeek=function(a){return 0===
a-this.getWeek()?1!==this.getDay()?this.moveToDayOfWeek(1,1<this.getDay()?-1:1):this:this.moveToDayOfWeek(1,1<this.getDay()?-1:1).addWeeks(a-this.getWeek())};f.setQuarter=function(a){a=Math.abs(3*(a-1)+1);return this.setMonth(a,1)};f.getQuarter=function(){return Date.getQuarter(this)};f.getDaysLeftInQuarter=function(){return Date.getDaysLeftInQuarter(this)};f.moveToNthOccurrence=function(a,b){if("Weekday"===a){if(0<b)this.moveToFirstDayOfMonth(),this.is().weekday()&&--b;else if(0>b)this.moveToLastDayOfMonth(),
this.is().weekday()&&(b+=1);else return this;return this.addWeekdays(b)}var e=0;if(0<b)e=b-1;else if(-1===b)return this.moveToLastDayOfMonth(),this.getDay()!==a&&this.moveToDayOfWeek(a,-1),this;return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(a,1).addWeeks(e)};var a=function(a,b,e){return function(g,c){var d=(g-this[a]()+e*(c||1))%e;return this[b](0===d?d+e*(c||1):d)}};f.moveToDayOfWeek=a("getDay","addDays",7);f.moveToMonth=a("getMonth","addMonths",12);f.getOrdinate=function(){var a=
this.getDate();return b(a)};f.getOrdinalNumber=function(){return Math.ceil((this.clone().clearTime()-new Date(this.getFullYear(),0,1))/864E5)+1};f.getTimezone=function(){return h.getTimezoneAbbreviation(this.getUTCOffset(),this.isDaylightSavingTime())};f.setTimezoneOffset=function(a){var b=this.getTimezoneOffset();return(a=-6*Number(a)/10)||0===a?this.addMinutes(a-b):this};f.setTimezone=function(a){return this.setTimezoneOffset(h.getTimezoneOffset(a))};f.hasDaylightSavingTime=function(){return Date.today().set({month:0,
day:1}).getTimezoneOffset()!==Date.today().set({month:6,day:1}).getTimezoneOffset()};f.isDaylightSavingTime=function(){return Date.today().set({month:0,day:1}).getTimezoneOffset()!==this.getTimezoneOffset()};f.getUTCOffset=function(a){a=-10*(a||this.getTimezoneOffset())/6;if(0>a)return a=(a-1E4).toString(),a.charAt(0)+a.substr(2);a=(a+1E4).toString();return"+"+a.substr(1)};f.getElapsed=function(a){return(a||new Date)-this};f.set=function(a){a=c.call(this,a);for(var b in a)if(hasOwnProperty.call(a,
b)){var e=b.charAt(0).toUpperCase()+b.slice(1),g,d;"week"!==b&&"month"!==b&&"timezone"!==b&&"timezoneOffset"!==b&&(e+="s");g="add"+e;d="get"+e;"month"===b?g+="s":"year"===b&&(d="getFullYear");if("day"!==b&&"timezone"!==b&&"timezoneOffset"!==b&&"week"!==b&&"hour"!==b)this[g](a[b]-this[d]());else if("timezone"===b||"timezoneOffset"===b||"week"===b||"hour"===b)this["set"+e](a[b])}a.day&&this.addDays(a.day-this.getDate());return this};f.moveToFirstDayOfMonth=function(){return this.set({day:1})};f.moveToLastDayOfMonth=
function(){return this.set({day:h.getDaysInMonth(this.getFullYear(),this.getMonth())})};var b=function(a){switch(1*a){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},e=function(a){var b=Date.CultureInfo.formatPatterns;switch(a){case "d":return this.toString(b.shortDate);case "D":return this.toString(b.longDate);case "F":return this.toString(b.fullDateTime);case "m":return this.toString(b.monthDay);case "r":case "R":return a=this.clone().addMinutes(this.getTimezoneOffset()),
a.toString(b.rfc1123)+" GMT";case "s":return this.toString(b.sortableDateTime);case "t":return this.toString(b.shortTime);case "T":return this.toString(b.longTime);case "u":return a=this.clone().addMinutes(this.getTimezoneOffset()),a.toString(b.universalSortableDateTime);case "y":return this.toString(b.yearMonth);default:return!1}},g=function(a){return function(e){if("\\"===e.charAt(0))return e.replace("\\","");switch(e){case "hh":return d(13>a.getHours()?0===a.getHours()?12:a.getHours():a.getHours()-
12);case "h":return 13>a.getHours()?0===a.getHours()?12:a.getHours():a.getHours()-12;case "HH":return d(a.getHours());case "H":return a.getHours();case "mm":return d(a.getMinutes());case "m":return a.getMinutes();case "ss":return d(a.getSeconds());case "s":return a.getSeconds();case "yyyy":return d(a.getFullYear(),4);case "yy":return d(a.getFullYear());case "y":return a.getFullYear();case "E":case "dddd":return Date.CultureInfo.dayNames[a.getDay()];case "ddd":return Date.CultureInfo.abbreviatedDayNames[a.getDay()];
case "dd":return d(a.getDate());case "d":return a.getDate();case "MMMM":return Date.CultureInfo.monthNames[a.getMonth()];case "MMM":return Date.CultureInfo.abbreviatedMonthNames[a.getMonth()];case "MM":return d(a.getMonth()+1);case "M":return a.getMonth()+1;case "t":return 12>a.getHours()?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case "tt":return 12>a.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case "S":return b(a.getDate());
case "W":return a.getWeek();case "WW":return a.getISOWeek();case "Q":return"Q"+a.getQuarter();case "q":return String(a.getQuarter());case "z":return a.getTimezone();case "Z":case "X":return Date.getTimezoneOffset(a.getTimezone());case "ZZ":return-60*a.getTimezoneOffset();case "u":return a.getDay();case "L":return h.isLeapYear(a.getFullYear())?1:0;case "B":return"@"+(a.getUTCSeconds()+60*a.getUTCMinutes()+3600*(a.getUTCHours()+1))/86.4;default:return e}}};f.toString=function(a,b){if(!b&&a&&1===a.length&&
(output=e.call(this,a)))return output;var c=g(this);return a?a.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g,c).replace(/\[|\]/g,""):this._toString()}})();
(function(){var h=Date,f=h.prototype,d=Number.prototype;f._orient=1;f._nth=null;f._is=!1;f._same=!1;f._isSecond=!1;d._dateElement="days";f.next=function(){this._move=!0;this._orient=1;return this};h.next=function(){return h.today().next()};f.last=f.prev=f.previous=function(){this._move=!0;this._orient=-1;return this};h.last=h.prev=h.previous=function(){return h.today().last()};f.is=function(){this._is=!0;return this};f.same=function(){this._same=!0;this._isSecond=!1;return this};f.today=function(){return this.same().day()};
f.weekday=function(){return this._nth?m("Weekday").call(this):this._move?this.addWeekdays(this._orient):this._is?(this._is=!1,!this.is().sat()&&!this.is().sun()):!1};f.weekend=function(){return this._is?(this._is=!1,this.is().sat()||this.is().sun()):!1};f.at=function(a){return"string"===typeof a?h.parse(this.toString("d")+" "+a):this.set(a)};d.fromNow=d.after=function(a){var b={};b[this._dateElement]=this;return(a?a.clone():new Date).add(b)};d.ago=d.before=function(a){var b={};b["s"!==this._dateElement[this._dateElement.length-
1]?this._dateElement+"s":this._dateElement]=-1*this;return(a?a.clone():new Date).add(b)};var c="sunday monday tuesday wednesday thursday friday saturday".split(/\s/),a="january february march april may june july august september october november december".split(/\s/),b="Millisecond Second Minute Hour Day Week Month Year Quarter Weekday".split(/\s/),e="Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter".split(/\s/),g="final first second third fourth fifth".split(/\s/);f.toObject=function(){for(var a=
{},g=0;g<b.length;g++)this["get"+e[g]]&&(a[b[g].toLowerCase()]=this["get"+e[g]]());return a};h.fromObject=function(a){a.week=null;return Date.today().set(a)};var m=function(a){return function(){if(this._is)return this._is=!1,this.getDay()===a;this._move&&(this._move=null);if(null!==this._nth){this._isSecond&&this.addSeconds(-1*this._orient);this._isSecond=!1;var b=this._nth;this._nth=null;var e=this.clone().moveToLastDayOfMonth();this.moveToNthOccurrence(a,b);if(this>e)throw new RangeError(h.getDayName(a)+
" does not occur "+b+" times in the month of "+h.getMonthName(e.getMonth())+" "+e.getFullYear()+".");return this}return this.moveToDayOfWeek(a,this._orient)}},k=function(a,b,e){for(var g=0;g<a.length;g++)h[a[g].toUpperCase()]=h[a[g].toUpperCase().substring(0,3)]=g,h[a[g]]=h[a[g].substring(0,3)]=b(g),f[a[g]]=f[a[g].substring(0,3)]=e(g)};k(c,function(a){return function(){var b=h.today(),e=a-b.getDay();0===a&&1===Date.CultureInfo.firstDayOfWeek&&0!==b.getDay()&&(e+=7);return b.addDays(e)}},m);k(a,function(a){return function(){return h.today().set({month:a,
day:1})}},function(a){return function(){return this._is?(this._is=!1,this.getMonth()===a):this.moveToMonth(a,this._orient)}});for(var a=function(a){return function(e){if(this._isSecond)return this._isSecond=!1,this;if(this._same){this._same=this._is=!1;var g=this.toObject();e=(e||new Date).toObject();for(var c="",d=a.toLowerCase(),d="s"===d[d.length-1]?d.substring(0,d.length-1):d,f=b.length-1;-1<f;f--){c=b[f].toLowerCase();if(g[c]!==e[c])return!1;if(d===c)break}return!0}"s"!==a.substring(a.length-
1)&&(a+="s");this._move&&(this._move=null);return this["add"+a](this._orient)}},k=function(a){return function(){this._dateElement=a;return this}},n=0;n<b.length;n++)c=b[n].toLowerCase(),"weekday"!==c&&(f[c]=f[c+"s"]=a(b[n]),d[c]=d[c+"s"]=k(c+"s"));f._ss=a("Second");d=function(a){return function(b){if(this._same)return this._ss(b);if(b||0===b)return this.moveToNthOccurrence(b,a);this._nth=a;return 2!==a||void 0!==b&&null!==b?this:(this._isSecond=!0,this.addSeconds(this._orient))}};for(c=0;c<g.length;c++)f[g[c]]=
0===c?d(-1):d(c)})();
(function(){Date.Parsing={Exception:function(a){this.message="Parse error at '"+a.substring(0,10)+" ...'"}};var h=Date.Parsing,f=[0,31,59,90,120,151,181,212,243,273,304,334],d=[0,31,60,91,121,152,182,213,244,274,305,335];h.isLeapYear=function(a){return 0===a%4&&0!==a%100||0===a%400};var c={multiReplace:function(a,b){for(var e in b)if(Object.prototype.hasOwnProperty.call(b,e)){var g;"function"!==typeof b[e]&&(g=b[e]instanceof RegExp?b[e]:new RegExp(b[e],"g"));a=a.replace(g,e)}return a},getDayOfYearFromWeek:function(a){var b;
a.weekDay=a.weekDay||0===a.weekDay?a.weekDay:1;b=new Date(a.year,0,4);b=(0===b.getDay()?7:b.getDay())+3;a.dayOfYear=7*a.week+(0===a.weekDay?7:a.weekDay)-b;return a},getDayOfYear:function(a,b){a.dayOfYear||(a=c.getDayOfYearFromWeek(a));for(var e=0;e<=b.length;e++)if(a.dayOfYear<b[e]||e===b.length){a.day=a.day?a.day:a.dayOfYear-b[e-1];break}else a.month=e;return a},adjustForTimeZone:function(a,b){var e;"Z"===a.zone.toUpperCase()||0===a.zone_hours&&0===a.zone_minutes?e=-b.getTimezoneOffset():(e=60*a.zone_hours+
(a.zone_minutes||0),"+"===a.zone_sign&&(e*=-1),e-=b.getTimezoneOffset());b.setMinutes(b.getMinutes()+e);return b},setDefaults:function(a){a.year=a.year||Date.today().getFullYear();a.hours=a.hours||0;a.minutes=a.minutes||0;a.seconds=a.seconds||0;a.milliseconds=a.milliseconds||0;if(a.month||!a.week&&!a.dayOfYear)a.month=a.month||0,a.day=a.day||1;return a},dataNum:function(a,b,e,g){var c=1*a;return b?g?a?1*b(a):a:a?b(c):a:e?a&&"undefined"!==typeof a?c:a:a?c:a},timeDataProcess:function(a){var b={},e;
for(e in a.data)a.data.hasOwnProperty(e)&&(b[e]=a.ignore[e]?a.data[e]:c.dataNum(a.data[e],a.mods[e],a.explict[e],a.postProcess[e]));a.data.secmins&&(a.data.secmins=60*a.data.secmins.replace(",","."),b.minutes?b.seconds||(b.seconds=a.data.secmins):b.minutes=a.data.secmins,delete a.secmins);return b},buildTimeObjectFromData:function(a){return c.timeDataProcess({data:{year:a[1],month:a[5],day:a[7],week:a[8],dayOfYear:a[10],hours:a[15],zone_hours:a[23],zone_minutes:a[24],zone:a[21],zone_sign:a[22],weekDay:a[9],
minutes:a[16],seconds:a[19],milliseconds:a[20],secmins:a[18]},mods:{month:function(a){return a-1},weekDay:function(a){a=Math.abs(a);return 7===a?0:a},minutes:function(a){return a.replace(":","")},seconds:function(a){return Math.floor(1*a.replace(":","").replace(",","."))},milliseconds:function(a){return 1E3*a.replace(",",".")}},postProcess:{minutes:!0,seconds:!0,milliseconds:!0},explict:{zone_hours:!0,zone_minutes:!0},ignore:{zone:!0,zone_sign:!0,secmins:!0}})},addToHash:function(a,b,e){for(var g=
b.length,c=0;c<g;c++)a[b[c]]=e[c];return a},combineRegex:function(a,b){return new RegExp("(("+a.source+")\\s("+b.source+"))")},getDateNthString:function(a,b,e){if(a)return Date.today().addDays(e).toString("d");if(b)return Date.today().last()[e]().toString("d")},buildRegexData:function(a){for(var b=[],e=a.length,g=0;g<e;g++)"[object Array]"===Object.prototype.toString.call(a[g])?b.push(this.combineRegex(a[g][0],a[g][1])):b.push(a[g]);return b}};h.processTimeObject=function(a){var b;c.setDefaults(a);
b=h.isLeapYear(a.year)?d:f;a.month||!a.week&&!a.dayOfYear?a.dayOfYear=b[a.month]+a.day:c.getDayOfYear(a,b);b=new Date(a.year,a.month,a.day,a.hours,a.minutes,a.seconds,a.milliseconds);a.zone&&c.adjustForTimeZone(a,b);return b};h.ISO={regex:/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,
parse:function(a){a=a.match(this.regex);if(!a||!a.length)return null;a=c.buildTimeObjectFromData(a);return a.year&&(a.year||a.month||a.day||a.week||a.dayOfYear)?h.processTimeObject(a):null}};h.Numeric={isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},regex:/\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i,parse:function(a){var b,e={},g=Date.CultureInfo.dateElementOrder.split("");if(!this.isNumeric(a)||"+"===a[0]&&"-"===a[0])return null;if(5>a.length&&0>a.indexOf(".")&&0>a.indexOf("/"))return e.year=
a,h.processTimeObject(e);a=a.match(this.regex);if(!a||!a.length)return null;for(b=0;b<g.length;b++)switch(g[b]){case "d":e.day=a[b+1];break;case "m":e.month=a[b+1]-1;break;case "y":e.year=a[b+1]}return h.processTimeObject(e)}};h.Normalizer={regexData:function(){var a=Date.CultureInfo.regexPatterns;return c.buildRegexData([a.tomorrow,a.yesterday,[a.past,a.mon],[a.past,a.tue],[a.past,a.wed],[a.past,a.thu],[a.past,a.fri],[a.past,a.sat],[a.past,a.sun]])},basicReplaceHash:function(){var a=Date.CultureInfo.regexPatterns;
return{January:a.jan.source,February:a.feb,March:a.mar,April:a.apr,May:a.may,June:a.jun,July:a.jul,August:a.aug,September:a.sep,October:a.oct,November:a.nov,December:a.dec,"":/\bat\b/gi," ":/\s{2,}/,am:a.inTheMorning,"9am":a.thisMorning,pm:a.inTheEvening,"7pm":a.thisEvening}},keys:function(){return[c.getDateNthString(!0,!1,1),c.getDateNthString(!0,!1,-1),c.getDateNthString(!1,!0,"monday"),c.getDateNthString(!1,!0,"tuesday"),c.getDateNthString(!1,!0,"wednesday"),c.getDateNthString(!1,!0,"thursday"),
c.getDateNthString(!1,!0,"friday"),c.getDateNthString(!1,!0,"saturday"),c.getDateNthString(!1,!0,"sunday")]},buildRegexFunctions:function(){var a=Date.CultureInfo.regexPatterns,b=Date.i18n.__,b=new RegExp("(\\b\\d\\d?("+b("AM")+"|"+b("PM")+")? )("+a.tomorrow.source.slice(1)+")","i");this.replaceFuncs=[[new RegExp(a.today.source+"(?!\\s*([+-]))\\b"),function(a){return 1<a.length?Date.today().toString("d"):a}],[b,function(a,b){return Date.today().addDays(1).toString("d")+" "+b}],[a.amThisMorning,function(a,
b){return b}],[a.pmThisEvening,function(a,b){return b}]]},buildReplaceData:function(){this.buildRegexFunctions();this.replaceHash=c.addToHash(this.basicReplaceHash(),this.keys(),this.regexData())},stringReplaceFuncs:function(a){for(var b=0;b<this.replaceFuncs.length;b++)a=a.replace(this.replaceFuncs[b][0],this.replaceFuncs[b][1]);return a},parse:function(a){a=this.stringReplaceFuncs(a);a=c.multiReplace(a,this.replaceHash);try{var b=a.split(/([\s\-\.\,\/\x27]+)/);3===b.length&&h.Numeric.isNumeric(b[0])&&
h.Numeric.isNumeric(b[2])&&4<=b[2].length&&"d"===Date.CultureInfo.dateElementOrder[0]&&(a="1/"+b[0]+"/"+b[2])}catch(e){}return a}};h.Normalizer.buildReplaceData()})();
(function(){for(var h=Date.Parsing,f=h.Operators={rtoken:function(a){return function(e){var g=e.match(a);if(g)return[g[0],e.substring(g[0].length)];throw new h.Exception(e);}},token:function(){return function(a){return f.rtoken(new RegExp("^\\s*"+a+"\\s*"))(a)}},stoken:function(a){return f.rtoken(new RegExp("^"+a))},until:function(a){return function(e){for(var g=[],c=null;e.length;){try{c=a.call(this,e)}catch(d){g.push(c[0]);e=c[1];continue}break}return[g,e]}},many:function(a){return function(e){for(var g=
[],c=null;e.length;){try{c=a.call(this,e)}catch(d){break}g.push(c[0]);e=c[1]}return[g,e]}},optional:function(a){return function(e){var g=null;try{g=a.call(this,e)}catch(c){return[null,e]}return[g[0],g[1]]}},not:function(a){return function(e){try{a.call(this,e)}catch(g){return[null,e]}throw new h.Exception(e);}},ignore:function(a){return a?function(e){var g=null,g=a.call(this,e);return[null,g[1]]}:null},product:function(){for(var a=arguments[0],e=Array.prototype.slice.call(arguments,1),g=[],c=0;c<
a.length;c++)g.push(f.each(a[c],e));return g},cache:function(a){var e={},g=0,c=[],d=Date.Config.CACHE_MAX||1E5,f=null;return function(l){if(g===d)for(var p=0;10>p;p++){var q=c.shift();q&&(delete e[q],g--)}try{f=e[l]=e[l]||a.call(this,l)}catch(s){f=e[l]=s}g++;c.push(l);if(f instanceof h.Exception)throw f;return f}},any:function(){var a=arguments;return function(e){for(var g=null,c=0;c<a.length;c++)if(null!=a[c]){try{g=a[c].call(this,e)}catch(d){g=null}if(g)return g}throw new h.Exception(e);}},each:function(){var a=
arguments;return function(e){for(var c=[],d=null,f=0;f<a.length;f++)if(null!=a[f]){try{d=a[f].call(this,e)}catch(n){throw new h.Exception(e);}c.push(d[0]);e=d[1]}return[c,e]}},all:function(){var a=a;return a.each(a.optional(arguments))},sequence:function(a,e,c){e=e||f.rtoken(/^\s*/);c=c||null;return 1===a.length?a[0]:function(d){for(var f=null,n=null,l=[],p=0;p<a.length;p++){try{f=a[p].call(this,d)}catch(q){break}l.push(f[0]);try{n=e.call(this,f[1])}catch(s){n=null;break}d=n[1]}if(!f)throw new h.Exception(d);
if(n)throw new h.Exception(n[1]);if(c)try{f=c.call(this,f[1])}catch(u){throw new h.Exception(f[1]);}return[l,f?f[1]:d]}},between:function(a,e,c){c=c||a;var d=f.each(f.ignore(a),e,f.ignore(c));return function(a){a=d.call(this,a);return[[a[0][0],r[0][2]],a[1]]}},list:function(a,e,c){e=e||f.rtoken(/^\s*/);c=c||null;return a instanceof Array?f.each(f.product(a.slice(0,-1),f.ignore(e)),a.slice(-1),f.ignore(c)):f.each(f.many(f.each(a,f.ignore(e))),px,f.ignore(c))},set:function(a,e,c){e=e||f.rtoken(/^\s*/);
c=c||null;return function(d){for(var k=null,n=k=null,l=null,p=[[],d],q=!1,s=0;s<a.length;s++){k=n=null;q=1===a.length;try{k=a[s].call(this,d)}catch(u){continue}l=[[k[0]],k[1]];if(0<k[1].length&&!q)try{n=e.call(this,k[1])}catch(v){q=!0}else q=!0;q||0!==n[1].length||(q=!0);if(!q){k=[];for(q=0;q<a.length;q++)s!==q&&k.push(a[q]);k=f.set(k,e).call(this,n[1]);0<k[0].length&&(l[0]=l[0].concat(k[0]),l[1]=k[1])}l[1].length<p[1].length&&(p=l);if(0===p[1].length)break}if(0===p[0].length)return p;if(c){try{n=
c.call(this,p[1])}catch(w){throw new h.Exception(p[1]);}p[1]=n[1]}return p}},forward:function(a,e){return function(c){return a[e].call(this,c)}},replace:function(a,e){return function(c){c=a.call(this,c);return[e,c[1]]}},process:function(a,e){return function(c){c=a.call(this,c);return[e.call(this,c[0]),c[1]]}},min:function(a,e){return function(c){var d=e.call(this,c);if(d[0].length<a)throw new h.Exception(c);return d}}},d=function(a){return function(){var e=null,c=[],d;1<arguments.length?e=Array.prototype.slice.call(arguments):
arguments[0]instanceof Array&&(e=arguments[0]);if(e){if(d=e.shift(),0<d.length)return e.unshift(d[void 0]),c.push(a.apply(null,e)),e.shift(),c}else return a.apply(null,arguments)}},c="optional not ignore cache".split(/\s/),a=0;a<c.length;a++)f[c[a]]=d(f[c[a]]);d=function(a){return function(){return arguments[0]instanceof Array?a.apply(null,arguments[0]):a.apply(null,arguments)}};c="each any all".split(/\s/);for(a=0;a<c.length;a++)f[c[a]]=d(f[c[a]])})();
(function(){var h=Date,f=function(c){for(var a=[],b=0;b<c.length;b++)c[b]instanceof Array?a=a.concat(f(c[b])):c[b]&&a.push(c[b]);return a},d=function(){if(this.meridian&&(this.hour||0===this.hour)){if("a"===this.meridian&&11<this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";if("p"===this.meridian&&12>this.hour&&Date.Config.strict24hr)throw"Invalid hour and meridian combination";"p"===this.meridian&&12>this.hour?this.hour+=12:"a"===this.meridian&&12===this.hour&&(this.hour=
0)}};h.Translator={hour:function(c){return function(){this.hour=Number(c)}},minute:function(c){return function(){this.minute=Number(c)}},second:function(c){return function(){this.second=Number(c)}},secondAndMillisecond:function(c){return function(){var a=c.match(/^([0-5][0-9])\.([0-9]{1,3})/);this.second=Number(a[1]);this.millisecond=Number(a[2])}},meridian:function(c){return function(){this.meridian=c.slice(0,1).toLowerCase()}},timezone:function(c){return function(){var a=c.replace(/[^\d\+\-]/g,
"");a.length?this.timezoneOffset=Number(a):this.timezone=c.toLowerCase()}},day:function(c){var a=c[0];return function(){this.day=Number(a.match(/\d+/)[0]);if(1>this.day)throw"invalid day";}},month:function(c){return function(){this.month=3===c.length?"jan feb mar apr may jun jul aug sep oct nov dec".indexOf(c)/4:Number(c)-1;if(0>this.month)throw"invalid month";}},year:function(c){return function(){var a=Number(c);this.year=2<c.length?a:a+(a+2E3<Date.CultureInfo.twoDigitYearMax?2E3:1900)}},rday:function(c){return function(){switch(c){case "yesterday":this.days=
-1;break;case "tomorrow":this.days=1;break;case "today":this.days=0;break;case "now":this.days=0,this.now=!0}}},finishExact:function(c){c=c instanceof Array?c:[c];for(var a=0;a<c.length;a++)c[a]&&c[a].call(this);c=new Date;!this.hour&&!this.minute||this.month||this.year||this.day||(this.day=c.getDate());this.year||(this.year=c.getFullYear());this.month||0===this.month||(this.month=c.getMonth());this.day||(this.day=1);this.hour||(this.hour=0);this.minute||(this.minute=0);this.second||(this.second=
0);this.millisecond||(this.millisecond=0);d.call(this);if(this.day>h.getDaysInMonth(this.year,this.month))throw new RangeError(this.day+" is not a valid value for days.");c=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);100>this.year&&c.setFullYear(this.year);this.timezone?c.set({timezone:this.timezone}):this.timezoneOffset&&c.set({timezoneOffset:this.timezoneOffset});return c},finish:function(c){var a,b,e;c=c instanceof Array?f(c):[c];if(0===c.length)return null;
for(a=0;a<c.length;a++)"function"===typeof c[a]&&c[a].call(this);if(!this.now||this.unit||this.operator)c=this.now||-1!=="hour minute second".indexOf(this.unit)?new Date:h.today();else return new Date;a=!!(this.days&&null!==this.days||this.orient||this.operator);b="past"===this.orient||"subtract"===this.operator?-1:1;this.month&&"week"===this.unit&&(this.value=this.month+1,delete this.month,delete this.day);!this.month&&0!==this.month||-1==="year day hour minute second".indexOf(this.unit)||(this.value||
(this.value=this.month+1),this.month=null,a=!0);a||!this.weekday||this.day||this.days||(e=Date[this.weekday](),this.day=e.getDate(),this.month||(this.month=e.getMonth()),this.year=e.getFullYear());if(a&&this.weekday&&"month"!==this.unit&&"week"!==this.unit){var g=c;e=b||1;this.unit="day";this.days=(g=h.getDayNumberFromName(this.weekday)-g.getDay())?(g+7*e)%7:7*e}!this.weekday||"week"===this.unit||this.day||this.days||(e=Date[this.weekday](),this.day=e.getDate(),e.getMonth()!==c.getMonth()&&(this.month=
e.getMonth()));this.month&&"day"===this.unit&&this.operator&&(this.value||(this.value=this.month+1),this.month=null);null!=this.value&&null!=this.month&&null!=this.year&&(this.day=1*this.value);this.month&&!this.day&&this.value&&(c.set({day:1*this.value}),a||(this.day=1*this.value));this.month||!this.value||"month"!==this.unit||this.now||(this.month=this.value,a=!0);a&&(this.month||0===this.month)&&"year"!==this.unit&&(e=b||1,this.unit="month",this.months=(g=this.month-c.getMonth())?(g+12*e)%12:12*
e,this.month=null);this.unit||(this.unit="day");if(!this.value&&this.operator&&null!==this.operator&&this[this.unit+"s"]&&null!==this[this.unit+"s"])this[this.unit+"s"]=this[this.unit+"s"]+("add"===this.operator?1:-1)+(this.value||0)*b;else if(null==this[this.unit+"s"]||null!=this.operator)this.value||(this.value=1),this[this.unit+"s"]=this.value*b;d.call(this);!this.month&&0!==this.month||this.day||(this.day=1);if(!this.orient&&!this.operator&&"week"===this.unit&&this.value&&!this.day&&!this.month)return Date.today().setWeek(this.value);
if("week"===this.unit&&this.weeks&&!this.day&&!this.month)return c=Date[void 0!==this.weekday?this.weekday:"today"]().addWeeks(this.weeks),this.now&&c.setTimeToNow(),c;a&&this.timezone&&this.day&&this.days&&(this.day=this.days);a?c.add(this):c.set(this);this.timezone&&(this.timezone=this.timezone.toUpperCase(),a=h.getTimezoneOffset(this.timezone),c.hasDaylightSavingTime()&&(b=h.getTimezoneAbbreviation(a,c.isDaylightSavingTime()),b!==this.timezone&&(c.isDaylightSavingTime()?c.addHours(-1):c.addHours(1))),
c.setTimezoneOffset(a));return c}}})();
(function(){var h=Date;h.Grammar={};var f=h.Parsing.Operators,d=h.Grammar,c=h.Translator,a;a=function(){return f.each(f.any.apply(null,arguments),f.not(d.ctoken2("timeContext")))};d.datePartDelimiter=f.rtoken(/^([\s\-\.\,\/\x27]+)/);d.timePartDelimiter=f.stoken(":");d.whiteSpace=f.rtoken(/^\s*/);d.generalDelimiter=f.rtoken(/^(([\s\,]|at|@|on)+)/);var b={};d.ctoken=function(a){var c=b[a];if(!c){for(var c=Date.CultureInfo.regexPatterns,e=a.split(/\s+/),d=[],g=0;g<e.length;g++)d.push(f.replace(f.rtoken(c[e[g]]),
e[g]));c=b[a]=f.any.apply(null,d)}return c};d.ctoken2=function(a){return f.rtoken(Date.CultureInfo.regexPatterns[a])};var e=function(a,b,c,e){d[a]=e?f.cache(f.process(f.each(f.rtoken(b),f.optional(d.ctoken2(e))),c)):f.cache(f.process(f.rtoken(b),c))},g=function(a,b){return f.cache(f.process(d.ctoken2(a),b))},m={},k=function(a){m[a]=m[a]||d.format(a)[0];return m[a]};d.allformats=function(a){var b=[];if(a instanceof Array)for(var c=0;c<a.length;c++)b.push(k(a[c]));else b.push(k(a));return b};d.formats=
function(a){if(a instanceof Array){for(var b=[],c=0;c<a.length;c++)b.push(k(a[c]));return f.any.apply(null,b)}return k(a)};var n={timeFormats:function(){var a,b="h hh H HH m mm s ss ss.s z zz".split(" "),h=[/^(0[0-9]|1[0-2]|[1-9])/,/^(0[0-9]|1[0-2])/,/^([0-1][0-9]|2[0-3]|[0-9])/,/^([0-1][0-9]|2[0-3])/,/^([0-5][0-9]|[0-9])/,/^[0-5][0-9]/,/^([0-5][0-9]|[0-9])/,/^[0-5][0-9]/,/^[0-5][0-9]\.[0-9]{1,3}/,/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/,/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/],m=[c.hour,
c.hour,c.hour,c.minute,c.minute,c.second,c.second,c.secondAndMillisecond,c.timezone,c.timezone,c.timezone];for(a=0;a<b.length;a++)e(b[a],h[a],m[a]);d.hms=f.cache(f.sequence([d.H,d.m,d.s],d.timePartDelimiter));d.t=g("shortMeridian",c.meridian);d.tt=g("longMeridian",c.meridian);d.zzz=g("timezone",c.timezone);d.timeSuffix=f.each(f.ignore(d.whiteSpace),f.set([d.tt,d.zzz]));d.time=f.each(f.optional(f.ignore(f.stoken("T"))),d.hms,d.timeSuffix)},dateFormats:function(){var b=function(){return f.set(arguments,
d.datePartDelimiter)},g,h="d dd M MM y yy yyy yyyy".split(" "),m=[/^([0-2]\d|3[0-1]|\d)/,/^([0-2]\d|3[0-1])/,/^(1[0-2]|0\d|\d)/,/^(1[0-2]|0\d)/,/^(\d+)/,/^(\d\d)/,/^(\d\d?\d?\d?)/,/^(\d\d\d\d)/],n=[c.day,c.day,c.month,c.month,c.year,c.year,c.year,c.year],k=["ordinalSuffix","ordinalSuffix"];for(g=0;g<h.length;g++)e(h[g],m[g],n[g],k[g]);d.MMM=d.MMMM=f.cache(f.process(d.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),c.month));d.ddd=d.dddd=f.cache(f.process(d.ctoken("sun mon tue wed thu fri sat"),
function(a){return function(){this.weekday=a}}));d.day=a(d.d,d.dd);d.month=a(d.M,d.MMM);d.year=a(d.yyyy,d.yy);d.mdy=b(d.ddd,d.month,d.day,d.year);d.ymd=b(d.ddd,d.year,d.month,d.day);d.dmy=b(d.ddd,d.day,d.month,d.year);d.date=function(a){return(d[Date.CultureInfo.dateElementOrder]||d.mdy).call(this,a)}},relative:function(){d.orientation=f.process(d.ctoken("past future"),function(a){return function(){this.orient=a}});d.operator=f.process(d.ctoken("add subtract"),function(a){return function(){this.operator=
a}});d.rday=f.process(d.ctoken("yesterday tomorrow today now"),c.rday);d.unit=f.process(d.ctoken("second minute hour day week month year"),function(a){return function(){this.unit=a}})}};d.buildGrammarFormats=function(){b={};n.timeFormats();n.dateFormats();n.relative();d.value=f.process(f.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/),function(a){return function(){this.value=a.replace(/\D/g,"")}});d.expression=f.set([d.rday,d.operator,d.value,d.unit,d.orientation,d.ddd,d.MMM]);d.format=f.process(f.many(f.any(f.process(f.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),
function(a){if(d[a])return d[a];throw h.Parsing.Exception(a);}),f.process(f.rtoken(/^[^dMyhHmstz]+/),function(a){return f.ignore(f.stoken(a))}))),function(a){return f.process(f.each.apply(null,a),c.finishExact)});d._start=f.process(f.set([d.date,d.time,d.expression],d.generalDelimiter,d.whiteSpace),c.finish)};d.buildGrammarFormats();d._formats=d.formats('"yyyy-MM-ddTHH:mm:ssZ";yyyy-MM-ddTHH:mm:ss.sz;yyyy-MM-ddTHH:mm:ssZ;yyyy-MM-ddTHH:mm:ssz;yyyy-MM-ddTHH:mm:ss;yyyy-MM-ddTHH:mmZ;yyyy-MM-ddTHH:mmz;yyyy-MM-ddTHH:mm;ddd, MMM dd, yyyy H:mm:ss tt;ddd MMM d yyyy HH:mm:ss zzz;MMddyyyy;ddMMyyyy;Mddyyyy;ddMyyyy;Mdyyyy;dMyyyy;yyyy;Mdyy;dMyy;d'.split(";"));
d.start=function(a){try{var b=d._formats.call({},a);if(0===b[1].length)return b}catch(c){}return d._start.call({},a)}})();
(function(){var h=Date,f={removeOrds:function(d){return d=(ords=d.match(/\b(\d+)(?:st|nd|rd|th)\b/))&&2===ords.length?d.replace(ords[0],ords[1]):d},grammarParser:function(d){var c=null;try{c=h.Grammar.start.call({},d.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"))}catch(a){return null}return 0===c[1].length?c[0]:null},nativeFallback:function(d){var c;try{return(c=Date._parse(d))||0===c?new Date(c):null}catch(a){return null}}};h._parse||(h._parse=h.parse);h.parse=function(d){var c;if(!d)return null;if(d instanceof
Date)return d.clone();4<=d.length&&"0"!==d.charAt(0)&&"+"!==d.charAt(0)&&"-"!==d.charAt(0)&&(c=h.Parsing.ISO.parse(d)||h.Parsing.Numeric.parse(d));if(c instanceof Date&&!isNaN(c.getTime()))return c;d=h.Parsing.Normalizer.parse(f.removeOrds(d));c=f.grammarParser(d);return null!==c?c:f.nativeFallback(d)};Date.getParseFunction=function(d){var c=Date.Grammar.allformats(d);return function(a){for(var b=null,e=0;e<c.length;e++){try{b=c[e].call({},a)}catch(d){continue}if(0===b[1].length)return b[0]}return null}};
h.parseExact=function(d,c){return h.getParseFunction(c)(d)}})();
(function(){var h=Date,f=h.prototype,d=function(a,b){b||(b=2);return("000"+a).slice(-1*b)},c={d:"dd","%d":"dd",D:"ddd","%a":"ddd",j:"dddd",l:"dddd","%A":"dddd",S:"S",F:"MMMM","%B":"MMMM",m:"MM","%m":"MM",M:"MMM","%b":"MMM","%h":"MMM",n:"M",Y:"yyyy","%Y":"yyyy",y:"yy","%y":"yy",g:"h","%I":"h",G:"H",h:"hh",H:"HH","%H":"HH",i:"mm","%M":"mm",s:"ss","%S":"ss","%r":"hh:mm tt","%R":"H:mm","%T":"H:mm:ss","%X":"t","%x":"d","%e":"d","%D":"MM/dd/yy","%n":"\\n","%t":"\\t",e:"z",T:"z","%z":"z","%Z":"z",Z:"ZZ",
N:"u",w:"u","%w":"u",W:"W","%V":"W"},a={substitutes:function(a){return c[a]},interpreted:function(a,b){var c;switch(a){case "%u":return b.getDay()+1;case "z":return b.getOrdinalNumber();case "%j":return d(b.getOrdinalNumber(),3);case "%U":c=b.clone().set({month:0,day:1}).addDays(-1).moveToDayOfWeek(0);var f=b.clone().addDays(1).moveToDayOfWeek(0,-1);return f<c?"00":d((f.getOrdinalNumber()-c.getOrdinalNumber())/7+1);case "%W":return d(b.getWeek());case "t":return h.getDaysInMonth(b.getFullYear(),b.getMonth());
case "o":case "%G":return b.setWeek(b.getISOWeek()).toString("yyyy");case "%g":return b._format("%G").slice(-2);case "a":case "%p":return t("tt").toLowerCase();case "A":return t("tt").toUpperCase();case "u":return d(b.getMilliseconds(),3);case "I":return b.isDaylightSavingTime()?1:0;case "O":return b.getUTCOffset();case "P":return c=b.getUTCOffset(),c.substring(0,c.length-2)+":"+c.substring(c.length-2);case "B":return c=new Date,Math.floor((3600*c.getHours()+60*c.getMinutes()+c.getSeconds()+60*(c.getTimezoneOffset()+
60))/86.4);case "c":return b.toISOString().replace(/\"/g,"");case "U":return h.strtotime("now");case "%c":return t("d")+" "+t("t");case "%C":return Math.floor(b.getFullYear()/100+1)}},shouldOverrideDefaults:function(a){switch(a){case "%e":return!0;default:return!1}},parse:function(b,c){var d,f=c||new Date;return(d=a.substitutes(b))?d:(d=a.interpreted(b,f))?d:b}};h.normalizeFormat=function(b,c){return b.replace(/(%|\\)?.|%%/g,function(b){return a.parse(b,c)})};h.strftime=function(a,b){return Date.parse(b)._format(a)};
h.strtotime=function(a){a=h.parse(a);return Math.round(h.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds())/1E3)};var b=function(b){return function(c){var d=!1;if("\\"===c.charAt(0)||"%%"===c.substring(0,2))return c.replace("\\","").replace("%%","%");d=a.shouldOverrideDefaults(c);if(c=h.normalizeFormat(c,b))return b.toString(c,d)}};f._format=function(a){var c=b(this);return a?a.replace(/(%|\\)?.|%%/g,c):this._toString()};
f.format||(f.format=f._format)})();
(function(){var h=function(c){return function(){return this[c]}},f=function(c){return function(a){this[c]=a;return this}},d=function(c,a,b,e,f){if(1===arguments.length&&"number"===typeof c){var h=0>c?-1:1,k=Math.abs(c);this.setDays(Math.floor(k/864E5)*h);k%=864E5;this.setHours(Math.floor(k/36E5)*h);k%=36E5;this.setMinutes(Math.floor(k/6E4)*h);k%=6E4;this.setSeconds(Math.floor(k/1E3)*h);this.setMilliseconds(k%1E3*h)}else this.set(c,a,b,e,f);this.getTotalMilliseconds=function(){return 864E5*this.getDays()+
36E5*this.getHours()+6E4*this.getMinutes()+1E3*this.getSeconds()};this.compareTo=function(a){var b=new Date(1970,1,1,this.getHours(),this.getMinutes(),this.getSeconds());a=null===a?new Date(1970,1,1,0,0,0):new Date(1970,1,1,a.getHours(),a.getMinutes(),a.getSeconds());return b<a?-1:b>a?1:0};this.equals=function(a){return 0===this.compareTo(a)};this.add=function(a){return null===a?this:this.addSeconds(a.getTotalMilliseconds()/1E3)};this.subtract=function(a){return null===a?this:this.addSeconds(-a.getTotalMilliseconds()/
1E3)};this.addDays=function(a){return new d(this.getTotalMilliseconds()+864E5*a)};this.addHours=function(a){return new d(this.getTotalMilliseconds()+36E5*a)};this.addMinutes=function(a){return new d(this.getTotalMilliseconds()+6E4*a)};this.addSeconds=function(a){return new d(this.getTotalMilliseconds()+1E3*a)};this.addMilliseconds=function(a){return new d(this.getTotalMilliseconds()+a)};this.get12HourHour=function(){return 12<this.getHours()?this.getHours()-12:0===this.getHours()?12:this.getHours()};
this.getDesignator=function(){return 12>this.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator};this.toString=function(a){this._toString=function(){return null!==this.getDays()&&0<this.getDays()?this.getDays()+"."+this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds()):this.getHours()+":"+this.p(this.getMinutes())+":"+this.p(this.getSeconds())};this.p=function(a){return 2>a.toString().length?"0"+a:a};var b=this;return a?a.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g,
function(a){switch(a){case "d":return b.getDays();case "dd":return b.p(b.getDays());case "H":return b.getHours();case "HH":return b.p(b.getHours());case "h":return b.get12HourHour();case "hh":return b.p(b.get12HourHour());case "m":return b.getMinutes();case "mm":return b.p(b.getMinutes());case "s":return b.getSeconds();case "ss":return b.p(b.getSeconds());case "t":return(12>b.getHours()?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator).substring(0,1);case "tt":return 12>b.getHours()?Date.CultureInfo.amDesignator:
Date.CultureInfo.pmDesignator}}):this._toString()};return this};(function(c,a){for(var b=0;b<a.length;b++){var e=a[b],d=e.slice(0,1).toUpperCase()+e.slice(1);c.prototype[e]=0;c.prototype["get"+d]=h(e);c.prototype["set"+d]=f(e)}})(d,"years months days hours minutes seconds milliseconds".split(" ").slice(2));d.prototype.set=function(c,a,b,e,d){this.setDays(c||this.getDays());this.setHours(a||this.getHours());this.setMinutes(b||this.getMinutes());this.setSeconds(e||this.getSeconds());this.setMilliseconds(d||
this.getMilliseconds())};Date.prototype.getTimeOfDay=function(){return new d(0,this.getHours(),this.getMinutes(),this.getSeconds(),this.getMilliseconds())};Date.TimeSpan=d;"undefined"!==typeof window&&(window.TimeSpan=d)})();
(function(){var h=function(a){return function(){return this[a]}},f=function(a){return function(b){this[a]=b;return this}},d=function(a,b,c,d){function f(){b.addMonths(-a);d.months++;12===d.months&&(d.years++,d.months=0)}if(1===a)for(;b>c;)f();else for(;b<c;)f();d.months--;d.months*=a;d.years*=a},c=function(a,b,c,f,h,k,n){if(7===arguments.length)this.set(a,b,c,f,h,k,n);else if(2===arguments.length&&arguments[0]instanceof Date&&arguments[1]instanceof Date){var l=arguments[0].clone(),p=arguments[1].clone(),
q=l>p?1:-1;this.dates={start:arguments[0].clone(),end:arguments[1].clone()};d(q,l,p,this);var s=!1===(l.isDaylightSavingTime()===p.isDaylightSavingTime());s&&1===q?l.addHours(-1):s&&l.addHours(1);l=p-l;0!==l&&(l=new TimeSpan(l),this.set(this.years,this.months,l.getDays(),l.getHours(),l.getMinutes(),l.getSeconds(),l.getMilliseconds()))}return this};(function(a,b){for(var c=0;c<b.length;c++){var d=b[c],m=d.slice(0,1).toUpperCase()+d.slice(1);a.prototype[d]=0;a.prototype["get"+m]=h(d);a.prototype["set"+
m]=f(d)}})(c,"years months days hours minutes seconds milliseconds".split(" "));c.prototype.set=function(a,b,c,d,f,h,n){this.setYears(a||this.getYears());this.setMonths(b||this.getMonths());this.setDays(c||this.getDays());this.setHours(d||this.getHours());this.setMinutes(f||this.getMinutes());this.setSeconds(h||this.getSeconds());this.setMilliseconds(n||this.getMilliseconds())};Date.TimePeriod=c;"undefined"!==typeof window&&(window.TimePeriod=c)})();
|
var EXIF = (function() {
var debug = false;
var ExifTags = {
// version tags
0x9000 : "ExifVersion", // EXIF version
0xA000 : "FlashpixVersion", // Flashpix format version
// colorspace tags
0xA001 : "ColorSpace", // Color space information tag
// image configuration
0xA002 : "PixelXDimension", // Valid width of meaningful image
0xA003 : "PixelYDimension", // Valid height of meaningful image
0x9101 : "ComponentsConfiguration", // Information about channels
0x9102 : "CompressedBitsPerPixel", // Compressed bits per pixel
// user information
0x927C : "MakerNote", // Any desired information written by the manufacturer
0x9286 : "UserComment", // Comments by user
// related file
0xA004 : "RelatedSoundFile", // Name of related sound file
// date and time
0x9003 : "DateTimeOriginal", // Date and time when the original image was generated
0x9004 : "DateTimeDigitized", // Date and time when the image was stored digitally
0x9290 : "SubsecTime", // Fractions of seconds for DateTime
0x9291 : "SubsecTimeOriginal", // Fractions of seconds for DateTimeOriginal
0x9292 : "SubsecTimeDigitized", // Fractions of seconds for DateTimeDigitized
// picture-taking conditions
0x829A : "ExposureTime", // Exposure time (in seconds)
0x829D : "FNumber", // F number
0x8822 : "ExposureProgram", // Exposure program
0x8824 : "SpectralSensitivity", // Spectral sensitivity
0x8827 : "ISOSpeedRatings", // ISO speed rating
0x8828 : "OECF", // Optoelectric conversion factor
0x9201 : "ShutterSpeedValue", // Shutter speed
0x9202 : "ApertureValue", // Lens aperture
0x9203 : "BrightnessValue", // Value of brightness
0x9204 : "ExposureBias", // Exposure bias
0x9205 : "MaxApertureValue", // Smallest F number of lens
0x9206 : "SubjectDistance", // Distance to subject in meters
0x9207 : "MeteringMode", // Metering mode
0x9208 : "LightSource", // Kind of light source
0x9209 : "Flash", // Flash status
0x9214 : "SubjectArea", // Location and area of main subject
0x920A : "FocalLength", // Focal length of the lens in mm
0xA20B : "FlashEnergy", // Strobe energy in BCPS
0xA20C : "SpatialFrequencyResponse", //
0xA20E : "FocalPlaneXResolution", // Number of pixels in width direction per FocalPlaneResolutionUnit
0xA20F : "FocalPlaneYResolution", // Number of pixels in height direction per FocalPlaneResolutionUnit
0xA210 : "FocalPlaneResolutionUnit", // Unit for measuring FocalPlaneXResolution and FocalPlaneYResolution
0xA214 : "SubjectLocation", // Location of subject in image
0xA215 : "ExposureIndex", // Exposure index selected on camera
0xA217 : "SensingMethod", // Image sensor type
0xA300 : "FileSource", // Image source (3 == DSC)
0xA301 : "SceneType", // Scene type (1 == directly photographed)
0xA302 : "CFAPattern", // Color filter array geometric pattern
0xA401 : "CustomRendered", // Special processing
0xA402 : "ExposureMode", // Exposure mode
0xA403 : "WhiteBalance", // 1 = auto white balance, 2 = manual
0xA404 : "DigitalZoomRation", // Digital zoom ratio
0xA405 : "FocalLengthIn35mmFilm", // Equivalent foacl length assuming 35mm film camera (in mm)
0xA406 : "SceneCaptureType", // Type of scene
0xA407 : "GainControl", // Degree of overall image gain adjustment
0xA408 : "Contrast", // Direction of contrast processing applied by camera
0xA409 : "Saturation", // Direction of saturation processing applied by camera
0xA40A : "Sharpness", // Direction of sharpness processing applied by camera
0xA40B : "DeviceSettingDescription", //
0xA40C : "SubjectDistanceRange", // Distance to subject
// other tags
0xA005 : "InteroperabilityIFDPointer",
0xA420 : "ImageUniqueID" // Identifier assigned uniquely to each image
};
var TiffTags = {
0x0100 : "ImageWidth",
0x0101 : "ImageHeight",
0x8769 : "ExifIFDPointer",
0x8825 : "GPSInfoIFDPointer",
0xA005 : "InteroperabilityIFDPointer",
0x0102 : "BitsPerSample",
0x0103 : "Compression",
0x0106 : "PhotometricInterpretation",
0x0112 : "Orientation",
0x0115 : "SamplesPerPixel",
0x011C : "PlanarConfiguration",
0x0212 : "YCbCrSubSampling",
0x0213 : "YCbCrPositioning",
0x011A : "XResolution",
0x011B : "YResolution",
0x0128 : "ResolutionUnit",
0x0111 : "StripOffsets",
0x0116 : "RowsPerStrip",
0x0117 : "StripByteCounts",
0x0201 : "JPEGInterchangeFormat",
0x0202 : "JPEGInterchangeFormatLength",
0x012D : "TransferFunction",
0x013E : "WhitePoint",
0x013F : "PrimaryChromaticities",
0x0211 : "YCbCrCoefficients",
0x0214 : "ReferenceBlackWhite",
0x0132 : "DateTime",
0x010E : "ImageDescription",
0x010F : "Make",
0x0110 : "Model",
0x0131 : "Software",
0x013B : "Artist",
0x8298 : "Copyright"
};
var GPSTags = {
0x0000 : "GPSVersionID",
0x0001 : "GPSLatitudeRef",
0x0002 : "GPSLatitude",
0x0003 : "GPSLongitudeRef",
0x0004 : "GPSLongitude",
0x0005 : "GPSAltitudeRef",
0x0006 : "GPSAltitude",
0x0007 : "GPSTimeStamp",
0x0008 : "GPSSatellites",
0x0009 : "GPSStatus",
0x000A : "GPSMeasureMode",
0x000B : "GPSDOP",
0x000C : "GPSSpeedRef",
0x000D : "GPSSpeed",
0x000E : "GPSTrackRef",
0x000F : "GPSTrack",
0x0010 : "GPSImgDirectionRef",
0x0011 : "GPSImgDirection",
0x0012 : "GPSMapDatum",
0x0013 : "GPSDestLatitudeRef",
0x0014 : "GPSDestLatitude",
0x0015 : "GPSDestLongitudeRef",
0x0016 : "GPSDestLongitude",
0x0017 : "GPSDestBearingRef",
0x0018 : "GPSDestBearing",
0x0019 : "GPSDestDistanceRef",
0x001A : "GPSDestDistance",
0x001B : "GPSProcessingMethod",
0x001C : "GPSAreaInformation",
0x001D : "GPSDateStamp",
0x001E : "GPSDifferential"
};
var StringValues = {
ExposureProgram : {
0 : "Not defined",
1 : "Manual",
2 : "Normal program",
3 : "Aperture priority",
4 : "Shutter priority",
5 : "Creative program",
6 : "Action program",
7 : "Portrait mode",
8 : "Landscape mode"
},
MeteringMode : {
0 : "Unknown",
1 : "Average",
2 : "CenterWeightedAverage",
3 : "Spot",
4 : "MultiSpot",
5 : "Pattern",
6 : "Partial",
255 : "Other"
},
LightSource : {
0 : "Unknown",
1 : "Daylight",
2 : "Fluorescent",
3 : "Tungsten (incandescent light)",
4 : "Flash",
9 : "Fine weather",
10 : "Cloudy weather",
11 : "Shade",
12 : "Daylight fluorescent (D 5700 - 7100K)",
13 : "Day white fluorescent (N 4600 - 5400K)",
14 : "Cool white fluorescent (W 3900 - 4500K)",
15 : "White fluorescent (WW 3200 - 3700K)",
17 : "Standard light A",
18 : "Standard light B",
19 : "Standard light C",
20 : "D55",
21 : "D65",
22 : "D75",
23 : "D50",
24 : "ISO studio tungsten",
255 : "Other"
},
Flash : {
0x0000 : "Flash did not fire",
0x0001 : "Flash fired",
0x0005 : "Strobe return light not detected",
0x0007 : "Strobe return light detected",
0x0009 : "Flash fired, compulsory flash mode",
0x000D : "Flash fired, compulsory flash mode, return light not detected",
0x000F : "Flash fired, compulsory flash mode, return light detected",
0x0010 : "Flash did not fire, compulsory flash mode",
0x0018 : "Flash did not fire, auto mode",
0x0019 : "Flash fired, auto mode",
0x001D : "Flash fired, auto mode, return light not detected",
0x001F : "Flash fired, auto mode, return light detected",
0x0020 : "No flash function",
0x0041 : "Flash fired, red-eye reduction mode",
0x0045 : "Flash fired, red-eye reduction mode, return light not detected",
0x0047 : "Flash fired, red-eye reduction mode, return light detected",
0x0049 : "Flash fired, compulsory flash mode, red-eye reduction mode",
0x004D : "Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",
0x004F : "Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",
0x0059 : "Flash fired, auto mode, red-eye reduction mode",
0x005D : "Flash fired, auto mode, return light not detected, red-eye reduction mode",
0x005F : "Flash fired, auto mode, return light detected, red-eye reduction mode"
},
SensingMethod : {
1 : "Not defined",
2 : "One-chip color area sensor",
3 : "Two-chip color area sensor",
4 : "Three-chip color area sensor",
5 : "Color sequential area sensor",
7 : "Trilinear sensor",
8 : "Color sequential linear sensor"
},
SceneCaptureType : {
0 : "Standard",
1 : "Landscape",
2 : "Portrait",
3 : "Night scene"
},
SceneType : {
1 : "Directly photographed"
},
CustomRendered : {
0 : "Normal process",
1 : "Custom process"
},
WhiteBalance : {
0 : "Auto white balance",
1 : "Manual white balance"
},
GainControl : {
0 : "None",
1 : "Low gain up",
2 : "High gain up",
3 : "Low gain down",
4 : "High gain down"
},
Contrast : {
0 : "Normal",
1 : "Soft",
2 : "Hard"
},
Saturation : {
0 : "Normal",
1 : "Low saturation",
2 : "High saturation"
},
Sharpness : {
0 : "Normal",
1 : "Soft",
2 : "Hard"
},
SubjectDistanceRange : {
0 : "Unknown",
1 : "Macro",
2 : "Close view",
3 : "Distant view"
},
FileSource : {
3 : "DSC"
},
Components : {
0 : "",
1 : "Y",
2 : "Cb",
3 : "Cr",
4 : "R",
5 : "G",
6 : "B"
}
};
function addEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + event, handler);
}
}
function imageHasData(img) {
return !!(img.exifdata);
}
function getImageData(img, callback) {
function handleBinaryFile(binFile) {
var data = findEXIFinJPEG(binFile);
img.exifdata = data || {};
if (callback) {
callback.call(img)
}
}
if (img instanceof Image) {
BinaryAjax(img.src, function(http) {
handleBinaryFile(http.binaryResponse);
});
} else if (window.FileReader && img instanceof window.File) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
handleBinaryFile(new BinaryFile(e.target.result));
};
fileReader.readAsBinaryString(img);
}
}
function findEXIFinJPEG(file) {
if (file.getByteAt(0) != 0xFF || file.getByteAt(1) != 0xD8) {
return false; // not a valid jpeg
}
var offset = 2,
length = file.getLength(),
marker;
while (offset < length) {
if (file.getByteAt(offset) != 0xFF) {
if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + file.getByteAt(offset));
return false; // not a valid marker, something is wrong
}
marker = file.getByteAt(offset+1);
// we could implement handling for other markers here,
// but we're only looking for 0xFFE1 for EXIF data
if (marker == 22400) {
if (debug) console.log("Found 0xFFE1 marker");
return readEXIFData(file, offset + 4, file.getShortAt(offset+2, true)-2);
// offset += 2 + file.getShortAt(offset+2, true);
} else if (marker == 225) {
// 0xE1 = Application-specific 1 (for EXIF)
if (debug) console.log("Found 0xFFE1 marker");
return readEXIFData(file, offset + 4, file.getShortAt(offset+2, true)-2);
} else {
offset += 2 + file.getShortAt(offset+2, true);
}
}
}
function readTags(file, tiffStart, dirStart, strings, bigEnd) {
var entries = file.getShortAt(dirStart, bigEnd),
tags = {},
entryOffset, tag,
i;
for (i=0;i<entries;i++) {
entryOffset = dirStart + i*12 + 2;
tag = strings[file.getShortAt(entryOffset, bigEnd)];
if (!tag && debug) console.log("Unknown tag: " + file.getShortAt(entryOffset, bigEnd));
tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
}
return tags;
}
function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
var type = file.getShortAt(entryOffset+2, bigEnd),
numValues = file.getLongAt(entryOffset+4, bigEnd),
valueOffset = file.getLongAt(entryOffset+8, bigEnd) + tiffStart,
offset,
vals, val, n,
numerator, denominator;
switch (type) {
case 1: // byte, 8-bit unsigned int
case 7: // undefined, 8-bit byte, value depending on field
if (numValues == 1) {
return file.getByteAt(entryOffset + 8, bigEnd);
} else {
offset = numValues > 4 ? valueOffset : (entryOffset + 8);
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getByteAt(offset + n);
}
return vals;
}
case 2: // ascii, 8-bit byte
offset = numValues > 4 ? valueOffset : (entryOffset + 8);
return file.getStringAt(offset, numValues-1);
case 3: // short, 16 bit int
if (numValues == 1) {
return file.getShortAt(entryOffset + 8, bigEnd);
} else {
offset = numValues > 2 ? valueOffset : (entryOffset + 8);
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getShortAt(offset + 2*n, bigEnd);
}
return vals;
}
case 4: // long, 32 bit int
if (numValues == 1) {
return file.getLongAt(entryOffset + 8, bigEnd);
} else {
vals = [];
for (var n=0;n<numValues;n++) {
vals[n] = file.getLongAt(valueOffset + 4*n, bigEnd);
}
return vals;
}
case 5: // rational = two long values, first is numerator, second is denominator
if (numValues == 1) {
numerator = file.getLongAt(valueOffset, bigEnd);
denominator = file.getLongAt(valueOffset+4, bigEnd);
val = new Number(numerator / denominator);
val.numerator = numerator;
val.denominator = denominator;
return val;
} else {
vals = [];
for (n=0;n<numValues;n++) {
numerator = file.getLongAt(valueOffset + 8*n, bigEnd);
denominator = file.getLongAt(valueOffset+4 + 8*n, bigEnd);
vals[n] = new Number(numerator / denominator);
vals[n].numerator = numerator;
vals[n].denominator = denominator;
}
return vals;
}
case 9: // slong, 32 bit signed int
if (numValues == 1) {
return file.getSLongAt(entryOffset + 8, bigEnd);
} else {
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getSLongAt(valueOffset + 4*n, bigEnd);
}
return vals;
}
case 10: // signed rational, two slongs, first is numerator, second is denominator
if (numValues == 1) {
return file.getSLongAt(valueOffset, bigEnd) / file.getSLongAt(valueOffset+4, bigEnd);
} else {
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getSLongAt(valueOffset + 8*n, bigEnd) / file.getSLongAt(valueOffset+4 + 8*n, bigEnd);
}
return vals;
}
}
}
function readEXIFData(file, start) {
if (file.getStringAt(start, 4) != "Exif") {
if (debug) console.log("Not valid EXIF data! " + file.getStringAt(start, 4));
return false;
}
var bigEnd,
tags, tag,
exifData, gpsData,
tiffOffset = start + 6;
// test for TIFF validity and endianness
if (file.getShortAt(tiffOffset) == 0x4949) {
bigEnd = false;
} else if (file.getShortAt(tiffOffset) == 0x4D4D) {
bigEnd = true;
} else {
if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
return false;
}
if (file.getShortAt(tiffOffset+2, bigEnd) != 0x002A) {
if (debug) console.log("Not valid TIFF data! (no 0x002A)");
return false;
}
if (file.getLongAt(tiffOffset+4, bigEnd) != 0x00000008) {
if (debug) console.log("Not valid TIFF data! (First offset not 8)", file.getShortAt(tiffOffset+4, bigEnd));
return false;
}
tags = readTags(file, tiffOffset, tiffOffset+8, TiffTags, bigEnd);
if (tags.ExifIFDPointer) {
exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
for (tag in exifData) {
switch (tag) {
case "LightSource" :
case "Flash" :
case "MeteringMode" :
case "ExposureProgram" :
case "SensingMethod" :
case "SceneCaptureType" :
case "SceneType" :
case "CustomRendered" :
case "WhiteBalance" :
case "GainControl" :
case "Contrast" :
case "Saturation" :
case "Sharpness" :
case "SubjectDistanceRange" :
case "FileSource" :
exifData[tag] = StringValues[tag][exifData[tag]];
break;
case "ExifVersion" :
case "FlashpixVersion" :
exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
break;
case "ComponentsConfiguration" :
exifData[tag] =
StringValues.Components[exifData[tag][0]]
+ StringValues.Components[exifData[tag][1]]
+ StringValues.Components[exifData[tag][2]]
+ StringValues.Components[exifData[tag][3]];
break;
}
tags[tag] = exifData[tag];
}
}
if (tags.GPSInfoIFDPointer) {
gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
for (tag in gpsData) {
switch (tag) {
case "GPSVersionID" :
gpsData[tag] = gpsData[tag][0]
+ "." + gpsData[tag][1]
+ "." + gpsData[tag][2]
+ "." + gpsData[tag][3];
break;
}
tags[tag] = gpsData[tag];
}
}
return tags;
}
function getData(img, callback) {
if (img instanceof Image && !img.complete) return false;
if (!imageHasData(img)) {
getImageData(img, callback);
} else {
if (callback) {
callback.call(img);
}
}
return true;
}
function getTag(img, tag) {
if (!imageHasData(img)) return;
return img.exifdata[tag];
}
function getAllTags(img) {
if (!imageHasData(img)) return {};
var a,
data = img.exifdata,
tags = {};
for (a in data) {
if (data.hasOwnProperty(a)) {
tags[a] = data[a];
}
}
return tags;
}
function pretty(img) {
if (!imageHasData(img)) return "";
var a,
data = img.exifdata,
strPretty = "";
for (a in data) {
if (data.hasOwnProperty(a)) {
if (typeof data[a] == "object") {
if (data[a] instanceof Number) {
strPretty += a + " : " + data[a] + " [" + data[a].numerator + "/" + data[a].denominator + "]\r\n";
} else {
strPretty += a + " : [" + data[a].length + " values]\r\n";
}
} else {
strPretty += a + " : " + data[a] + "\r\n";
}
}
}
return strPretty;
}
function readFromBinaryFile(file) {
return findEXIFinJPEG(file);
}
return {
readFromBinaryFile : readFromBinaryFile,
pretty : pretty,
getTag : getTag,
getAllTags : getAllTags,
getData : getData,
Tags : ExifTags,
TiffTags : TiffTags,
GPSTags : GPSTags,
StringValues : StringValues
};
})();
|
/*!
* OOjs UI v0.22.3
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2017 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2017-07-11T22:12:33Z
*/
( function ( OO ) {
'use strict';
/**
* An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
* Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
* of the actions.
*
* Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
* @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
* should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
* for more information about setting modes.
* @cfg {boolean} [framed=false] Render the action button with a frame
*/
OO.ui.ActionWidget = function OoUiActionWidget( config ) {
// Configuration initialization
config = $.extend( { framed: false }, config );
// Parent constructor
OO.ui.ActionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this, config );
// Properties
this.action = config.action || '';
this.modes = config.modes || [];
this.width = 0;
this.height = 0;
// Initialization
this.$element.addClass( 'oo-ui-actionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
/* Methods */
/**
* Check if the action is configured to be available in the specified `mode`.
*
* @param {string} mode Name of mode
* @return {boolean} The action is configured with the mode
*/
OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
return this.modes.indexOf( mode ) !== -1;
};
/**
* Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
*
* @return {string}
*/
OO.ui.ActionWidget.prototype.getAction = function () {
return this.action;
};
/**
* Get the symbolic name of the mode or modes for which the action is configured to be available.
*
* The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
* Only actions that are configured to be avaiable in the current mode will be visible. All other actions
* are hidden.
*
* @return {string[]}
*/
OO.ui.ActionWidget.prototype.getModes = function () {
return this.modes.slice();
};
/* eslint-disable no-unused-vars */
/**
* ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
* Actions can be made available for specific contexts (modes) and circumstances
* (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
*
* ActionSets contain two types of actions:
*
* - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
* - Other: Other actions include all non-special visible actions.
*
* Please see the [OOjs UI documentation on MediaWiki][1] for more information.
*
* @example
* // Example: An action set used in a process dialog
* function MyProcessDialog( config ) {
* MyProcessDialog.parent.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
* MyProcessDialog.static.title = 'An action set in a process dialog';
* MyProcessDialog.static.name = 'myProcessDialog';
* // An action set that uses modes ('edit' and 'help' mode, in this example).
* MyProcessDialog.static.actions = [
* { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
* { action: 'help', modes: 'edit', label: 'Help' },
* { modes: 'edit', label: 'Cancel', flags: 'safe' },
* { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
* this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
* this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
* this.stackLayout = new OO.ui.StackLayout( {
* items: [ this.panel1, this.panel2 ]
* } );
* this.$body.append( this.stackLayout.$element );
* };
* MyProcessDialog.prototype.getSetupProcess = function ( data ) {
* return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
* .next( function () {
* this.actions.setMode( 'edit' );
* }, this );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* if ( action === 'help' ) {
* this.actions.setMode( 'help' );
* this.stackLayout.setItem( this.panel2 );
* } else if ( action === 'back' ) {
* this.actions.setMode( 'edit' );
* this.stackLayout.setItem( this.panel1 );
* } else if ( action === 'continue' ) {
* var dialog = this;
* return new OO.ui.Process( function () {
* dialog.close();
* } );
* }
* return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
* };
* MyProcessDialog.prototype.getBodyHeight = function () {
* return this.panel1.$element.outerHeight( true );
* };
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* var dialog = new MyProcessDialog( {
* size: 'medium'
* } );
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @abstract
* @class
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ActionSet = function OoUiActionSet( config ) {
// Configuration initialization
config = config || {};
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.list = [];
this.categories = {
actions: 'getAction',
flags: 'getFlags',
modes: 'getModes'
};
this.categorized = {};
this.special = {};
this.others = [];
this.organized = false;
this.changing = false;
this.changed = false;
};
/* eslint-enable no-unused-vars */
/* Setup */
OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the flags used to identify special actions. Special actions are displayed in the
* header of a {@link OO.ui.ProcessDialog process dialog}.
* See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
*
* [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
/* Events */
/**
* @event click
*
* A 'click' event is emitted when an action is clicked.
*
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
/**
* @event add
*
* An 'add' event is emitted when actions are {@link #method-add added} to the action set.
*
* @param {OO.ui.ActionWidget[]} added Actions added
*/
/**
* @event remove
*
* A 'remove' event is emitted when actions are {@link #method-remove removed}
* or {@link #clear cleared}.
*
* @param {OO.ui.ActionWidget[]} added Actions removed
*/
/**
* @event change
*
* A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
* or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
*
*/
/* Methods */
/**
* Handle action change events.
*
* @private
* @fires change
*/
OO.ui.ActionSet.prototype.onActionChange = function () {
this.organized = false;
if ( this.changing ) {
this.changed = true;
} else {
this.emit( 'change' );
}
};
/**
* Check if an action is one of the special actions.
*
* @param {OO.ui.ActionWidget} action Action to check
* @return {boolean} Action is special
*/
OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
var flag;
for ( flag in this.special ) {
if ( action === this.special[ flag ] ) {
return true;
}
}
return false;
};
/**
* Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
* or ‘disabled’.
*
* @param {Object} [filters] Filters to use, omit to get all actions
* @param {string|string[]} [filters.actions] Actions that action widgets must have
* @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
* @param {string|string[]} [filters.modes] Modes that action widgets must have
* @param {boolean} [filters.visible] Action widgets must be visible
* @param {boolean} [filters.disabled] Action widgets must be disabled
* @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
*/
OO.ui.ActionSet.prototype.get = function ( filters ) {
var i, len, list, category, actions, index, match, matches;
if ( filters ) {
this.organize();
// Collect category candidates
matches = [];
for ( category in this.categorized ) {
list = filters[ category ];
if ( list ) {
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( i = 0, len = list.length; i < len; i++ ) {
actions = this.categorized[ category ][ list[ i ] ];
if ( Array.isArray( actions ) ) {
matches.push.apply( matches, actions );
}
}
}
}
// Remove by boolean filters
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
if (
( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
) {
matches.splice( i, 1 );
len--;
i--;
}
}
// Remove duplicates
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
index = matches.lastIndexOf( match );
while ( index !== i ) {
matches.splice( index, 1 );
len--;
index = matches.lastIndexOf( match );
}
}
return matches;
}
return this.list.slice();
};
/**
* Get 'special' actions.
*
* Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
* Special flags can be configured in subclasses by changing the static #specialFlags property.
*
* @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
*/
OO.ui.ActionSet.prototype.getSpecial = function () {
this.organize();
return $.extend( {}, this.special );
};
/**
* Get 'other' actions.
*
* Other actions include all non-special visible action widgets.
*
* @return {OO.ui.ActionWidget[]} 'Other' action widgets
*/
OO.ui.ActionSet.prototype.getOthers = function () {
this.organize();
return this.others.slice();
};
/**
* Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
* to be available in the specified mode will be made visible. All other actions will be hidden.
*
* @param {string} mode The mode. Only actions configured to be available in the specified
* mode will be made visible.
* @chainable
* @fires toggle
* @fires change
*/
OO.ui.ActionSet.prototype.setMode = function ( mode ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.toggle( action.hasMode( mode ) );
}
this.organized = false;
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Set the abilities of the specified actions.
*
* Action widgets that are configured with the specified actions will be enabled
* or disabled based on the boolean values specified in the `actions`
* parameter.
*
* @param {Object.<string,boolean>} actions A list keyed by action name with boolean
* values that indicate whether or not the action should be enabled.
* @chainable
*/
OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
var i, len, action, item;
for ( i = 0, len = this.list.length; i < len; i++ ) {
item = this.list[ i ];
action = item.getAction();
if ( actions[ action ] !== undefined ) {
item.setDisabled( !actions[ action ] );
}
}
return this;
};
/**
* Executes a function once per action.
*
* When making changes to multiple actions, use this method instead of iterating over the actions
* manually to defer emitting a #change event until after all actions have been changed.
*
* @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
* @param {Function} callback Callback to run for each action; callback is invoked with three
* arguments: the action, the action's index, the list of actions being iterated over
* @chainable
*/
OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
this.changed = false;
this.changing = true;
this.get( filter ).forEach( callback );
this.changing = false;
if ( this.changed ) {
this.emit( 'change' );
}
return this;
};
/**
* Add action widgets to the action set.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to add
* @chainable
* @fires add
* @fires change
*/
OO.ui.ActionSet.prototype.add = function ( actions ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
action.connect( this, {
click: [ 'emit', 'click', action ],
toggle: [ 'onActionChange' ]
} );
this.list.push( action );
}
this.organized = false;
this.emit( 'add', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove action widgets from the set.
*
* To remove all actions, you may wish to use the #clear method instead.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to remove
* @chainable
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.remove = function ( actions ) {
var i, len, index, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
index = this.list.indexOf( action );
if ( index !== -1 ) {
action.disconnect( this );
this.list.splice( index, 1 );
}
}
this.organized = false;
this.emit( 'remove', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove all action widets from the set.
*
* To remove only specified actions, use the {@link #method-remove remove} method instead.
*
* @chainable
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.clear = function () {
var i, len, action,
removed = this.list.slice();
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.disconnect( this );
}
this.list = [];
this.organized = false;
this.emit( 'remove', removed );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Organize actions.
*
* This is called whenever organized information is requested. It will only reorganize the actions
* if something has changed since the last time it ran.
*
* @private
* @chainable
*/
OO.ui.ActionSet.prototype.organize = function () {
var i, iLen, j, jLen, flag, action, category, list, item, special,
specialFlags = this.constructor.static.specialFlags;
if ( !this.organized ) {
this.categorized = {};
this.special = {};
this.others = [];
for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
action = this.list[ i ];
if ( action.isVisible() ) {
// Populate categories
for ( category in this.categories ) {
if ( !this.categorized[ category ] ) {
this.categorized[ category ] = {};
}
list = action[ this.categories[ category ] ]();
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( j = 0, jLen = list.length; j < jLen; j++ ) {
item = list[ j ];
if ( !this.categorized[ category ][ item ] ) {
this.categorized[ category ][ item ] = [];
}
this.categorized[ category ][ item ].push( action );
}
}
// Populate special/others
special = false;
for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
flag = specialFlags[ j ];
if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
this.special[ flag ] = action;
special = true;
break;
}
}
if ( !special ) {
this.others.push( action );
}
}
}
this.organized = true;
}
return this;
};
/**
* Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
* in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
* appearance and functionality of the error interface.
*
* The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
* is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
* that initiated the failed process will be disabled.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
* process again.
*
* For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
*
* @class
*
* @constructor
* @param {string|jQuery} message Description of error
* @param {Object} [config] Configuration options
* @cfg {boolean} [recoverable=true] Error is recoverable.
* By default, errors are recoverable, and users can try the process again.
* @cfg {boolean} [warning=false] Error is a warning.
* If the error is a warning, the error interface will include a
* 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
* is not triggered a second time if the user chooses to continue.
*/
OO.ui.Error = function OoUiError( message, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( message ) && config === undefined ) {
config = message;
message = config.message;
}
// Configuration initialization
config = config || {};
// Properties
this.message = message instanceof jQuery ? message : String( message );
this.recoverable = config.recoverable === undefined || !!config.recoverable;
this.warning = !!config.warning;
};
/* Setup */
OO.initClass( OO.ui.Error );
/* Methods */
/**
* Check if the error is recoverable.
*
* If the error is recoverable, users are able to try the process again.
*
* @return {boolean} Error is recoverable
*/
OO.ui.Error.prototype.isRecoverable = function () {
return this.recoverable;
};
/**
* Check if the error is a warning.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
*
* @return {boolean} Error is warning
*/
OO.ui.Error.prototype.isWarning = function () {
return this.warning;
};
/**
* Get error message as DOM nodes.
*
* @return {jQuery} Error message in DOM nodes
*/
OO.ui.Error.prototype.getMessage = function () {
return this.message instanceof jQuery ?
this.message.clone() :
$( '<div>' ).text( this.message ).contents();
};
/**
* Get the error message text.
*
* @return {string} Error message
*/
OO.ui.Error.prototype.getMessageText = function () {
return this.message instanceof jQuery ? this.message.text() : this.message;
};
/**
* A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
* or a function:
*
* - **number**: the process will wait for the specified number of milliseconds before proceeding.
* - **promise**: the process will continue to the next step when the promise is successfully resolved
* or stop if the promise is rejected.
* - **function**: the process will execute the function. The process will stop if the function returns
* either a boolean `false` or a promise that is rejected; if the function returns a number, the process
* will wait for that number of milliseconds before proceeding.
*
* If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
* configured, users can dismiss the error and try the process again, or not. If a process is stopped,
* its remaining steps will not be performed.
*
* @class
*
* @constructor
* @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
* that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
* @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
* a number or promise.
*/
OO.ui.Process = function ( step, context ) {
// Properties
this.steps = [];
// Initialization
if ( step !== undefined ) {
this.next( step, context );
}
};
/* Setup */
OO.initClass( OO.ui.Process );
/* Methods */
/**
* Start the process.
*
* @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
* If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
* and any remaining steps are not performed.
*/
OO.ui.Process.prototype.execute = function () {
var i, len, promise;
/**
* Continue execution.
*
* @ignore
* @param {Array} step A function and the context it should be called in
* @return {Function} Function that continues the process
*/
function proceed( step ) {
return function () {
// Execute step in the correct context
var deferred,
result = step.callback.call( step.context );
if ( result === false ) {
// Use rejected promise for boolean false results
return $.Deferred().reject( [] ).promise();
}
if ( typeof result === 'number' ) {
if ( result < 0 ) {
throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
}
// Use a delayed promise for numbers, expecting them to be in milliseconds
deferred = $.Deferred();
setTimeout( deferred.resolve, result );
return deferred.promise();
}
if ( result instanceof OO.ui.Error ) {
// Use rejected promise for error
return $.Deferred().reject( [ result ] ).promise();
}
if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
// Use rejected promise for list of errors
return $.Deferred().reject( result ).promise();
}
// Duck-type the object to see if it can produce a promise
if ( result && $.isFunction( result.promise ) ) {
// Use a promise generated from the result
return result.promise();
}
// Use resolved promise for other results
return $.Deferred().resolve().promise();
};
}
if ( this.steps.length ) {
// Generate a chain reaction of promises
promise = proceed( this.steps[ 0 ] )();
for ( i = 1, len = this.steps.length; i < len; i++ ) {
promise = promise.then( proceed( this.steps[ i ] ) );
}
} else {
promise = $.Deferred().resolve().promise();
}
return promise;
};
/**
* Create a process step.
*
* @private
* @param {number|jQuery.Promise|Function} step
*
* - Number of milliseconds to wait before proceeding
* - Promise that must be resolved before proceeding
* - Function to execute
* - If the function returns a boolean false the process will stop
* - If the function returns a promise, the process will continue to the next
* step when the promise is resolved or stop if the promise is rejected
* - If the function returns a number, the process will wait for that number of
* milliseconds before proceeding
* @param {Object} [context=null] Execution context of the function. The context is
* ignored if the step is a number or promise.
* @return {Object} Step object, with `callback` and `context` properties
*/
OO.ui.Process.prototype.createStep = function ( step, context ) {
if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
return {
callback: function () {
return step;
},
context: null
};
}
if ( $.isFunction( step ) ) {
return {
callback: step,
context: context
};
}
throw new Error( 'Cannot create process step: number, promise or function expected' );
};
/**
* Add step to the beginning of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.first = function ( step, context ) {
this.steps.unshift( this.createStep( step, context ) );
return this;
};
/**
* Add step to the end of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.next = function ( step, context ) {
this.steps.push( this.createStep( step, context ) );
return this;
};
/**
* A window instance represents the life cycle for one single opening of a window
* until its closing.
*
* While OO.ui.WindowManager will reuse OO.ui.Window objects, each time a window is
* opened, a new lifecycle starts.
*
* For more information, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
*
* @class
*
* @constructor
*/
OO.ui.WindowInstance = function OOuiWindowInstance() {
var deferreds = {
opening: $.Deferred(),
opened: $.Deferred(),
closing: $.Deferred(),
closed: $.Deferred()
};
/**
* @private
* @property {Object}
*/
this.deferreds = deferreds;
// Set these up as chained promises so that rejecting of
// an earlier stage automatically rejects the subsequent
// would-be stages as well.
/**
* @property {jQuery.Promise}
*/
this.opening = deferreds.opening.promise();
/**
* @property {jQuery.Promise}
*/
this.opened = this.opening.then( function () {
return deferreds.opened;
} );
/**
* @property {jQuery.Promise}
*/
this.closing = this.opened.then( function () {
return deferreds.closing;
} );
/**
* @property {jQuery.Promise}
*/
this.closed = this.closing.then( function () {
return deferreds.closed;
} );
};
/* Setup */
OO.initClass( OO.ui.WindowInstance );
/**
* Check if window is opening.
*
* @return {boolean} Window is opening
*/
OO.ui.WindowInstance.prototype.isOpening = function () {
return this.deferreds.opened.state() === 'pending';
};
/**
* Check if window is opened.
*
* @return {boolean} Window is opened
*/
OO.ui.WindowInstance.prototype.isOpened = function () {
return this.deferreds.opened.state() === 'resolved' &&
this.deferreds.closing.state() === 'pending';
};
/**
* Check if window is closing.
*
* @return {boolean} Window is closing
*/
OO.ui.WindowInstance.prototype.isClosing = function () {
return this.deferreds.closing.state() === 'resolved' &&
this.deferreds.closed.state() === 'pending';
};
/**
* Check if window is closed.
*
* @return {boolean} Window is closed
*/
OO.ui.WindowInstance.prototype.isClosed = function () {
return this.deferreds.closed.state() === 'resolved';
};
/**
* Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
* Managed windows are mutually exclusive. If a new window is opened while a current window is opening
* or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
* themselves are persistent and—rather than being torn down when closed—can be repopulated with the
* pertinent data and reused.
*
* Over the lifecycle of a window, the window manager makes available three promises: `opening`,
* `opened`, and `closing`, which represent the primary stages of the cycle:
*
* **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
* {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
*
* - an `opening` event is emitted with an `opening` promise
* - the #getSetupDelay method is called and the returned value is used to time a pause in execution before the
* window’s {@link OO.ui.Window#method-setup setup} method is called which executes OO.ui.Window#getSetupProcess.
* - a `setup` progress notification is emitted from the `opening` promise
* - the #getReadyDelay method is called the returned value is used to time a pause in execution before the
* window’s {@link OO.ui.Window#method-ready ready} method is called which executes OO.ui.Window#getReadyProcess.
* - a `ready` progress notification is emitted from the `opening` promise
* - the `opening` promise is resolved with an `opened` promise
*
* **Opened**: the window is now open.
*
* **Closing**: the closing stage begins when the window manager's #closeWindow or the
* window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
* to close the window.
*
* - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
* - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
* the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
* window and its result executed
* - a `hold` progress notification is emitted from the `closing` promise
* - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
* the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
* window and its result executed
* - a `teardown` progress notification is emitted from the `closing` promise
* - the `closing` promise is resolved. The window is now closed
*
* See the [OOjs UI documentation on MediaWiki][1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
* Note that window classes that are instantiated with a factory must have
* a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
* @cfg {boolean} [modal=true] Prevent interaction outside the dialog
*/
OO.ui.WindowManager = function OoUiWindowManager( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.WindowManager.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.factory = config.factory;
this.modal = config.modal === undefined || !!config.modal;
this.windows = {};
// Deprecated placeholder promise given to compatOpening in openWindow()
// that is resolved in closeWindow().
this.compatOpened = null;
this.preparingToOpen = null;
this.preparingToClose = null;
this.currentWindow = null;
this.globalEvents = false;
this.$returnFocusTo = null;
this.$ariaHidden = null;
this.onWindowResizeTimeout = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
// Initialization
this.$element
.addClass( 'oo-ui-windowManager' )
.toggleClass( 'oo-ui-windowManager-modal', this.modal );
};
/* Setup */
OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
/* Events */
/**
* An 'opening' event is emitted when the window begins to be opened.
*
* @event opening
* @param {OO.ui.Window} win Window that's being opened
* @param {jQuery.Promise} opened A promise resolved with a value when the window is opened successfully.
* This promise also emits `setup` and `ready` notifications. When this promise is resolved, the first
* argument of the value is an 'closed' promise, the second argument is the opening data.
* @param {Object} data Window opening data
*/
/**
* A 'closing' event is emitted when the window begins to be closed.
*
* @event closing
* @param {OO.ui.Window} win Window that's being closed
* @param {jQuery.Promise} closed A promise resolved with a value when the window is closed successfully.
* This promise also emits `hold` and `teardown` notifications. When this promise is resolved, the first
* argument of its value is the closing data.
* @param {Object} data Window closing data
*/
/**
* A 'resize' event is emitted when a window is resized.
*
* @event resize
* @param {OO.ui.Window} win Window that was resized
*/
/* Static Properties */
/**
* Map of the symbolic name of each window size and its CSS properties.
*
* @static
* @inheritable
* @property {Object}
*/
OO.ui.WindowManager.static.sizes = {
small: {
width: 300
},
medium: {
width: 500
},
large: {
width: 700
},
larger: {
width: 900
},
full: {
// These can be non-numeric because they are never used in calculations
width: '100%',
height: '100%'
}
};
/**
* Symbolic name of the default window size.
*
* The default size is used if the window's requested size is not recognized.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.WindowManager.static.defaultSize = 'medium';
/* Methods */
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.onWindowResize = function () {
clearTimeout( this.onWindowResizeTimeout );
this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
};
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.afterWindowResize = function () {
if ( this.currentWindow ) {
this.updateWindowSize( this.currentWindow );
}
};
/**
* Check if window is opening.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opening
*/
OO.ui.WindowManager.prototype.isOpening = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isOpening();
};
/**
* Check if window is closing.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is closing
*/
OO.ui.WindowManager.prototype.isClosing = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isClosing();
};
/**
* Check if window is opened.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opened
*/
OO.ui.WindowManager.prototype.isOpened = function ( win ) {
return win === this.currentWindow && !!this.lifecycle &&
this.lifecycle.isOpened();
};
/**
* Check if a window is being managed.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is being managed
*/
OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
var name;
for ( name in this.windows ) {
if ( this.windows[ name ] === win ) {
return true;
}
}
return false;
};
/**
* Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getSetupDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getReadyDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getHoldDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after the ‘hold’ process has finished before
* executing the ‘teardown’ process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getTeardownDelay = function () {
return this.modal ? 250 : 0;
};
/**
* Get a window by its symbolic name.
*
* If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
* instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
* for more information about using factories.
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @param {string} name Symbolic name of the window
* @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
* @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
* @throws {Error} An error is thrown if the named window is not recognized as a managed window.
*/
OO.ui.WindowManager.prototype.getWindow = function ( name ) {
var deferred = $.Deferred(),
win = this.windows[ name ];
if ( !( win instanceof OO.ui.Window ) ) {
if ( this.factory ) {
if ( !this.factory.lookup( name ) ) {
deferred.reject( new OO.ui.Error(
'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
) );
} else {
win = this.factory.create( name );
this.addWindows( [ win ] );
deferred.resolve( win );
}
} else {
deferred.reject( new OO.ui.Error(
'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
) );
}
} else {
deferred.resolve( win );
}
return deferred.promise();
};
/**
* Get current window.
*
* @return {OO.ui.Window|null} Currently opening/opened/closing window
*/
OO.ui.WindowManager.prototype.getCurrentWindow = function () {
return this.currentWindow;
};
/**
* Open a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to open
* @param {Object} [data] Window opening data
* @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when closed.
* Defaults the current activeElement. If set to null, focus isn't changed on close.
* @return {OO.ui.WindowInstance|jQuery.Promise} A lifecycle object representing this particular
* opening of the window. For backwards-compatibility, then object is also a Thenable that is resolved
* when the window is done opening, with nested promise for when closing starts. This behaviour
* is deprecated and is not compatible with jQuery 3 (T163510).
* @fires opening
*/
OO.ui.WindowManager.prototype.openWindow = function ( win, data, lifecycle, compatOpening ) {
var error,
manager = this;
data = data || {};
// Internal parameter 'lifecycle' allows this method to always return
// a lifecycle even if the window still needs to be created
// asynchronously when 'win' is a string.
lifecycle = lifecycle || new OO.ui.WindowInstance();
compatOpening = compatOpening || $.Deferred();
// Turn lifecycle into a Thenable for backwards-compatibility with
// the deprecated nested-promise behaviour (T163510).
[ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
.forEach( function ( method ) {
lifecycle[ method ] = function () {
OO.ui.warnDeprecation(
'Using the return value of openWindow as a promise is deprecated. ' +
'Use .openWindow( ... ).opening.' + method + '( ... ) instead.'
);
return compatOpening[ method ].apply( this, arguments );
};
} );
// Argument handling
if ( typeof win === 'string' ) {
this.getWindow( win ).then(
function ( win ) {
manager.openWindow( win, data, lifecycle, compatOpening );
},
function ( err ) {
lifecycle.deferreds.opening.reject( err );
}
);
return lifecycle;
}
// Error handling
if ( !this.hasWindow( win ) ) {
error = 'Cannot open window: window is not attached to manager';
} else if ( this.lifecycle && this.lifecycle.isOpened() ) {
error = 'Cannot open window: another window is open';
} else if ( this.preparingToOpen || ( this.lifecycle && this.lifecycle.isOpening() ) ) {
error = 'Cannot open window: another window is opening';
}
if ( error ) {
compatOpening.reject( new OO.ui.Error( error ) );
lifecycle.deferreds.opening.reject( new OO.ui.Error( error ) );
return lifecycle;
}
// If a window is currently closing, wait for it to complete
this.preparingToOpen = $.when( this.lifecycle && this.lifecycle.closed );
// Ensure handlers get called after preparingToOpen is set
this.preparingToOpen.done( function () {
if ( manager.modal ) {
manager.toggleGlobalEvents( true );
manager.toggleAriaIsolation( true );
}
manager.$returnFocusTo = data.$returnFocusTo !== undefined ? data.$returnFocusTo : $( document.activeElement );
manager.currentWindow = win;
manager.lifecycle = lifecycle;
manager.preparingToOpen = null;
manager.emit( 'opening', win, compatOpening, data );
lifecycle.deferreds.opening.resolve( data );
setTimeout( function () {
manager.compatOpened = $.Deferred();
win.setup( data ).then( function () {
manager.updateWindowSize( win );
compatOpening.notify( { state: 'setup' } );
setTimeout( function () {
win.ready( data ).then( function () {
compatOpening.notify( { state: 'ready' } );
lifecycle.deferreds.opened.resolve( data );
compatOpening.resolve( manager.compatOpened.promise(), data );
}, function () {
lifecycle.deferreds.opened.reject();
compatOpening.reject();
manager.closeWindow( win );
} );
}, manager.getReadyDelay() );
}, function () {
lifecycle.deferreds.opened.reject();
compatOpening.reject();
manager.closeWindow( win );
} );
}, manager.getSetupDelay() );
} );
return lifecycle;
};
/**
* Close a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to close
* @param {Object} [data] Window closing data
* @return {OO.ui.WindowInstance|jQuery.Promise} A lifecycle object representing this particular
* opening of the window. For backwards-compatibility, the object is also a Thenable that is resolved
* when the window is done closing (T163510).
* @fires closing
*/
OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
var error,
manager = this,
compatClosing = $.Deferred(),
lifecycle = this.lifecycle,
compatOpened;
// Argument handling
if ( typeof win === 'string' ) {
win = this.windows[ win ];
} else if ( !this.hasWindow( win ) ) {
win = null;
}
// Error handling
if ( !lifecycle ) {
error = 'Cannot close window: no window is currently open';
} else if ( !win ) {
error = 'Cannot close window: window is not attached to manager';
} else if ( win !== this.currentWindow || this.lifecycle.isClosed() ) {
error = 'Cannot close window: window already closed with different data';
} else if ( this.preparingToClose || this.lifecycle.isClosing() ) {
error = 'Cannot close window: window already closing with different data';
}
if ( error ) {
// This function was called for the wrong window and we don't want to mess with the current
// window's state.
lifecycle = new OO.ui.WindowInstance();
// Pretend the window has been opened, so that we can pretend to fail to close it.
lifecycle.deferreds.opening.resolve( {} );
lifecycle.deferreds.opened.resolve( {} );
}
// Turn lifecycle into a Thenable for backwards-compatibility with
// the deprecated nested-promise behaviour (T163510).
[ 'state', 'always', 'catch', 'pipe', 'then', 'promise', 'progress', 'done', 'fail' ]
.forEach( function ( method ) {
lifecycle[ method ] = function () {
OO.ui.warnDeprecation(
'Using the return value of closeWindow as a promise is deprecated. ' +
'Use .closeWindow( ... ).closed.' + method + '( ... ) instead.'
);
return compatClosing[ method ].apply( this, arguments );
};
} );
if ( error ) {
compatClosing.reject( new OO.ui.Error( error ) );
lifecycle.deferreds.closing.reject( new OO.ui.Error( error ) );
return lifecycle;
}
// If the window is currently opening, close it when it's done
this.preparingToClose = $.when( this.lifecycle.opened );
// Ensure handlers get called after preparingToClose is set
this.preparingToClose.always( function () {
manager.preparingToClose = null;
manager.emit( 'closing', win, compatClosing, data );
lifecycle.deferreds.closing.resolve( data );
compatOpened = manager.compatOpened;
manager.compatOpened = null;
compatOpened.resolve( compatClosing.promise(), data );
setTimeout( function () {
win.hold( data ).then( function () {
compatClosing.notify( { state: 'hold' } );
setTimeout( function () {
win.teardown( data ).then( function () {
compatClosing.notify( { state: 'teardown' } );
if ( manager.modal ) {
manager.toggleGlobalEvents( false );
manager.toggleAriaIsolation( false );
}
if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) {
manager.$returnFocusTo[ 0 ].focus();
}
manager.currentWindow = null;
manager.lifecycle = null;
lifecycle.deferreds.closed.resolve( data );
compatClosing.resolve( data );
} );
}, manager.getTeardownDelay() );
} );
}, manager.getHoldDelay() );
} );
return lifecycle;
};
/**
* Add windows to the window manager.
*
* Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
* See the [OOjs ui documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* This function can be called in two manners:
*
* 1. `.addWindows( [ windowA, windowB, ... ] )` (where `windowA`, `windowB` are OO.ui.Window objects)
*
* This syntax registers windows under the symbolic names defined in their `.static.name`
* properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling
* `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the
* static name to be set, otherwise an exception will be thrown.
*
* This is the recommended way, as it allows for an easier switch to using a window factory.
*
* 2. `.addWindows( { nameA: windowA, nameB: windowB, ... } )`
*
* This syntax registers windows under the explicitly given symbolic names. In this example,
* calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what
* its `.static.name` is set to. The static name is not required to be set.
*
* This should only be used if you need to override the default symbolic names.
*
* Example:
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* // Add a window under the default name: see OO.ui.MessageDialog.static.name
* windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
* // Add a window under an explicit name
* windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } );
*
* // Open window by default name
* windowManager.openWindow( 'message' );
* // Open window by explicitly given name
* windowManager.openWindow( 'myMessageDialog' );
*
*
* @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
* by reference, symbolic name, or explicitly defined symbolic names.
* @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
* explicit nor a statically configured symbolic name.
*/
OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
var i, len, win, name, list;
if ( Array.isArray( windows ) ) {
// Convert to map of windows by looking up symbolic names from static configuration
list = {};
for ( i = 0, len = windows.length; i < len; i++ ) {
name = windows[ i ].constructor.static.name;
if ( !name ) {
throw new Error( 'Windows must have a `name` static property defined.' );
}
list[ name ] = windows[ i ];
}
} else if ( OO.isPlainObject( windows ) ) {
list = windows;
}
// Add windows
for ( name in list ) {
win = list[ name ];
this.windows[ name ] = win.toggle( false );
this.$element.append( win.$element );
win.setManager( this );
}
};
/**
* Remove the specified windows from the windows manager.
*
* Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
* the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
* longer listens to events, use the #destroy method.
*
* @param {string[]} names Symbolic names of windows to remove
* @return {jQuery.Promise} Promise resolved when window is closed and removed
* @throws {Error} An error is thrown if the named windows are not managed by the window manager.
*/
OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
var i, len, win, name, cleanupWindow,
manager = this,
promises = [],
cleanup = function ( name, win ) {
delete manager.windows[ name ];
win.$element.detach();
};
for ( i = 0, len = names.length; i < len; i++ ) {
name = names[ i ];
win = this.windows[ name ];
if ( !win ) {
throw new Error( 'Cannot remove window' );
}
cleanupWindow = cleanup.bind( null, name, win );
promises.push( this.closeWindow( name ).closed.then( cleanupWindow, cleanupWindow ) );
}
return $.when.apply( $, promises );
};
/**
* Remove all windows from the window manager.
*
* Windows will be closed before they are removed. Note that the window manager, though not in use, will still
* listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
* To remove just a subset of windows, use the #removeWindows method.
*
* @return {jQuery.Promise} Promise resolved when all windows are closed and removed
*/
OO.ui.WindowManager.prototype.clearWindows = function () {
return this.removeWindows( Object.keys( this.windows ) );
};
/**
* Set dialog size. In general, this method should not be called directly.
*
* Fullscreen mode will be used if the dialog is too wide to fit in the screen.
*
* @param {OO.ui.Window} win Window to update, should be the current window
* @chainable
*/
OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
var isFullscreen;
// Bypass for non-current, and thus invisible, windows
if ( win !== this.currentWindow ) {
return;
}
isFullscreen = win.getSize() === 'full';
this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
win.setDimensions( win.getSizeProperties() );
this.emit( 'resize', win );
return this;
};
/**
* Bind or unbind global events for scrolling.
*
* @private
* @param {boolean} [on] Bind global events
* @chainable
*/
OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
var scrollWidth, bodyMargin,
$body = $( this.getElementDocument().body ),
// We could have multiple window managers open so only modify
// the body css at the bottom of the stack
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
on = on === undefined ? !!this.globalEvents : !!on;
if ( on ) {
if ( !this.globalEvents ) {
$( this.getElementWindow() ).on( {
// Start listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
if ( stackDepth === 0 ) {
scrollWidth = window.innerWidth - document.documentElement.clientWidth;
bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
$body.css( {
overflow: 'hidden',
'margin-right': bodyMargin + scrollWidth
} );
}
stackDepth++;
this.globalEvents = true;
}
} else if ( this.globalEvents ) {
$( this.getElementWindow() ).off( {
// Stop listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
stackDepth--;
if ( stackDepth === 0 ) {
$body.css( {
overflow: '',
'margin-right': ''
} );
}
this.globalEvents = false;
}
$body.data( 'windowManagerGlobalEvents', stackDepth );
return this;
};
/**
* Toggle screen reader visibility of content other than the window manager.
*
* @private
* @param {boolean} [isolate] Make only the window manager visible to screen readers
* @chainable
*/
OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
if ( isolate ) {
if ( !this.$ariaHidden ) {
// Hide everything other than the window manager from screen readers
this.$ariaHidden = $( 'body' )
.children()
.not( this.$element.parentsUntil( 'body' ).last() )
.attr( 'aria-hidden', '' );
}
} else if ( this.$ariaHidden ) {
// Restore screen reader visibility
this.$ariaHidden.removeAttr( 'aria-hidden' );
this.$ariaHidden = null;
}
return this;
};
/**
* Destroy the window manager.
*
* Destroying the window manager ensures that it will no longer listen to events. If you would like to
* continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
* instead.
*/
OO.ui.WindowManager.prototype.destroy = function () {
this.toggleGlobalEvents( false );
this.toggleAriaIsolation( false );
this.clearWindows();
this.$element.remove();
};
/**
* A window is a container for elements that are in a child frame. They are used with
* a window manager (OO.ui.WindowManager), which is used to open and close the window and control
* its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
* ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
* the window manager will choose a sensible fallback.
*
* The lifecycle of a window has three primary stages (opening, opened, and closing) in which
* different processes are executed:
*
* **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
* openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
* the window.
*
* - {@link #getSetupProcess} method is called and its result executed
* - {@link #getReadyProcess} method is called and its result executed
*
* **opened**: The window is now open
*
* **closing**: The closing stage begins when the window manager's
* {@link OO.ui.WindowManager#closeWindow closeWindow}
* or the window's {@link #close} methods are used, and the window manager begins to close the window.
*
* - {@link #getHoldProcess} method is called and its result executed
* - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
*
* Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
* by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
* methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
* processing can complete. Always assume window processes are executed asynchronously.
*
* For more information, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
* `full`. If omitted, the value of the {@link #static-size static size} property will be used.
*/
OO.ui.Window = function OoUiWindow( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Window.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.manager = null;
this.size = config.size || this.constructor.static.size;
this.$frame = $( '<div>' );
/**
* Overlay element to use for the `$overlay` configuration option of widgets that support it.
* Things put inside of it are overlaid on top of the window and are not bound to its dimensions.
* See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
*
* MyDialog.prototype.initialize = function () {
* ...
* var popupButton = new OO.ui.PopupButtonWidget( {
* $overlay: this.$overlay,
* label: 'Popup button',
* popup: {
* $content: $( '<p>Popup contents.</p><p>Popup contents.</p><p>Popup contents.</p>' ),
* padded: true
* }
* } );
* ...
* };
*
* @property {jQuery}
*/
this.$overlay = $( '<div>' );
this.$content = $( '<div>' );
this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
// Initialization
this.$overlay.addClass( 'oo-ui-window-overlay' );
this.$content
.addClass( 'oo-ui-window-content' )
.attr( 'tabindex', 0 );
this.$frame
.addClass( 'oo-ui-window-frame' )
.append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
this.$element
.addClass( 'oo-ui-window' )
.append( this.$frame, this.$overlay );
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.Window, OO.ui.Element );
OO.mixinClass( OO.ui.Window, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
*
* The static size is used if no #size is configured during construction.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Window.static.size = 'medium';
/* Methods */
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.Window.prototype.onMouseDown = function ( e ) {
// Prevent clicking on the click-block from stealing focus
if ( e.target === this.$element[ 0 ] ) {
return false;
}
};
/**
* Check if the window has been initialized.
*
* Initialization occurs when a window is added to a manager.
*
* @return {boolean} Window has been initialized
*/
OO.ui.Window.prototype.isInitialized = function () {
return !!this.manager;
};
/**
* Check if the window is visible.
*
* @return {boolean} Window is visible
*/
OO.ui.Window.prototype.isVisible = function () {
return this.visible;
};
/**
* Check if the window is opening.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
* method.
*
* @return {boolean} Window is opening
*/
OO.ui.Window.prototype.isOpening = function () {
return this.manager.isOpening( this );
};
/**
* Check if the window is closing.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
*
* @return {boolean} Window is closing
*/
OO.ui.Window.prototype.isClosing = function () {
return this.manager.isClosing( this );
};
/**
* Check if the window is opened.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
*
* @return {boolean} Window is opened
*/
OO.ui.Window.prototype.isOpened = function () {
return this.manager.isOpened( this );
};
/**
* Get the window manager.
*
* All windows must be attached to a window manager, which is used to open
* and close the window and control its presentation.
*
* @return {OO.ui.WindowManager} Manager of window
*/
OO.ui.Window.prototype.getManager = function () {
return this.manager;
};
/**
* Get the symbolic name of the window size (e.g., `small` or `medium`).
*
* @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
*/
OO.ui.Window.prototype.getSize = function () {
var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
sizes = this.manager.constructor.static.sizes,
size = this.size;
if ( !sizes[ size ] ) {
size = this.manager.constructor.static.defaultSize;
}
if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
size = 'full';
}
return size;
};
/**
* Get the size properties associated with the current window size
*
* @return {Object} Size properties
*/
OO.ui.Window.prototype.getSizeProperties = function () {
return this.manager.constructor.static.sizes[ this.getSize() ];
};
/**
* Disable transitions on window's frame for the duration of the callback function, then enable them
* back.
*
* @private
* @param {Function} callback Function to call while transitions are disabled
*/
OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
// We need to build the transition CSS properties using these specific properties since
// Firefox doesn't return anything useful when asked just for 'transition'.
var oldTransition = this.$frame.css( 'transition-property' ) + ' ' +
this.$frame.css( 'transition-duration' ) + ' ' +
this.$frame.css( 'transition-timing-function' ) + ' ' +
this.$frame.css( 'transition-delay' );
this.$frame.css( 'transition', 'none' );
callback();
// Force reflow to make sure the style changes done inside callback
// really are not transitioned
this.$frame.height();
this.$frame.css( 'transition', oldTransition );
};
/**
* Get the height of the full window contents (i.e., the window head, body and foot together).
*
* What consistitutes the head, body, and foot varies depending on the window type.
* A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
* and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
* and special actions in the head, and dialog content in the body.
*
* To get just the height of the dialog body, use the #getBodyHeight method.
*
* @return {number} The height of the window contents (the dialog head, body and foot) in pixels
*/
OO.ui.Window.prototype.getContentHeight = function () {
var bodyHeight,
win = this,
bodyStyleObj = this.$body[ 0 ].style,
frameStyleObj = this.$frame[ 0 ].style;
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
this.withoutSizeTransitions( function () {
var oldHeight = frameStyleObj.height,
oldPosition = bodyStyleObj.position;
frameStyleObj.height = '1px';
// Force body to resize to new width
bodyStyleObj.position = 'relative';
bodyHeight = win.getBodyHeight();
frameStyleObj.height = oldHeight;
bodyStyleObj.position = oldPosition;
} );
return (
// Add buffer for border
( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
// Use combined heights of children
( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
);
};
/**
* Get the height of the window body.
*
* To get the height of the full window contents (the window body, head, and foot together),
* use #getContentHeight.
*
* When this function is called, the window will temporarily have been resized
* to height=1px, so .scrollHeight measurements can be taken accurately.
*
* @return {number} Height of the window body in pixels
*/
OO.ui.Window.prototype.getBodyHeight = function () {
return this.$body[ 0 ].scrollHeight;
};
/**
* Get the directionality of the frame (right-to-left or left-to-right).
*
* @return {string} Directionality: `'ltr'` or `'rtl'`
*/
OO.ui.Window.prototype.getDir = function () {
return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
};
/**
* Get the 'setup' process.
*
* The setup process is used to set up a window for use in a particular context,
* based on the `data` argument. This method is called during the opening phase of the window’s
* lifecycle.
*
* Override this method to add additional steps to the ‘setup’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* To add window content that persists between openings, you may wish to use the #initialize method
* instead.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Setup process
*/
OO.ui.Window.prototype.getSetupProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘ready’ process.
*
* The ready process is used to ready a window for use in a particular
* context, based on the `data` argument. This method is called during the opening phase of
* the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
*
* Override this method to add additional steps to the ‘ready’ process the parent method
* provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
* methods of OO.ui.Process.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Ready process
*/
OO.ui.Window.prototype.getReadyProcess = function () {
return new OO.ui.Process();
};
/**
* Get the 'hold' process.
*
* The hold process is used to keep a window from being used in a particular context,
* based on the `data` argument. This method is called during the closing phase of the window’s
* lifecycle.
*
* Override this method to add additional steps to the 'hold' process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Hold process
*/
OO.ui.Window.prototype.getHoldProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘teardown’ process.
*
* The teardown process is used to teardown a window after use. During teardown,
* user interactions within the window are conveyed and the window is closed, based on the `data`
* argument. This method is called during the closing phase of the window’s lifecycle.
*
* Override this method to add additional steps to the ‘teardown’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Teardown process
*/
OO.ui.Window.prototype.getTeardownProcess = function () {
return new OO.ui.Process();
};
/**
* Set the window manager.
*
* This will cause the window to initialize. Calling it more than once will cause an error.
*
* @param {OO.ui.WindowManager} manager Manager for this window
* @throws {Error} An error is thrown if the method is called more than once
* @chainable
*/
OO.ui.Window.prototype.setManager = function ( manager ) {
if ( this.manager ) {
throw new Error( 'Cannot set window manager, window already has a manager' );
}
this.manager = manager;
this.initialize();
return this;
};
/**
* Set the window size by symbolic name (e.g., 'small' or 'medium')
*
* @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
* `full`
* @chainable
*/
OO.ui.Window.prototype.setSize = function ( size ) {
this.size = size;
this.updateSize();
return this;
};
/**
* Update the window size.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
*/
OO.ui.Window.prototype.updateSize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot update window size, must be attached to a manager' );
}
this.manager.updateWindowSize( this );
return this;
};
/**
* Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
* when the window is opening. In general, setDimensions should not be called directly.
*
* To set the size of the window, use the #setSize method.
*
* @param {Object} dim CSS dimension properties
* @param {string|number} [dim.width] Width
* @param {string|number} [dim.minWidth] Minimum width
* @param {string|number} [dim.maxWidth] Maximum width
* @param {string|number} [dim.height] Height, omit to set based on height of contents
* @param {string|number} [dim.minHeight] Minimum height
* @param {string|number} [dim.maxHeight] Maximum height
* @chainable
*/
OO.ui.Window.prototype.setDimensions = function ( dim ) {
var height,
win = this,
styleObj = this.$frame[ 0 ].style;
// Calculate the height we need to set using the correct width
if ( dim.height === undefined ) {
this.withoutSizeTransitions( function () {
var oldWidth = styleObj.width;
win.$frame.css( 'width', dim.width || '' );
height = win.getContentHeight();
styleObj.width = oldWidth;
} );
} else {
height = dim.height;
}
this.$frame.css( {
width: dim.width || '',
minWidth: dim.minWidth || '',
maxWidth: dim.maxWidth || '',
height: height || '',
minHeight: dim.minHeight || '',
maxHeight: dim.maxHeight || ''
} );
return this;
};
/**
* Initialize window contents.
*
* Before the window is opened for the first time, #initialize is called so that content that
* persists between openings can be added to the window.
*
* To set up a window with new content each time the window opens, use #getSetupProcess.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
*/
OO.ui.Window.prototype.initialize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot initialize window, must be attached to a manager' );
}
// Properties
this.$head = $( '<div>' );
this.$body = $( '<div>' );
this.$foot = $( '<div>' );
this.$document = $( this.getElementDocument() );
// Events
this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
// Initialization
this.$head.addClass( 'oo-ui-window-head' );
this.$body.addClass( 'oo-ui-window-body' );
this.$foot.addClass( 'oo-ui-window-foot' );
this.$content.append( this.$head, this.$body, this.$foot );
return this;
};
/**
* Called when someone tries to focus the hidden element at the end of the dialog.
* Sends focus back to the start of the dialog.
*
* @param {jQuery.Event} event Focus event
*/
OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
var backwards = this.$focusTrapBefore.is( event.target ),
element = OO.ui.findFocusable( this.$content, backwards );
if ( element ) {
// There's a focusable element inside the content, at the front or
// back depending on which focus trap we hit; select it.
element.focus();
} else {
// There's nothing focusable inside the content. As a fallback,
// this.$content is focusable, and focusing it will keep our focus
// properly trapped. It's not a *meaningful* focus, since it's just
// the content-div for the Window, but it's better than letting focus
// escape into the page.
this.$content.focus();
}
};
/**
* Open the window.
*
* This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
* method, which returns a promise resolved when the window is done opening.
*
* To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
* if the window fails to open. When the promise is resolved successfully, the first argument of the
* value is a new promise, which is resolved when the window begins closing.
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.open = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot open window, must be attached to a manager' );
}
return this.manager.openWindow( this, data );
};
/**
* Close the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
* which returns a closing promise resolved when the window is done closing.
*
* The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
* phase of the window’s lifecycle and can be used to specify closing behavior each time
* the window closes.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is closed
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.close = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot close window, must be attached to a manager' );
}
return this.manager.closeWindow( this, data );
};
/**
* Setup window.
*
* This is called by OO.ui.WindowManager during window opening, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is setup
*/
OO.ui.Window.prototype.setup = function ( data ) {
var win = this;
this.toggle( true );
this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
this.$focusTraps.on( 'focus', this.focusTrapHandler );
return this.getSetupProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.addClass( 'oo-ui-window-content-setup' ).width();
} );
};
/**
* Ready window.
*
* This is called by OO.ui.WindowManager during window opening, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is ready
*/
OO.ui.Window.prototype.ready = function ( data ) {
var win = this;
this.$content.focus();
return this.getReadyProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-ready' ).width();
win.$content.addClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Hold window.
*
* This is called by OO.ui.WindowManager during window closing, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is held
*/
OO.ui.Window.prototype.hold = function ( data ) {
var win = this;
return this.getHoldProcess( data ).execute().then( function () {
// Get the focused element within the window's content
var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
// Blur the focused element
if ( $focus.length ) {
$focus[ 0 ].blur();
}
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-ready' ).width();
win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Teardown window.
*
* This is called by OO.ui.WindowManager during window closing, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is torn down
*/
OO.ui.Window.prototype.teardown = function ( data ) {
var win = this;
return this.getTeardownProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
win.$focusTraps.off( 'focus', win.focusTrapHandler );
win.toggle( false );
} );
};
/**
* The Dialog class serves as the base class for the other types of dialogs.
* Unless extended to include controls, the rendered dialog box is a simple window
* that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
* which opens, closes, and controls the presentation of the window. See the
* [OOjs UI documentation on MediaWiki] [1] for more information.
*
* @example
* // A simple dialog window.
* function MyDialog( config ) {
* MyDialog.parent.call( this, config );
* }
* OO.inheritClass( MyDialog, OO.ui.Dialog );
* MyDialog.static.name = 'myDialog';
* MyDialog.prototype.initialize = function () {
* MyDialog.parent.prototype.initialize.call( this );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
* this.$body.append( this.content.$element );
* };
* MyDialog.prototype.getBodyHeight = function () {
* return this.content.$element.outerHeight( true );
* };
* var myDialog = new MyDialog( {
* size: 'medium'
* } );
* // Create and append a window manager, which opens and closes the window.
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* windowManager.addWindows( [ myDialog ] );
* // Open the window!
* windowManager.openWindow( myDialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
*
* @abstract
* @class
* @extends OO.ui.Window
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Dialog = function OoUiDialog( config ) {
// Parent constructor
OO.ui.Dialog.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this );
// Properties
this.actions = new OO.ui.ActionSet();
this.attachedActions = [];
this.currentAction = null;
this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
// Events
this.actions.connect( this, {
click: 'onActionClick',
change: 'onActionsChange'
} );
// Initialization
this.$element
.addClass( 'oo-ui-dialog' )
.attr( 'role', 'dialog' );
};
/* Setup */
OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
/* Static Properties */
/**
* Symbolic name of dialog.
*
* The dialog class must have a symbolic name in order to be registered with OO.Factory.
* Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
*
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Dialog.static.name = '';
/**
* The dialog title.
*
* The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
* that will produce a Label node or string. The title can also be specified with data passed to the
* constructor (see #getSetupProcess). In this case, the static value will be overridden.
*
* @abstract
* @static
* @inheritable
* @property {jQuery|string|Function}
*/
OO.ui.Dialog.static.title = '';
/**
* An array of configured {@link OO.ui.ActionWidget action widgets}.
*
* Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
* value will be overridden.
*
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @static
* @inheritable
* @property {Object[]}
*/
OO.ui.Dialog.static.actions = [];
/**
* Close the dialog when the 'Esc' key is pressed.
*
* @static
* @abstract
* @inheritable
* @property {boolean}
*/
OO.ui.Dialog.static.escapable = true;
/* Methods */
/**
* Handle frame document key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
var actions;
if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
this.executeAction( '' );
e.preventDefault();
e.stopPropagation();
} else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) {
actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
if ( actions.length > 0 ) {
this.executeAction( actions[ 0 ].getAction() );
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Handle action click events.
*
* @private
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
OO.ui.Dialog.prototype.onActionClick = function ( action ) {
if ( !this.isPending() ) {
this.executeAction( action.getAction() );
}
};
/**
* Handle actions change event.
*
* @private
*/
OO.ui.Dialog.prototype.onActionsChange = function () {
this.detachActions();
if ( !this.isClosing() ) {
this.attachActions();
}
};
/**
* Get the set of actions used by the dialog.
*
* @return {OO.ui.ActionSet}
*/
OO.ui.Dialog.prototype.getActions = function () {
return this.actions;
};
/**
* Get a process for taking action.
*
* When you override this method, you can create a new OO.ui.Process and return it, or add additional
* accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
* and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
*
* @param {string} [action] Symbolic name of action
* @return {OO.ui.Process} Action process
*/
OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
return new OO.ui.Process()
.next( function () {
if ( !action ) {
// An empty action always closes the dialog without data, which should always be
// safe and make no changes
this.close();
}
}, this );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
* the {@link #static-title static title}
* @param {Object[]} [data.actions] List of configuration options for each
* {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
*/
OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
.next( function () {
var config = this.constructor.static,
actions = data.actions !== undefined ? data.actions : config.actions,
title = data.title !== undefined ? data.title : config.title;
this.title.setLabel( title ).setTitle( title );
this.actions.add( this.getActionWidgets( actions ) );
this.$element.on( 'keydown', this.onDialogKeyDownHandler );
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
.first( function () {
this.$element.off( 'keydown', this.onDialogKeyDownHandler );
this.actions.clear();
this.currentAction = null;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.initialize = function () {
// Parent method
OO.ui.Dialog.parent.prototype.initialize.call( this );
// Properties
this.title = new OO.ui.LabelWidget();
// Initialization
this.$content.addClass( 'oo-ui-dialog-content' );
this.$element.attr( 'aria-labelledby', this.title.getElementId() );
this.setPendingElement( this.$head );
};
/**
* Get action widgets from a list of configs
*
* @param {Object[]} actions Action widget configs
* @return {OO.ui.ActionWidget[]} Action widgets
*/
OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
var i, len, widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
widgets.push(
new OO.ui.ActionWidget( actions[ i ] )
);
}
return widgets;
};
/**
* Attach action actions.
*
* @protected
*/
OO.ui.Dialog.prototype.attachActions = function () {
// Remember the list of potentially attached actions
this.attachedActions = this.actions.get();
};
/**
* Detach action actions.
*
* @protected
* @chainable
*/
OO.ui.Dialog.prototype.detachActions = function () {
var i, len;
// Detach all actions that may have been previously attached
for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
this.attachedActions[ i ].$element.detach();
}
this.attachedActions = [];
};
/**
* Execute an action.
*
* @param {string} action Symbolic name of action to execute
* @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
*/
OO.ui.Dialog.prototype.executeAction = function ( action ) {
this.pushPending();
this.currentAction = action;
return this.getActionProcess( action ).execute()
.always( this.popPending.bind( this ) );
};
/**
* MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
* consists of a header that contains the dialog title, a body with the message, and a footer that
* contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
* of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
*
* There are two basic types of message dialogs, confirmation and alert:
*
* - **confirmation**: the dialog title describes what a progressive action will do and the message provides
* more details about the consequences.
* - **alert**: the dialog title describes which event occurred and the message provides more information
* about why the event occurred.
*
* The MessageDialog class specifies two actions: ‘accept’, the primary
* action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
* passing along the selected action.
*
* For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example: Creating and opening a message dialog window.
* var messageDialog = new OO.ui.MessageDialog();
*
* // Create and append a window manager.
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* windowManager.addWindows( [ messageDialog ] );
* // Open the window.
* windowManager.openWindow( messageDialog, {
* title: 'Basic message dialog',
* message: 'This is the message'
* } );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
*
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
// Parent constructor
OO.ui.MessageDialog.parent.call( this, config );
// Properties
this.verticalActionLayout = null;
// Initialization
this.$element.addClass( 'oo-ui-messageDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.name = 'message';
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.size = 'small';
/**
* Dialog title.
*
* The title of a confirmation dialog describes what a progressive action will do. The
* title of an alert dialog describes which event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.title = null;
/**
* The message displayed in the dialog body.
*
* A confirmation message describes the consequences of a progressive action. An alert
* message describes why an event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.message = null;
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.actions = [
// Note that OO.ui.alert() and OO.ui.confirm() rely on these.
{ action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
{ action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
];
/* Methods */
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
// Events
this.manager.connect( this, {
resize: 'onResize'
} );
return this;
};
/**
* Handle window resized events.
*
* @private
*/
OO.ui.MessageDialog.prototype.onResize = function () {
var dialog = this;
dialog.fitActions();
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.fitActions();
}, 300 );
};
/**
* Toggle action layout between vertical and horizontal.
*
* @private
* @param {boolean} [value] Layout actions vertically, omit to toggle
* @chainable
*/
OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
value = value === undefined ? !this.verticalActionLayout : !!value;
if ( value !== this.verticalActionLayout ) {
this.verticalActionLayout = value;
this.$actions
.toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
.toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
if ( action ) {
return new OO.ui.Process( function () {
this.close( { action: action } );
}, this );
}
return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
* @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
* @param {string} [data.size] Symbolic name of the dialog size, see OO.ui.Window
* @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
* action item
*/
OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
.next( function () {
this.title.setLabel(
data.title !== undefined ? data.title : this.constructor.static.title
);
this.message.setLabel(
data.message !== undefined ? data.message : this.constructor.static.message
);
this.size = data.size !== undefined ? data.size : this.constructor.static.size;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
.next( function () {
// Focus the primary action button
var actions = this.actions.get();
actions = actions.filter( function ( action ) {
return action.getFlags().indexOf( 'primary' ) > -1;
} );
if ( actions.length > 0 ) {
actions[ 0 ].focus();
}
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getBodyHeight = function () {
var bodyHeight, oldOverflow,
$scrollable = this.container.$element;
oldOverflow = $scrollable[ 0 ].style.overflow;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
bodyHeight = this.text.$element.outerHeight( true );
$scrollable[ 0 ].style.overflow = oldOverflow;
return bodyHeight;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
var $scrollable = this.container.$element;
OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
// Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
// Need to do it after transition completes (250ms), add 50ms just in case.
setTimeout( function () {
var oldOverflow = $scrollable[ 0 ].style.overflow,
activeElement = document.activeElement;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
// Check reconsiderScrollbars didn't destroy our focus, as we
// are doing this after the ready process.
if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) {
activeElement.focus();
}
$scrollable[ 0 ].style.overflow = oldOverflow;
}, 300 );
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.initialize = function () {
// Parent method
OO.ui.MessageDialog.parent.prototype.initialize.call( this );
// Properties
this.$actions = $( '<div>' );
this.container = new OO.ui.PanelLayout( {
scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
} );
this.text = new OO.ui.PanelLayout( {
padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
} );
this.message = new OO.ui.LabelWidget( {
classes: [ 'oo-ui-messageDialog-message' ]
} );
// Initialization
this.title.$element.addClass( 'oo-ui-messageDialog-title' );
this.$content.addClass( 'oo-ui-messageDialog-content' );
this.container.$element.append( this.text.$element );
this.text.$element.append( this.title.$element, this.message.$element );
this.$body.append( this.container.$element );
this.$actions.addClass( 'oo-ui-messageDialog-actions' );
this.$foot.append( this.$actions );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.safe ) {
this.$actions.append( special.safe.$element );
special.safe.toggleFramed( false );
}
if ( others.length ) {
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$actions.append( other.$element );
other.toggleFramed( false );
}
}
if ( special.primary ) {
this.$actions.append( special.primary.$element );
special.primary.toggleFramed( false );
}
if ( !this.isOpening() ) {
// If the dialog is currently opening, this will be called automatically soon.
// This also calls #fitActions.
this.updateSize();
}
};
/**
* Fit action actions into columns or rows.
*
* Columns will be used if all labels can fit without overflow, otherwise rows will be used.
*
* @private
*/
OO.ui.MessageDialog.prototype.fitActions = function () {
var i, len, action,
previous = this.verticalActionLayout,
actions = this.actions.get();
// Detect clipping
this.toggleVerticalActionLayout( false );
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
this.toggleVerticalActionLayout( true );
break;
}
}
// Move the body out of the way of the foot
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
if ( this.verticalActionLayout !== previous ) {
// We changed the layout, window height might need to be updated.
this.updateSize();
}
};
/**
* ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
* to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
* interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
* relevant. The ProcessDialog class is always extended and customized with the actions and content
* required for each process.
*
* The process dialog box consists of a header that visually represents the ‘working’ state of long
* processes with an animation. The header contains the dialog title as well as
* two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
* a ‘primary’ action on the right (e.g., ‘Done’).
*
* Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
* Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
*
* @example
* // Example: Creating and opening a process dialog window.
* function MyProcessDialog( config ) {
* MyProcessDialog.parent.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
*
* MyProcessDialog.static.name = 'myProcessDialog';
* MyProcessDialog.static.title = 'Process dialog';
* MyProcessDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
* this.$body.append( this.content.$element );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action ) {
* return new OO.ui.Process( function () {
* dialog.close( { action: action } );
* } );
* }
* return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* var dialog = new MyProcessDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
*
* @abstract
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
// Parent constructor
OO.ui.ProcessDialog.parent.call( this, config );
// Properties
this.fitOnOpen = false;
// Initialization
this.$element.addClass( 'oo-ui-processDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
/* Methods */
/**
* Handle dismiss button click events.
*
* Hides errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
this.hideErrors();
};
/**
* Handle retry button click events.
*
* Hides errors and then tries again.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
this.hideErrors();
this.executeAction( this.currentAction );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.initialize = function () {
// Parent method
OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
// Properties
this.$navigation = $( '<div>' );
this.$location = $( '<div>' );
this.$safeActions = $( '<div>' );
this.$primaryActions = $( '<div>' );
this.$otherActions = $( '<div>' );
this.dismissButton = new OO.ui.ButtonWidget( {
label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
} );
this.retryButton = new OO.ui.ButtonWidget();
this.$errors = $( '<div>' );
this.$errorsTitle = $( '<div>' );
// Events
this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
// Initialization
this.title.$element.addClass( 'oo-ui-processDialog-title' );
this.$location
.append( this.title.$element )
.addClass( 'oo-ui-processDialog-location' );
this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
this.$errorsTitle
.addClass( 'oo-ui-processDialog-errors-title' )
.text( OO.ui.msg( 'ooui-dialog-process-error' ) );
this.$errors
.addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
.append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
this.$content
.addClass( 'oo-ui-processDialog-content' )
.append( this.$errors );
this.$navigation
.addClass( 'oo-ui-processDialog-navigation' )
// Note: Order of appends below is important. These are in the order
// we want tab to go through them. Display-order is handled entirely
// by CSS absolute-positioning. As such, primary actions like "done"
// should go first.
.append( this.$primaryActions, this.$location, this.$safeActions );
this.$head.append( this.$navigation );
this.$foot.append( this.$otherActions );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
var i, len, config,
isMobile = OO.ui.isMobile(),
widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
config = $.extend( { framed: !OO.ui.isMobile() }, actions[ i ] );
if ( isMobile &&
( config.flags === 'back' || ( Array.isArray( config.flags ) && config.flags.indexOf( 'back' ) !== -1 ) )
) {
$.extend( config, {
icon: 'previous',
label: ''
} );
}
widgets.push(
new OO.ui.ActionWidget( config )
);
}
return widgets;
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.primary ) {
this.$primaryActions.append( special.primary.$element );
}
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$otherActions.append( other.$element );
}
if ( special.safe ) {
this.$safeActions.append( special.safe.$element );
}
this.fitLabel();
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
var process = this;
return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
.fail( function ( errors ) {
process.showErrors( errors || [] );
} );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.setDimensions = function () {
// Parent method
OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
this.fitLabel();
};
/**
* Fit label between actions.
*
* @private
* @chainable
*/
OO.ui.ProcessDialog.prototype.fitLabel = function () {
var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
size = this.getSizeProperties();
if ( typeof size.width !== 'number' ) {
if ( this.isOpened() ) {
navigationWidth = this.$head.width() - 20;
} else if ( this.isOpening() ) {
if ( !this.fitOnOpen ) {
// Size is relative and the dialog isn't open yet, so wait.
// FIXME: This should ideally be handled by setup somehow.
this.manager.lifecycle.opened.done( this.fitLabel.bind( this ) );
this.fitOnOpen = true;
}
return;
} else {
return;
}
} else {
navigationWidth = size.width - 20;
}
safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
biggerWidth = Math.max( safeWidth, primaryWidth );
labelWidth = this.title.$element.width();
if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
// We have enough space to center the label
leftWidth = rightWidth = biggerWidth;
} else {
// Let's hope we at least have enough space not to overlap, because we can't wrap the label…
if ( this.getDir() === 'ltr' ) {
leftWidth = safeWidth;
rightWidth = primaryWidth;
} else {
leftWidth = primaryWidth;
rightWidth = safeWidth;
}
}
this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
return this;
};
/**
* Handle errors that occurred during accept or reject processes.
*
* @private
* @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
*/
OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
var i, len, $item, actions,
items = [],
abilities = {},
recoverable = true,
warning = false;
if ( errors instanceof OO.ui.Error ) {
errors = [ errors ];
}
for ( i = 0, len = errors.length; i < len; i++ ) {
if ( !errors[ i ].isRecoverable() ) {
recoverable = false;
}
if ( errors[ i ].isWarning() ) {
warning = true;
}
$item = $( '<div>' )
.addClass( 'oo-ui-processDialog-error' )
.append( errors[ i ].getMessage() );
items.push( $item[ 0 ] );
}
this.$errorItems = $( items );
if ( recoverable ) {
abilities[ this.currentAction ] = true;
// Copy the flags from the first matching action
actions = this.actions.get( { actions: this.currentAction } );
if ( actions.length ) {
this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
}
} else {
abilities[ this.currentAction ] = false;
this.actions.setAbilities( abilities );
}
if ( warning ) {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
} else {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
}
this.retryButton.toggle( recoverable );
this.$errorsTitle.after( this.$errorItems );
this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
};
/**
* Hide errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.hideErrors = function () {
this.$errors.addClass( 'oo-ui-element-hidden' );
if ( this.$errorItems ) {
this.$errorItems.remove();
this.$errorItems = null;
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
.first( function () {
// Make sure to hide errors
this.hideErrors();
this.fitOnOpen = false;
}, this );
};
/**
* @class OO.ui
*/
/**
* Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
* OO.ui.confirm.
*
* @private
* @return {OO.ui.WindowManager}
*/
OO.ui.getWindowManager = function () {
if ( !OO.ui.windowManager ) {
OO.ui.windowManager = new OO.ui.WindowManager();
$( 'body' ).append( OO.ui.windowManager.$element );
OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
}
return OO.ui.windowManager;
};
/**
* Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
* rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
* has only one action button, labelled "OK", clicking it will simply close the dialog.
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.alert( 'Something happened!' ).done( function () {
* console.log( 'User closed the dialog.' );
* } );
*
* OO.ui.alert( 'Something larger happened!', { size: 'large' } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog
*/
OO.ui.alert = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text,
actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
}, options ) ).closed.then( function () {
return undefined;
} );
};
/**
* Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
* (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
* if ( confirmed ) {
* console.log( 'User clicked "OK"!' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
* `false`.
*/
OO.ui.confirm = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text
}, options ) ).closed.then( function ( data ) {
return !!( data && data.action === 'accept' );
} );
};
/**
* Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has a text input widget and two action buttons, one to confirm an operation (labelled "OK")
* and one to cancel it (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.prompt( 'Choose a line to go to', { textInput: { placeholder: 'Line number' } } ).done( function ( result ) {
* if ( result !== null ) {
* console.log( 'User typed "' + result + '" then clicked "OK".' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @param {Object} [options.textInput] Additional options for text input widget, see OO.ui.TextInputWidget
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve with the value of the text input widget; otherwise, it will
* resolve to `null`.
*/
OO.ui.prompt = function ( text, options ) {
var instance,
manager = OO.ui.getWindowManager(),
textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ),
textField = new OO.ui.FieldLayout( textInput, {
align: 'top',
label: text
} );
instance = manager.openWindow( 'message', $.extend( {
message: textField.$element
}, options ) );
// TODO: This is a little hacky, and could be done by extending MessageDialog instead.
instance.opened.then( function () {
textInput.on( 'enter', function () {
manager.getCurrentWindow().close( { action: 'accept' } );
} );
textInput.focus();
} );
return instance.closed.then( function ( data ) {
return data && data.action === 'accept' ? textInput.getValue() : null;
} );
};
}( OO ) );
//# sourceMappingURL=oojs-ui-windows.js.map |
// Load modules
var Hoek = require('hoek');
var Language = require('./language');
// Declare internals
var internals = {};
internals.stringify = function (value, wrapArrays) {
var type = typeof value;
if (value === null) {
return 'null';
}
if (type === 'string') {
return value;
}
if (value instanceof internals.Err || type === 'function') {
return value.toString();
}
if (type === 'object') {
if (Array.isArray(value)) {
var partial = '';
for (var i = 0, il = value.length; i < il; ++i) {
partial += (partial.length ? ', ' : '') + internals.stringify(value[i], wrapArrays);
}
return wrapArrays ? '[' + partial + ']' : partial;
}
return value.toString();
}
return JSON.stringify(value);
};
internals.Err = function (type, context, state, options) {
this.type = type;
this.context = context || {};
this.context.key = state.key;
this.path = state.path;
this.options = options;
};
internals.Err.prototype.toString = function () {
var self = this;
var localized = this.options.language;
if (localized.label) {
this.context.key = localized.label;
}
else if (this.context.key === '' || this.context.key === null) {
this.context.key = localized.root || Language.errors.root;
}
var format = Hoek.reach(localized, this.type) || Hoek.reach(Language.errors, this.type);
var hasKey = /\{\{\!?key\}\}/.test(format);
var skipKey = format.length > 2 && format[0] === '!' && format[1] === '!';
if (skipKey) {
format = format.slice(2);
}
if (!hasKey && !skipKey) {
format = (Hoek.reach(localized, 'key') || Hoek.reach(Language.errors, 'key')) + format;
}
var wrapArrays = Hoek.reach(localized, 'messages.wrapArrays');
if (typeof wrapArrays !== 'boolean') {
wrapArrays = Language.errors.messages.wrapArrays;
}
var message = format.replace(/\{\{(\!?)([^}]+)\}\}/g, function ($0, isSecure, name) {
var value = Hoek.reach(self.context, name);
var normalized = internals.stringify(value, wrapArrays);
return (isSecure ? Hoek.escapeHtml(normalized) : normalized);
});
return message;
};
exports.create = function (type, context, state, options) {
return new internals.Err(type, context, state, options);
};
exports.process = function (errors, object) {
if (!errors || !errors.length) {
return null;
}
// Construct error
var message = '';
var details = [];
var processErrors = function (localErrors, parent) {
for (var i = 0, il = localErrors.length; i < il; ++i) {
var item = localErrors[i];
var detail = {
message: item.toString(),
path: internals.getPath(item),
type: item.type,
context: item.context
};
if (!parent) {
message += (message ? '. ' : '') + detail.message;
}
// Do not push intermediate errors, we're only interested in leafs
if (item.context.reason && item.context.reason.length) {
processErrors(item.context.reason, item.path);
}
else {
details.push(detail);
}
}
};
processErrors(errors);
var error = new Error(message);
error.name = 'ValidationError';
error.details = details;
error._object = object;
error.annotate = internals.annotate;
return error;
};
internals.getPath = function (item) {
var recursePath = function (it) {
var reachedItem = Hoek.reach(it, 'context.reason.0');
if (reachedItem && reachedItem.context) {
return recursePath(reachedItem);
}
return it.path;
};
return recursePath(item) || item.context.key;
};
// Inspired by json-stringify-safe
internals.safeStringify = function (obj, spaces) {
return JSON.stringify(obj, internals.serializer(), spaces);
};
internals.serializer = function () {
var cycleReplacer = function (key, value) {
if (stack[0] === value) {
return '[Circular ~]';
}
return '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']';
};
var keys = [], stack = [];
return function (key, value) {
if (stack.length > 0) {
var thisPos = stack.indexOf(this);
if (~thisPos) {
stack.length = thisPos + 1;
keys.length = thisPos + 1;
keys[thisPos] = key;
}
else {
stack.push(this);
keys.push(key);
}
if (~stack.indexOf(value)) {
value = cycleReplacer.call(this, key, value);
}
}
else {
stack.push(value);
}
return value;
};
};
internals.annotate = function () {
var obj = Hoek.clone(this._object || {});
var lookup = {};
var el = this.details.length;
for (var e = el - 1; e >= 0; --e) { // Reverse order to process deepest child first
var pos = el - e;
var error = this.details[e];
var path = error.path.split('.');
var ref = obj;
for (var i = 0, il = path.length; i < il && ref; ++i) {
var seg = path[i];
if (i + 1 < il) {
ref = ref[seg];
}
else {
var value = ref[seg];
if (value !== undefined) {
delete ref[seg];
var label = seg + '_$key$_' + pos + '_$end$_';
ref[label] = value;
lookup[error.path] = label;
}
else if (lookup[error.path]) {
var replacement = lookup[error.path];
var appended = replacement.replace('_$end$_', ', ' + pos + '_$end$_');
ref[appended] = ref[replacement];
lookup[error.path] = appended;
delete ref[replacement];
}
else {
ref['_$miss$_' + seg + '|' + pos + '_$end$_'] = '__missing__';
}
}
}
}
var message = internals.safeStringify(obj, 2)
.replace(/_\$key\$_([, \d]+)_\$end\$_\"/g, function ($0, $1) {
return '" \u001b[31m[' + $1 + ']\u001b[0m';
}).replace(/\"_\$miss\$_([^\|]+)\|(\d+)_\$end\$_\"\: \"__missing__\"/g, function ($0, $1, $2) {
return '\u001b[41m"' + $1 + '"\u001b[0m\u001b[31m [' + $2 + ']: -- missing --\u001b[0m';
});
message += '\n\u001b[31m';
for (e = 0; e < el; ++e) {
message += '\n[' + (e + 1) + '] ' + this.details[e].message;
}
message += '\u001b[0m';
return message;
};
|
var tedious = require("../../lib/tedious");
var Request = tedious.Request;
var TYPES = tedious.TYPES;
var common = require("../common");
var connection;
common.createBenchmark({
name: "inserting varbinary(max) with 4 bytes",
setup: function(cb) {
common.createConnection(function(_connection) {
connection = _connection;
var request = new Request("CREATE TABLE #benchmark ([value] varbinary(max))", function(err) {
if (err) return cb(err);
var request = new Request("INSERT INTO #benchmark ([value]) VALUES (@value)", cb);
request.addParameter("value", TYPES.VarBinary, new Buffer("asdf"));
connection.execSql(request);
});
connection.execSqlBatch(request);
});
},
exec: function(cb) {
var request = new Request("SELECT * FROM #benchmark", cb);
connection.execSql(request);
},
teardown: function(cb) {
var request = new Request("DROP TABLE #benchmark", function(err) {
if (err) {
return cb(err);
}
connection.close();
});
connection.execSqlBatch(request);
}
});
|
import Ember from 'ember';
const {Controller, compare, computed} = Ember;
const {equal} = computed;
// a custom sort function is needed in order to sort the posts list the same way the server would:
// status: ASC
// published_at: DESC
// updated_at: DESC
// id: DESC
function comparator(item1, item2) {
let updated1 = item1.get('updated_at');
let updated2 = item2.get('updated_at');
let idResult,
publishedAtResult,
statusResult,
updatedAtResult;
// when `updated_at` is undefined, the model is still
// being written to with the results from the server
if (item1.get('isNew') || !updated1) {
return -1;
}
if (item2.get('isNew') || !updated2) {
return 1;
}
idResult = compare(parseInt(item1.get('id')), parseInt(item2.get('id')));
statusResult = compare(item1.get('status'), item2.get('status'));
updatedAtResult = compare(updated1.valueOf(), updated2.valueOf());
publishedAtResult = publishedAtCompare(item1, item2);
if (statusResult === 0) {
if (publishedAtResult === 0) {
if (updatedAtResult === 0) {
// This should be DESC
return idResult * -1;
}
// This should be DESC
return updatedAtResult * -1;
}
// This should be DESC
return publishedAtResult * -1;
}
return statusResult;
}
function publishedAtCompare(item1, item2) {
let published1 = item1.get('published_at');
let published2 = item2.get('published_at');
if (!published1 && !published2) {
return 0;
}
if (!published1 && published2) {
return -1;
}
if (!published2 && published1) {
return 1;
}
return compare(published1.valueOf(), published2.valueOf());
}
export default Controller.extend({
// See PostsRoute's shortcuts
postListFocused: equal('keyboardFocus', 'postList'),
postContentFocused: equal('keyboardFocus', 'postContent'),
sortedPosts: computed('model.@each.status', 'model.@each.published_at', 'model.@each.isNew', 'model.@each.updated_at', function () {
let postsArray = this.get('model').toArray();
return postsArray.sort(comparator);
}),
actions: {
showPostContent(post) {
if (!post) {
return;
}
this.transitionToRoute('posts.post', post);
}
}
});
|
describe('Core_getCellMeta', function () {
var id = 'testContainer';
beforeEach(function () {
this.$container = $('<div id="' + id + '"></div>').appendTo('body');
});
afterEach(function () {
if (this.$container) {
destroy();
this.$container.remove();
}
});
it('should not allow manual editing of a read only cell', function () {
var allCellsReadOnly = false;
handsontable({
cells: function () {
return {readOnly: allCellsReadOnly}
}
});
allCellsReadOnly = true;
selectCell(2, 2);
keyDown('enter');
expect(isEditorVisible()).toEqual(false);
});
it('should allow manual editing of cell that is no longer read only', function () {
var allCellsReadOnly = true;
handsontable({
cells: function () {
return {readOnly: allCellsReadOnly};
}
});
allCellsReadOnly = false;
selectCell(2, 2);
keyDown('enter');
expect(isEditorVisible()).toEqual(true);
});
it('should move the selection to the cell below, when hitting the ENTER key on a read-only cell', function () {
handsontable({
data: Handsontable.helper.createSpreadsheetData(3,3),
cells: function () {
return {readOnly: true};
}
});
selectCell(0,0);
expect(getCellMeta(0,0).readOnly).toBe(true);
keyDown('enter');
expect(getSelected()).toEqual([1, 0, 1, 0]);
});
it('should use default cell editor for a cell that has declared only cell renderer', function () {
handsontable({
cells: function () {
return {
renderer: function (instance, td, row, col, prop, value, cellProperties) {
//taken from demo/renderers.html
Handsontable.renderers.TextRenderer.apply(this, arguments);
$(td).css({
background: 'yellow'
});
}
}
}
});
selectCell(2, 2);
keyDown('enter');
document.activeElement.value = 'new value';
destroyEditor();
expect(getDataAtCell(2, 2)).toEqual('new value');
});
it('should allow to use type and renderer in `flat` notation', function () {
handsontable({
data: [
[1, 2, 3, 4],
[5, 6, 7, 8],
[0, 9, 8, 7]
],
cells: function (row, col) {
if (row === 2 && col === 2) {
return {
type: 'checkbox',
renderer: function (instance, td, row, col, prop, value, cellProperties) {
//taken from demo/renderers.html
Handsontable.renderers.TextRenderer.apply(this, arguments);
td.style.backgroundColor = 'yellow';
}
}
}
}
});
expect(getCell(2, 2).style.backgroundColor).toEqual('yellow');
expect(getCell(1, 1).style.backgroundColor).toEqual('');
});
it('this in cells should point to cellProperties', function () {
var called = 0
, _row
, _this;
handsontable({
cells: function (row, col, prop) {
called++;
_row = row;
_this = this;
}
});
var HOT = getInstance();
expect(called).toBeGreaterThan(0);
expect(_this.row).toEqual(_row);
expect(_this.instance).toBe(HOT);
});
it("should get proper cellProperties when order of displayed rows is different than order of stored data", function () {
var hot = handsontable({
data: [
['C'],
['A'],
['B']
],
minSpareRows: 1,
cells: function (row, col, prop) {
var cellProperties = {};
if (getSourceData()[row][col] === 'A') {
cellProperties.readOnly = true;
}
return cellProperties;
}
});
expect(this.$container.find('tbody tr:eq(0) td:eq(0)').text()).toEqual('C');
expect(this.$container.find('tbody tr:eq(0) td:eq(0)').hasClass('htDimmed')).toBe(false);
expect(this.$container.find('tbody tr:eq(1) td:eq(0)').text()).toEqual('A');
expect(this.$container.find('tbody tr:eq(1) td:eq(0)').hasClass('htDimmed')).toBe(true);
expect(this.$container.find('tbody tr:eq(2) td:eq(0)').text()).toEqual('B');
expect(this.$container.find('tbody tr:eq(2) td:eq(0)').hasClass('htDimmed')).toBe(false);
//Column sorting changes the order of displayed rows while keeping table data unchanged
updateSettings({
columnSorting: {
column: 0,
sortOrder: true
}
});
expect(this.$container.find('tbody tr:eq(0) td:eq(0)').text()).toEqual('A');
expect(this.$container.find('tbody tr:eq(0) td:eq(0)').hasClass('htDimmed')).toBe(true);
expect(this.$container.find('tbody tr:eq(1) td:eq(0)').text()).toEqual('B');
expect(this.$container.find('tbody tr:eq(1) td:eq(0)').hasClass('htDimmed')).toBe(false);
expect(this.$container.find('tbody tr:eq(2) td:eq(0)').text()).toEqual('C');
expect(this.$container.find('tbody tr:eq(2) td:eq(0)').hasClass('htDimmed')).toBe(false);
});
});
|
define(
//begin v1.x content
{
"field-second": "sekund",
"field-year-relative+-1": "i fjol",
"field-week": "vecka",
"field-month-relative+-1": "förra månaden",
"field-day-relative+-1": "i går",
"field-day-relative+-2": "i förrgår",
"field-year": "år",
"field-week-relative+0": "denna vecka",
"field-week-relative+1": "nästa vecka",
"field-minute": "minut",
"field-week-relative+-1": "förra veckan",
"field-day-relative+0": "i dag",
"field-hour": "timme",
"field-day-relative+1": "i morgon",
"field-day-relative+2": "i övermorgon",
"field-day": "dag",
"field-month-relative+0": "denna månad",
"field-month-relative+1": "nästa månad",
"field-dayperiod": "fm/em",
"field-month": "månad",
"field-era": "era",
"field-year-relative+0": "i år",
"field-year-relative+1": "nästa år",
"eraAbbr": [
"Taika (645–650)",
"Hakuchi (650–671)",
"Hakuhō (672–686)",
"Shuchō (686–701)",
"Taihō (701–704)",
"Keiun (704–708)",
"Wadō (708–715)",
"Reiki (715–717)",
"Yōrō (717–724)",
"Jinki (724–729)",
"Tempyō (729–749)",
"Tempyō-kampō (749–749)",
"Tempyō-shōhō (749–757)",
"Tempyō-hōji (757–765)",
"Temphō-jingo (765–767)",
"Jingo-keiun (767–770)",
"Hōki (770–780)",
"Ten-ō (781–782)",
"Enryaku (782–806)",
"Daidō (806–810)",
"Kōnin (810–824)",
"Tenchō (824–834)",
"Jōwa (834–848)",
"Kajō (848–851)",
"Ninju (851–854)",
"Saiko (854–857)",
"Tennan (857–859)",
"Jōgan (859–877)",
"Genkei (877–885)",
"Ninna (885–889)",
"Kampyō (889–898)",
"Shōtai (898–901)",
"Engi (901–923)",
"Enchō (923–931)",
"Shōhei (931–938)",
"Tengyō (938–947)",
"Tenryaku (947–957)",
"Tentoku (957–961)",
"Ōwa (961–964)",
"Kōhō (964–968)",
"Anna (968–970)",
"Tenroku (970–973)",
"Ten-en (973–976)",
"Jōgen (976–978)",
"Tengen (978–983)",
"Eikan (983–985)",
"Kanna (985–987)",
"Ei-en (987–989)",
"Eiso (989–990)",
"Shōryaku (990–995)",
"Chōtoku (995–999)",
"Chōhō (999–1004)",
"Kankō (1004–1012)",
"Chōwa (1012–1017)",
"Kannin (1017–1021)",
"Jian (1021–1024)",
"Manju (1024–1028)",
"Chōgen (1028–1037)",
"Chōryaku (1037–1040)",
"Chōkyū (1040–1044)",
"Kantoku (1044–1046)",
"Eishō (1046–1053)",
"Tengi (1053–1058)",
"Kōhei (1058–1065)",
"Jiryaku (1065–1069)",
"Enkyū (1069–1074)",
"Shōho (1074–1077)",
"Shōryaku (1077–1081)",
"Eiho (1081–1084)",
"Ōtoku (1084–1087)",
"Kanji (1087–1094)",
"Kaho (1094–1096)",
"Eichō (1096–1097)",
"Shōtoku (1097–1099)",
"Kōwa (1099–1104)",
"Chōji (1104–1106)",
"Kashō (1106–1108)",
"Tennin (1108–1110)",
"Ten-ei (1110–1113)",
"Eikyū (1113–1118)",
"Gen-ei (1118–1120)",
"Hoan (1120–1124)",
"Tenji (1124–1126)",
"Daiji (1126–1131)",
"Tenshō (1131–1132)",
"Chōshō (1132–1135)",
"Hoen (1135–1141)",
"Eiji (1141–1142)",
"Kōji (1142–1144)",
"Tenyō (1144–1145)",
"Kyūan (1145–1151)",
"Ninpei (1151–1154)",
"Kyūju (1154–1156)",
"Hogen (1156–1159)",
"Heiji (1159–1160)",
"Eiryaku (1160–1161)",
"Ōho (1161–1163)",
"Chōkan (1163–1165)",
"Eiman (1165–1166)",
"Nin-an (1166–1169)",
"Kaō (1169–1171)",
"Shōan (1171–1175)",
"Angen (1175–1177)",
"Jishō (1177–1181)",
"Yōwa (1181–1182)",
"Juei (1182–1184)",
"Genryuku (1184–1185)",
"Bunji (1185–1190)",
"Kenkyū (1190–1199)",
"Shōji (1199–1201)",
"Kennin (1201–1204)",
"Genkyū (1204–1206)",
"Ken-ei (1206–1207)",
"Shōgen (1207–1211)",
"Kenryaku (1211–1213)",
"Kenpō (1213–1219)",
"Shōkyū (1219–1222)",
"Jōō (1222–1224)",
"Gennin (1224–1225)",
"Karoku (1225–1227)",
"Antei (1227–1229)",
"Kanki (1229–1232)",
"Jōei (1232–1233)",
"Tempuku (1233–1234)",
"Bunryaku (1234–1235)",
"Katei (1235–1238)",
"Ryakunin (1238–1239)",
"En-ō (1239–1240)",
"Ninji (1240–1243)",
"Kangen (1243–1247)",
"Hōji (1247–1249)",
"Kenchō (1249–1256)",
"Kōgen (1256–1257)",
"Shōka (1257–1259)",
"Shōgen (1259–1260)",
"Bun-ō (1260–1261)",
"Kōchō (1261–1264)",
"Bun-ei (1264–1275)",
"Kenji (1275–1278)",
"Kōan (1278–1288)",
"Shōō (1288–1293)",
"Einin (1293–1299)",
"Shōan (1299–1302)",
"Kengen (1302–1303)",
"Kagen (1303–1306)",
"Tokuji (1306–1308)",
"Enkei (1308–1311)",
"Ōchō (1311–1312)",
"Shōwa (1312–1317)",
"Bunpō (1317–1319)",
"Genō (1319–1321)",
"Genkyō (1321–1324)",
"Shōchū (1324–1326)",
"Kareki (1326–1329)",
"Gentoku (1329–1331)",
"Genkō (1331–1334)",
"Kemmu (1334–1336)",
"Engen (1336–1340)",
"Kōkoku (1340–1346)",
"Shōhei (1346–1370)",
"Kentoku (1370–1372)",
"Bunchū (1372–1375)",
"Tenju (1375–1379)",
"Kōryaku (1379–1381)",
"Kōwa (1381–1384)",
"Genchū (1384–1392)",
"Meitoku (1384–1387)",
"Kakei (1387–1389)",
"Kōō (1389–1390)",
"Meitoku (1390–1394)",
"Ōei (1394–1428)",
"Shōchō (1428–1429)",
"Eikyō (1429–1441)",
"Kakitsu (1441–1444)",
"Bun-an (1444–1449)",
"Hōtoku (1449–1452)",
"Kyōtoku (1452–1455)",
"Kōshō (1455–1457)",
"Chōroku (1457–1460)",
"Kanshō (1460–1466)",
"Bunshō (1466–1467)",
"Ōnin (1467–1469)",
"Bunmei (1469–1487)",
"Chōkyō (1487–1489)",
"Entoku (1489–1492)",
"Meiō (1492–1501)",
"Bunki (1501–1504)",
"Eishō (1504–1521)",
"Taiei (1521–1528)",
"Kyōroku (1528–1532)",
"Tenmon (1532–1555)",
"Kōji (1555–1558)",
"Eiroku (1558–1570)",
"Genki (1570–1573)",
"Tenshō (1573–1592)",
"Bunroku (1592–1596)",
"Keichō (1596–1615)",
"Genwa (1615–1624)",
"Kan-ei (1624–1644)",
"Shōho (1644–1648)",
"Keian (1648–1652)",
"Shōō (1652–1655)",
"Meiryaku (1655–1658)",
"Manji (1658–1661)",
"Kanbun (1661–1673)",
"Enpō (1673–1681)",
"Tenwa (1681–1684)",
"Jōkyō (1684–1688)",
"Genroku (1688–1704)",
"Hōei (1704–1711)",
"Shōtoku (1711–1716)",
"Kyōhō (1716–1736)",
"Genbun (1736–1741)",
"Kanpō (1741–1744)",
"Enkyō (1744–1748)",
"Kan-en (1748–1751)",
"Hōryaku (1751–1764)",
"Meiwa (1764–1772)",
"An-ei (1772–1781)",
"Tenmei (1781–1789)",
"Kansei (1789–1801)",
"Kyōwa (1801–1804)",
"Bunka (1804–1818)",
"Bunsei (1818–1830)",
"Tenpō (1830–1844)",
"Kōka (1844–1848)",
"Kaei (1848–1854)",
"Ansei (1854–1860)",
"Man-en (1860–1861)",
"Bunkyū (1861–1864)",
"Genji (1864–1865)",
"Keiō (1865–1868)",
"Meiji",
"Taishō",
"Shōwa",
"Heisei"
],
"field-weekday": "veckodag",
"field-zone": "tidszon"
}
//end v1.x content
); |
/*!
* OOjs UI v0.21.2
* https://www.mediawiki.org/wiki/OOjs_UI
*
* Copyright 2011–2017 OOjs UI Team and other contributors.
* Released under the MIT license
* http://oojs.mit-license.org
*
* Date: 2017-04-26T01:05:10Z
*/
( function ( OO ) {
'use strict';
/**
* An ActionWidget is a {@link OO.ui.ButtonWidget button widget} that executes an action.
* Action widgets are used with OO.ui.ActionSet, which manages the behavior and availability
* of the actions.
*
* Both actions and action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
* Please see the [OOjs UI documentation on MediaWiki] [1] for more information
* and examples.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @class
* @extends OO.ui.ButtonWidget
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [action] Symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
* @cfg {string[]} [modes] Symbolic names of the modes (e.g., ‘edit’ or ‘read’) in which the action
* should be made available. See the action set's {@link OO.ui.ActionSet#setMode setMode} method
* for more information about setting modes.
* @cfg {boolean} [framed=false] Render the action button with a frame
*/
OO.ui.ActionWidget = function OoUiActionWidget( config ) {
// Configuration initialization
config = $.extend( { framed: false }, config );
// Parent constructor
OO.ui.ActionWidget.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this, config );
// Properties
this.action = config.action || '';
this.modes = config.modes || [];
this.width = 0;
this.height = 0;
// Initialization
this.$element.addClass( 'oo-ui-actionWidget' );
};
/* Setup */
OO.inheritClass( OO.ui.ActionWidget, OO.ui.ButtonWidget );
OO.mixinClass( OO.ui.ActionWidget, OO.ui.mixin.PendingElement );
/* Methods */
/**
* Check if the action is configured to be available in the specified `mode`.
*
* @param {string} mode Name of mode
* @return {boolean} The action is configured with the mode
*/
OO.ui.ActionWidget.prototype.hasMode = function ( mode ) {
return this.modes.indexOf( mode ) !== -1;
};
/**
* Get the symbolic name of the action (e.g., ‘continue’ or ‘cancel’).
*
* @return {string}
*/
OO.ui.ActionWidget.prototype.getAction = function () {
return this.action;
};
/**
* Get the symbolic name of the mode or modes for which the action is configured to be available.
*
* The current mode is set with the action set's {@link OO.ui.ActionSet#setMode setMode} method.
* Only actions that are configured to be avaiable in the current mode will be visible. All other actions
* are hidden.
*
* @return {string[]}
*/
OO.ui.ActionWidget.prototype.getModes = function () {
return this.modes.slice();
};
/* eslint-disable no-unused-vars */
/**
* ActionSets manage the behavior of the {@link OO.ui.ActionWidget action widgets} that comprise them.
* Actions can be made available for specific contexts (modes) and circumstances
* (abilities). Action sets are primarily used with {@link OO.ui.Dialog Dialogs}.
*
* ActionSets contain two types of actions:
*
* - Special: Special actions are the first visible actions with special flags, such as 'safe' and 'primary', the default special flags. Additional special flags can be configured in subclasses with the static #specialFlags property.
* - Other: Other actions include all non-special visible actions.
*
* Please see the [OOjs UI documentation on MediaWiki][1] for more information.
*
* @example
* // Example: An action set used in a process dialog
* function MyProcessDialog( config ) {
* MyProcessDialog.parent.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
* MyProcessDialog.static.title = 'An action set in a process dialog';
* MyProcessDialog.static.name = 'myProcessDialog';
* // An action set that uses modes ('edit' and 'help' mode, in this example).
* MyProcessDialog.static.actions = [
* { action: 'continue', modes: 'edit', label: 'Continue', flags: [ 'primary', 'constructive' ] },
* { action: 'help', modes: 'edit', label: 'Help' },
* { modes: 'edit', label: 'Cancel', flags: 'safe' },
* { action: 'back', modes: 'help', label: 'Back', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
* this.panel1 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel1.$element.append( '<p>This dialog uses an action set (continue, help, cancel, back) configured with modes. This is edit mode. Click \'help\' to see help mode.</p>' );
* this.panel2 = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.panel2.$element.append( '<p>This is help mode. Only the \'back\' action widget is configured to be visible here. Click \'back\' to return to \'edit\' mode.</p>' );
* this.stackLayout = new OO.ui.StackLayout( {
* items: [ this.panel1, this.panel2 ]
* } );
* this.$body.append( this.stackLayout.$element );
* };
* MyProcessDialog.prototype.getSetupProcess = function ( data ) {
* return MyProcessDialog.parent.prototype.getSetupProcess.call( this, data )
* .next( function () {
* this.actions.setMode( 'edit' );
* }, this );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* if ( action === 'help' ) {
* this.actions.setMode( 'help' );
* this.stackLayout.setItem( this.panel2 );
* } else if ( action === 'back' ) {
* this.actions.setMode( 'edit' );
* this.stackLayout.setItem( this.panel1 );
* } else if ( action === 'continue' ) {
* var dialog = this;
* return new OO.ui.Process( function () {
* dialog.close();
* } );
* }
* return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
* };
* MyProcessDialog.prototype.getBodyHeight = function () {
* return this.panel1.$element.outerHeight( true );
* };
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* var dialog = new MyProcessDialog( {
* size: 'medium'
* } );
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @abstract
* @class
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ActionSet = function OoUiActionSet( config ) {
// Configuration initialization
config = config || {};
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.list = [];
this.categories = {
actions: 'getAction',
flags: 'getFlags',
modes: 'getModes'
};
this.categorized = {};
this.special = {};
this.others = [];
this.organized = false;
this.changing = false;
this.changed = false;
};
/* eslint-enable no-unused-vars */
/* Setup */
OO.mixinClass( OO.ui.ActionSet, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the flags used to identify special actions. Special actions are displayed in the
* header of a {@link OO.ui.ProcessDialog process dialog}.
* See the [OOjs UI documentation on MediaWiki][2] for more information and examples.
*
* [2]:https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.ActionSet.static.specialFlags = [ 'safe', 'primary' ];
/* Events */
/**
* @event click
*
* A 'click' event is emitted when an action is clicked.
*
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
/**
* @event add
*
* An 'add' event is emitted when actions are {@link #method-add added} to the action set.
*
* @param {OO.ui.ActionWidget[]} added Actions added
*/
/**
* @event remove
*
* A 'remove' event is emitted when actions are {@link #method-remove removed}
* or {@link #clear cleared}.
*
* @param {OO.ui.ActionWidget[]} added Actions removed
*/
/**
* @event change
*
* A 'change' event is emitted when actions are {@link #method-add added}, {@link #clear cleared},
* or {@link #method-remove removed} from the action set or when the {@link #setMode mode} is changed.
*
*/
/* Methods */
/**
* Handle action change events.
*
* @private
* @fires change
*/
OO.ui.ActionSet.prototype.onActionChange = function () {
this.organized = false;
if ( this.changing ) {
this.changed = true;
} else {
this.emit( 'change' );
}
};
/**
* Check if an action is one of the special actions.
*
* @param {OO.ui.ActionWidget} action Action to check
* @return {boolean} Action is special
*/
OO.ui.ActionSet.prototype.isSpecial = function ( action ) {
var flag;
for ( flag in this.special ) {
if ( action === this.special[ flag ] ) {
return true;
}
}
return false;
};
/**
* Get action widgets based on the specified filter: ‘actions’, ‘flags’, ‘modes’, ‘visible’,
* or ‘disabled’.
*
* @param {Object} [filters] Filters to use, omit to get all actions
* @param {string|string[]} [filters.actions] Actions that action widgets must have
* @param {string|string[]} [filters.flags] Flags that action widgets must have (e.g., 'safe')
* @param {string|string[]} [filters.modes] Modes that action widgets must have
* @param {boolean} [filters.visible] Action widgets must be visible
* @param {boolean} [filters.disabled] Action widgets must be disabled
* @return {OO.ui.ActionWidget[]} Action widgets matching all criteria
*/
OO.ui.ActionSet.prototype.get = function ( filters ) {
var i, len, list, category, actions, index, match, matches;
if ( filters ) {
this.organize();
// Collect category candidates
matches = [];
for ( category in this.categorized ) {
list = filters[ category ];
if ( list ) {
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( i = 0, len = list.length; i < len; i++ ) {
actions = this.categorized[ category ][ list[ i ] ];
if ( Array.isArray( actions ) ) {
matches.push.apply( matches, actions );
}
}
}
}
// Remove by boolean filters
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
if (
( filters.visible !== undefined && match.isVisible() !== filters.visible ) ||
( filters.disabled !== undefined && match.isDisabled() !== filters.disabled )
) {
matches.splice( i, 1 );
len--;
i--;
}
}
// Remove duplicates
for ( i = 0, len = matches.length; i < len; i++ ) {
match = matches[ i ];
index = matches.lastIndexOf( match );
while ( index !== i ) {
matches.splice( index, 1 );
len--;
index = matches.lastIndexOf( match );
}
}
return matches;
}
return this.list.slice();
};
/**
* Get 'special' actions.
*
* Special actions are the first visible action widgets with special flags, such as 'safe' and 'primary'.
* Special flags can be configured in subclasses by changing the static #specialFlags property.
*
* @return {OO.ui.ActionWidget[]|null} 'Special' action widgets.
*/
OO.ui.ActionSet.prototype.getSpecial = function () {
this.organize();
return $.extend( {}, this.special );
};
/**
* Get 'other' actions.
*
* Other actions include all non-special visible action widgets.
*
* @return {OO.ui.ActionWidget[]} 'Other' action widgets
*/
OO.ui.ActionSet.prototype.getOthers = function () {
this.organize();
return this.others.slice();
};
/**
* Set the mode (e.g., ‘edit’ or ‘view’). Only {@link OO.ui.ActionWidget#modes actions} configured
* to be available in the specified mode will be made visible. All other actions will be hidden.
*
* @param {string} mode The mode. Only actions configured to be available in the specified
* mode will be made visible.
* @chainable
* @fires toggle
* @fires change
*/
OO.ui.ActionSet.prototype.setMode = function ( mode ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.toggle( action.hasMode( mode ) );
}
this.organized = false;
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Set the abilities of the specified actions.
*
* Action widgets that are configured with the specified actions will be enabled
* or disabled based on the boolean values specified in the `actions`
* parameter.
*
* @param {Object.<string,boolean>} actions A list keyed by action name with boolean
* values that indicate whether or not the action should be enabled.
* @chainable
*/
OO.ui.ActionSet.prototype.setAbilities = function ( actions ) {
var i, len, action, item;
for ( i = 0, len = this.list.length; i < len; i++ ) {
item = this.list[ i ];
action = item.getAction();
if ( actions[ action ] !== undefined ) {
item.setDisabled( !actions[ action ] );
}
}
return this;
};
/**
* Executes a function once per action.
*
* When making changes to multiple actions, use this method instead of iterating over the actions
* manually to defer emitting a #change event until after all actions have been changed.
*
* @param {Object|null} filter Filters to use to determine which actions to iterate over; see #get
* @param {Function} callback Callback to run for each action; callback is invoked with three
* arguments: the action, the action's index, the list of actions being iterated over
* @chainable
*/
OO.ui.ActionSet.prototype.forEach = function ( filter, callback ) {
this.changed = false;
this.changing = true;
this.get( filter ).forEach( callback );
this.changing = false;
if ( this.changed ) {
this.emit( 'change' );
}
return this;
};
/**
* Add action widgets to the action set.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to add
* @chainable
* @fires add
* @fires change
*/
OO.ui.ActionSet.prototype.add = function ( actions ) {
var i, len, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
action.connect( this, {
click: [ 'emit', 'click', action ],
toggle: [ 'onActionChange' ]
} );
this.list.push( action );
}
this.organized = false;
this.emit( 'add', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove action widgets from the set.
*
* To remove all actions, you may wish to use the #clear method instead.
*
* @param {OO.ui.ActionWidget[]} actions Action widgets to remove
* @chainable
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.remove = function ( actions ) {
var i, len, index, action;
this.changing = true;
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
index = this.list.indexOf( action );
if ( index !== -1 ) {
action.disconnect( this );
this.list.splice( index, 1 );
}
}
this.organized = false;
this.emit( 'remove', actions );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Remove all action widets from the set.
*
* To remove only specified actions, use the {@link #method-remove remove} method instead.
*
* @chainable
* @fires remove
* @fires change
*/
OO.ui.ActionSet.prototype.clear = function () {
var i, len, action,
removed = this.list.slice();
this.changing = true;
for ( i = 0, len = this.list.length; i < len; i++ ) {
action = this.list[ i ];
action.disconnect( this );
}
this.list = [];
this.organized = false;
this.emit( 'remove', removed );
this.changing = false;
this.emit( 'change' );
return this;
};
/**
* Organize actions.
*
* This is called whenever organized information is requested. It will only reorganize the actions
* if something has changed since the last time it ran.
*
* @private
* @chainable
*/
OO.ui.ActionSet.prototype.organize = function () {
var i, iLen, j, jLen, flag, action, category, list, item, special,
specialFlags = this.constructor.static.specialFlags;
if ( !this.organized ) {
this.categorized = {};
this.special = {};
this.others = [];
for ( i = 0, iLen = this.list.length; i < iLen; i++ ) {
action = this.list[ i ];
if ( action.isVisible() ) {
// Populate categories
for ( category in this.categories ) {
if ( !this.categorized[ category ] ) {
this.categorized[ category ] = {};
}
list = action[ this.categories[ category ] ]();
if ( !Array.isArray( list ) ) {
list = [ list ];
}
for ( j = 0, jLen = list.length; j < jLen; j++ ) {
item = list[ j ];
if ( !this.categorized[ category ][ item ] ) {
this.categorized[ category ][ item ] = [];
}
this.categorized[ category ][ item ].push( action );
}
}
// Populate special/others
special = false;
for ( j = 0, jLen = specialFlags.length; j < jLen; j++ ) {
flag = specialFlags[ j ];
if ( !this.special[ flag ] && action.hasFlag( flag ) ) {
this.special[ flag ] = action;
special = true;
break;
}
}
if ( !special ) {
this.others.push( action );
}
}
}
this.organized = true;
}
return this;
};
/**
* Errors contain a required message (either a string or jQuery selection) that is used to describe what went wrong
* in a {@link OO.ui.Process process}. The error's #recoverable and #warning configurations are used to customize the
* appearance and functionality of the error interface.
*
* The basic error interface contains a formatted error message as well as two buttons: 'Dismiss' and 'Try again' (i.e., the error
* is 'recoverable' by default). If the error is not recoverable, the 'Try again' button will not be rendered and the widget
* that initiated the failed process will be disabled.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button, which will try the
* process again.
*
* For an example of error interfaces, please see the [OOjs UI documentation on MediaWiki][1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Processes_and_errors
*
* @class
*
* @constructor
* @param {string|jQuery} message Description of error
* @param {Object} [config] Configuration options
* @cfg {boolean} [recoverable=true] Error is recoverable.
* By default, errors are recoverable, and users can try the process again.
* @cfg {boolean} [warning=false] Error is a warning.
* If the error is a warning, the error interface will include a
* 'Dismiss' and a 'Continue' button. It is the responsibility of the developer to ensure that the warning
* is not triggered a second time if the user chooses to continue.
*/
OO.ui.Error = function OoUiError( message, config ) {
// Allow passing positional parameters inside the config object
if ( OO.isPlainObject( message ) && config === undefined ) {
config = message;
message = config.message;
}
// Configuration initialization
config = config || {};
// Properties
this.message = message instanceof jQuery ? message : String( message );
this.recoverable = config.recoverable === undefined || !!config.recoverable;
this.warning = !!config.warning;
};
/* Setup */
OO.initClass( OO.ui.Error );
/* Methods */
/**
* Check if the error is recoverable.
*
* If the error is recoverable, users are able to try the process again.
*
* @return {boolean} Error is recoverable
*/
OO.ui.Error.prototype.isRecoverable = function () {
return this.recoverable;
};
/**
* Check if the error is a warning.
*
* If the error is a warning, the error interface will include a 'Dismiss' and a 'Continue' button.
*
* @return {boolean} Error is warning
*/
OO.ui.Error.prototype.isWarning = function () {
return this.warning;
};
/**
* Get error message as DOM nodes.
*
* @return {jQuery} Error message in DOM nodes
*/
OO.ui.Error.prototype.getMessage = function () {
return this.message instanceof jQuery ?
this.message.clone() :
$( '<div>' ).text( this.message ).contents();
};
/**
* Get the error message text.
*
* @return {string} Error message
*/
OO.ui.Error.prototype.getMessageText = function () {
return this.message instanceof jQuery ? this.message.text() : this.message;
};
/**
* A Process is a list of steps that are called in sequence. The step can be a number, a jQuery promise,
* or a function:
*
* - **number**: the process will wait for the specified number of milliseconds before proceeding.
* - **promise**: the process will continue to the next step when the promise is successfully resolved
* or stop if the promise is rejected.
* - **function**: the process will execute the function. The process will stop if the function returns
* either a boolean `false` or a promise that is rejected; if the function returns a number, the process
* will wait for that number of milliseconds before proceeding.
*
* If the process fails, an {@link OO.ui.Error error} is generated. Depending on how the error is
* configured, users can dismiss the error and try the process again, or not. If a process is stopped,
* its remaining steps will not be performed.
*
* @class
*
* @constructor
* @param {number|jQuery.Promise|Function} step Number of miliseconds to wait before proceeding, promise
* that must be resolved before proceeding, or a function to execute. See #createStep for more information. see #createStep for more information
* @param {Object} [context=null] Execution context of the function. The context is ignored if the step is
* a number or promise.
*/
OO.ui.Process = function ( step, context ) {
// Properties
this.steps = [];
// Initialization
if ( step !== undefined ) {
this.next( step, context );
}
};
/* Setup */
OO.initClass( OO.ui.Process );
/* Methods */
/**
* Start the process.
*
* @return {jQuery.Promise} Promise that is resolved when all steps have successfully completed.
* If any of the steps return a promise that is rejected or a boolean false, this promise is rejected
* and any remaining steps are not performed.
*/
OO.ui.Process.prototype.execute = function () {
var i, len, promise;
/**
* Continue execution.
*
* @ignore
* @param {Array} step A function and the context it should be called in
* @return {Function} Function that continues the process
*/
function proceed( step ) {
return function () {
// Execute step in the correct context
var deferred,
result = step.callback.call( step.context );
if ( result === false ) {
// Use rejected promise for boolean false results
return $.Deferred().reject( [] ).promise();
}
if ( typeof result === 'number' ) {
if ( result < 0 ) {
throw new Error( 'Cannot go back in time: flux capacitor is out of service' );
}
// Use a delayed promise for numbers, expecting them to be in milliseconds
deferred = $.Deferred();
setTimeout( deferred.resolve, result );
return deferred.promise();
}
if ( result instanceof OO.ui.Error ) {
// Use rejected promise for error
return $.Deferred().reject( [ result ] ).promise();
}
if ( Array.isArray( result ) && result.length && result[ 0 ] instanceof OO.ui.Error ) {
// Use rejected promise for list of errors
return $.Deferred().reject( result ).promise();
}
// Duck-type the object to see if it can produce a promise
if ( result && $.isFunction( result.promise ) ) {
// Use a promise generated from the result
return result.promise();
}
// Use resolved promise for other results
return $.Deferred().resolve().promise();
};
}
if ( this.steps.length ) {
// Generate a chain reaction of promises
promise = proceed( this.steps[ 0 ] )();
for ( i = 1, len = this.steps.length; i < len; i++ ) {
promise = promise.then( proceed( this.steps[ i ] ) );
}
} else {
promise = $.Deferred().resolve().promise();
}
return promise;
};
/**
* Create a process step.
*
* @private
* @param {number|jQuery.Promise|Function} step
*
* - Number of milliseconds to wait before proceeding
* - Promise that must be resolved before proceeding
* - Function to execute
* - If the function returns a boolean false the process will stop
* - If the function returns a promise, the process will continue to the next
* step when the promise is resolved or stop if the promise is rejected
* - If the function returns a number, the process will wait for that number of
* milliseconds before proceeding
* @param {Object} [context=null] Execution context of the function. The context is
* ignored if the step is a number or promise.
* @return {Object} Step object, with `callback` and `context` properties
*/
OO.ui.Process.prototype.createStep = function ( step, context ) {
if ( typeof step === 'number' || $.isFunction( step.promise ) ) {
return {
callback: function () {
return step;
},
context: null
};
}
if ( $.isFunction( step ) ) {
return {
callback: step,
context: context
};
}
throw new Error( 'Cannot create process step: number, promise or function expected' );
};
/**
* Add step to the beginning of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.first = function ( step, context ) {
this.steps.unshift( this.createStep( step, context ) );
return this;
};
/**
* Add step to the end of the process.
*
* @inheritdoc #createStep
* @return {OO.ui.Process} this
* @chainable
*/
OO.ui.Process.prototype.next = function ( step, context ) {
this.steps.push( this.createStep( step, context ) );
return this;
};
/**
* Window managers are used to open and close {@link OO.ui.Window windows} and control their presentation.
* Managed windows are mutually exclusive. If a new window is opened while a current window is opening
* or is opened, the current window will be closed and any ongoing {@link OO.ui.Process process} will be cancelled. Windows
* themselves are persistent and—rather than being torn down when closed—can be repopulated with the
* pertinent data and reused.
*
* Over the lifecycle of a window, the window manager makes available three promises: `opening`,
* `opened`, and `closing`, which represent the primary stages of the cycle:
*
* **Opening**: the opening stage begins when the window manager’s #openWindow or a window’s
* {@link OO.ui.Window#open open} method is used, and the window manager begins to open the window.
*
* - an `opening` event is emitted with an `opening` promise
* - the #getSetupDelay method is called and the returned value is used to time a pause in execution before
* the window’s {@link OO.ui.Window#getSetupProcess getSetupProcess} method is called on the
* window and its result executed
* - a `setup` progress notification is emitted from the `opening` promise
* - the #getReadyDelay method is called the returned value is used to time a pause in execution before
* the window’s {@link OO.ui.Window#getReadyProcess getReadyProcess} method is called on the
* window and its result executed
* - a `ready` progress notification is emitted from the `opening` promise
* - the `opening` promise is resolved with an `opened` promise
*
* **Opened**: the window is now open.
*
* **Closing**: the closing stage begins when the window manager's #closeWindow or the
* window's {@link OO.ui.Window#close close} methods is used, and the window manager begins
* to close the window.
*
* - the `opened` promise is resolved with `closing` promise and a `closing` event is emitted
* - the #getHoldDelay method is called and the returned value is used to time a pause in execution before
* the window's {@link OO.ui.Window#getHoldProcess getHoldProces} method is called on the
* window and its result executed
* - a `hold` progress notification is emitted from the `closing` promise
* - the #getTeardownDelay() method is called and the returned value is used to time a pause in execution before
* the window's {@link OO.ui.Window#getTeardownProcess getTeardownProcess} method is called on the
* window and its result executed
* - a `teardown` progress notification is emitted from the `closing` promise
* - the `closing` promise is resolved. The window is now closed
*
* See the [OOjs UI documentation on MediaWiki][1] for more information.
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {OO.Factory} [factory] Window factory to use for automatic instantiation
* Note that window classes that are instantiated with a factory must have
* a {@link OO.ui.Dialog#static-name static name} property that specifies a symbolic name.
* @cfg {boolean} [modal=true] Prevent interaction outside the dialog
*/
OO.ui.WindowManager = function OoUiWindowManager( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.WindowManager.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.factory = config.factory;
this.modal = config.modal === undefined || !!config.modal;
this.windows = {};
this.opening = null;
this.opened = null;
this.closing = null;
this.preparingToOpen = null;
this.preparingToClose = null;
this.currentWindow = null;
this.globalEvents = false;
this.$returnFocusTo = null;
this.$ariaHidden = null;
this.onWindowResizeTimeout = null;
this.onWindowResizeHandler = this.onWindowResize.bind( this );
this.afterWindowResizeHandler = this.afterWindowResize.bind( this );
// Initialization
this.$element
.addClass( 'oo-ui-windowManager' )
.toggleClass( 'oo-ui-windowManager-modal', this.modal );
};
/* Setup */
OO.inheritClass( OO.ui.WindowManager, OO.ui.Element );
OO.mixinClass( OO.ui.WindowManager, OO.EventEmitter );
/* Events */
/**
* An 'opening' event is emitted when the window begins to be opened.
*
* @event opening
* @param {OO.ui.Window} win Window that's being opened
* @param {jQuery.Promise} opening An `opening` promise resolved with a value when the window is opened successfully.
* When the `opening` promise is resolved, the first argument of the value is an 'opened' promise, the second argument
* is the opening data. The `opening` promise emits `setup` and `ready` notifications when those processes are complete.
* @param {Object} data Window opening data
*/
/**
* A 'closing' event is emitted when the window begins to be closed.
*
* @event closing
* @param {OO.ui.Window} win Window that's being closed
* @param {jQuery.Promise} closing A `closing` promise is resolved with a value when the window
* is closed successfully. The promise emits `hold` and `teardown` notifications when those
* processes are complete. When the `closing` promise is resolved, the first argument of its value
* is the closing data.
* @param {Object} data Window closing data
*/
/**
* A 'resize' event is emitted when a window is resized.
*
* @event resize
* @param {OO.ui.Window} win Window that was resized
*/
/* Static Properties */
/**
* Map of the symbolic name of each window size and its CSS properties.
*
* @static
* @inheritable
* @property {Object}
*/
OO.ui.WindowManager.static.sizes = {
small: {
width: 300
},
medium: {
width: 500
},
large: {
width: 700
},
larger: {
width: 900
},
full: {
// These can be non-numeric because they are never used in calculations
width: '100%',
height: '100%'
}
};
/**
* Symbolic name of the default window size.
*
* The default size is used if the window's requested size is not recognized.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.WindowManager.static.defaultSize = 'medium';
/* Methods */
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.onWindowResize = function () {
clearTimeout( this.onWindowResizeTimeout );
this.onWindowResizeTimeout = setTimeout( this.afterWindowResizeHandler, 200 );
};
/**
* Handle window resize events.
*
* @private
* @param {jQuery.Event} e Window resize event
*/
OO.ui.WindowManager.prototype.afterWindowResize = function () {
if ( this.currentWindow ) {
this.updateWindowSize( this.currentWindow );
}
};
/**
* Check if window is opening.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opening
*/
OO.ui.WindowManager.prototype.isOpening = function ( win ) {
return win === this.currentWindow && !!this.opening && this.opening.state() === 'pending';
};
/**
* Check if window is closing.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is closing
*/
OO.ui.WindowManager.prototype.isClosing = function ( win ) {
return win === this.currentWindow && !!this.closing && this.closing.state() === 'pending';
};
/**
* Check if window is opened.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is opened
*/
OO.ui.WindowManager.prototype.isOpened = function ( win ) {
return win === this.currentWindow && !!this.opened && this.opened.state() === 'pending';
};
/**
* Check if a window is being managed.
*
* @param {OO.ui.Window} win Window to check
* @return {boolean} Window is being managed
*/
OO.ui.WindowManager.prototype.hasWindow = function ( win ) {
var name;
for ( name in this.windows ) {
if ( this.windows[ name ] === win ) {
return true;
}
}
return false;
};
/**
* Get the number of milliseconds to wait after opening begins before executing the ‘setup’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getSetupDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after setup has finished before executing the ‘ready’ process.
*
* @param {OO.ui.Window} win Window being opened
* @param {Object} [data] Window opening data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getReadyDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after closing has begun before executing the 'hold' process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getHoldDelay = function () {
return 0;
};
/**
* Get the number of milliseconds to wait after the ‘hold’ process has finished before
* executing the ‘teardown’ process.
*
* @param {OO.ui.Window} win Window being closed
* @param {Object} [data] Window closing data
* @return {number} Milliseconds to wait
*/
OO.ui.WindowManager.prototype.getTeardownDelay = function () {
return this.modal ? 250 : 0;
};
/**
* Get a window by its symbolic name.
*
* If the window is not yet instantiated and its symbolic name is recognized by a factory, it will be
* instantiated and added to the window manager automatically. Please see the [OOjs UI documentation on MediaWiki][3]
* for more information about using factories.
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @param {string} name Symbolic name of the window
* @return {jQuery.Promise} Promise resolved with matching window, or rejected with an OO.ui.Error
* @throws {Error} An error is thrown if the symbolic name is not recognized by the factory.
* @throws {Error} An error is thrown if the named window is not recognized as a managed window.
*/
OO.ui.WindowManager.prototype.getWindow = function ( name ) {
var deferred = $.Deferred(),
win = this.windows[ name ];
if ( !( win instanceof OO.ui.Window ) ) {
if ( this.factory ) {
if ( !this.factory.lookup( name ) ) {
deferred.reject( new OO.ui.Error(
'Cannot auto-instantiate window: symbolic name is unrecognized by the factory'
) );
} else {
win = this.factory.create( name );
this.addWindows( [ win ] );
deferred.resolve( win );
}
} else {
deferred.reject( new OO.ui.Error(
'Cannot get unmanaged window: symbolic name unrecognized as a managed window'
) );
}
} else {
deferred.resolve( win );
}
return deferred.promise();
};
/**
* Get current window.
*
* @return {OO.ui.Window|null} Currently opening/opened/closing window
*/
OO.ui.WindowManager.prototype.getCurrentWindow = function () {
return this.currentWindow;
};
/**
* Open a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to open
* @param {Object} [data] Window opening data
* @param {jQuery|null} [data.$returnFocusTo] Element to which the window will return focus when closed.
* Defaults the current activeElement. If set to null, focus isn't changed on close.
* @return {jQuery.Promise} An `opening` promise resolved when the window is done opening.
* See {@link #event-opening 'opening' event} for more information about `opening` promises.
* @fires opening
*/
OO.ui.WindowManager.prototype.openWindow = function ( win, data ) {
var manager = this,
opening = $.Deferred();
data = data || {};
// Argument handling
if ( typeof win === 'string' ) {
return this.getWindow( win ).then( function ( win ) {
return manager.openWindow( win, data );
} );
}
// Error handling
if ( !this.hasWindow( win ) ) {
opening.reject( new OO.ui.Error(
'Cannot open window: window is not attached to manager'
) );
} else if ( this.preparingToOpen || this.opening || this.opened ) {
opening.reject( new OO.ui.Error(
'Cannot open window: another window is opening or open'
) );
}
// Window opening
if ( opening.state() !== 'rejected' ) {
// If a window is currently closing, wait for it to complete
this.preparingToOpen = $.when( this.closing );
// Ensure handlers get called after preparingToOpen is set
this.preparingToOpen.done( function () {
if ( manager.modal ) {
manager.toggleGlobalEvents( true );
manager.toggleAriaIsolation( true );
}
manager.$returnFocusTo = data.$returnFocusTo !== undefined ? data.$returnFocusTo : $( document.activeElement );
manager.currentWindow = win;
manager.opening = opening;
manager.preparingToOpen = null;
manager.emit( 'opening', win, opening, data );
setTimeout( function () {
win.setup( data ).then( function () {
manager.updateWindowSize( win );
manager.opening.notify( { state: 'setup' } );
setTimeout( function () {
win.ready( data ).then( function () {
manager.opening.notify( { state: 'ready' } );
manager.opening = null;
manager.opened = $.Deferred();
opening.resolve( manager.opened.promise(), data );
}, function () {
manager.opening = null;
manager.opened = $.Deferred();
opening.reject();
manager.closeWindow( win );
} );
}, manager.getReadyDelay() );
}, function () {
manager.opening = null;
manager.opened = $.Deferred();
opening.reject();
manager.closeWindow( win );
} );
}, manager.getSetupDelay() );
} );
}
return opening.promise();
};
/**
* Close a window.
*
* @param {OO.ui.Window|string} win Window object or symbolic name of window to close
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} A `closing` promise resolved when the window is done closing.
* See {@link #event-closing 'closing' event} for more information about closing promises.
* @throws {Error} An error is thrown if the window is not managed by the window manager.
* @fires closing
*/
OO.ui.WindowManager.prototype.closeWindow = function ( win, data ) {
var manager = this,
closing = $.Deferred(),
opened;
// Argument handling
if ( typeof win === 'string' ) {
win = this.windows[ win ];
} else if ( !this.hasWindow( win ) ) {
win = null;
}
// Error handling
if ( !win ) {
closing.reject( new OO.ui.Error(
'Cannot close window: window is not attached to manager'
) );
} else if ( win !== this.currentWindow ) {
closing.reject( new OO.ui.Error(
'Cannot close window: window already closed with different data'
) );
} else if ( this.preparingToClose || this.closing ) {
closing.reject( new OO.ui.Error(
'Cannot close window: window already closing with different data'
) );
}
// Window closing
if ( closing.state() !== 'rejected' ) {
// If the window is currently opening, close it when it's done
this.preparingToClose = $.when( this.opening );
// Ensure handlers get called after preparingToClose is set
this.preparingToClose.always( function () {
manager.closing = closing;
manager.preparingToClose = null;
manager.emit( 'closing', win, closing, data );
opened = manager.opened;
manager.opened = null;
opened.resolve( closing.promise(), data );
setTimeout( function () {
win.hold( data ).then( function () {
closing.notify( { state: 'hold' } );
setTimeout( function () {
win.teardown( data ).then( function () {
closing.notify( { state: 'teardown' } );
if ( manager.modal ) {
manager.toggleGlobalEvents( false );
manager.toggleAriaIsolation( false );
}
if ( manager.$returnFocusTo && manager.$returnFocusTo.length ) {
manager.$returnFocusTo[ 0 ].focus();
}
manager.closing = null;
manager.currentWindow = null;
closing.resolve( data );
} );
}, manager.getTeardownDelay() );
} );
}, manager.getHoldDelay() );
} );
}
return closing.promise();
};
/**
* Add windows to the window manager.
*
* Windows can be added by reference, symbolic name, or explicitly defined symbolic names.
* See the [OOjs ui documentation on MediaWiki] [2] for examples.
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* This function can be called in two manners:
*
* 1. `.addWindows( [ windowA, windowB, ... ] )` (where `windowA`, `windowB` are OO.ui.Window objects)
*
* This syntax registers windows under the symbolic names defined in their `.static.name`
* properties. For example, if `windowA.constructor.static.name` is `'nameA'`, calling
* `.openWindow( 'nameA' )` afterwards will open the window `windowA`. This syntax requires the
* static name to be set, otherwise an exception will be thrown.
*
* This is the recommended way, as it allows for an easier switch to using a window factory.
*
* 2. `.addWindows( { nameA: windowA, nameB: windowB, ... } )`
*
* This syntax registers windows under the explicitly given symbolic names. In this example,
* calling `.openWindow( 'nameA' )` afterwards will open the window `windowA`, regardless of what
* its `.static.name` is set to. The static name is not required to be set.
*
* This should only be used if you need to override the default symbolic names.
*
* Example:
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* // Add a window under the default name: see OO.ui.MessageDialog.static.name
* windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
* // Add a window under an explicit name
* windowManager.addWindows( { myMessageDialog: new OO.ui.MessageDialog() } );
*
* // Open window by default name
* windowManager.openWindow( 'message' );
* // Open window by explicitly given name
* windowManager.openWindow( 'myMessageDialog' );
*
*
* @param {Object.<string,OO.ui.Window>|OO.ui.Window[]} windows An array of window objects specified
* by reference, symbolic name, or explicitly defined symbolic names.
* @throws {Error} An error is thrown if a window is added by symbolic name, but has neither an
* explicit nor a statically configured symbolic name.
*/
OO.ui.WindowManager.prototype.addWindows = function ( windows ) {
var i, len, win, name, list;
if ( Array.isArray( windows ) ) {
// Convert to map of windows by looking up symbolic names from static configuration
list = {};
for ( i = 0, len = windows.length; i < len; i++ ) {
name = windows[ i ].constructor.static.name;
if ( !name ) {
throw new Error( 'Windows must have a `name` static property defined.' );
}
list[ name ] = windows[ i ];
}
} else if ( OO.isPlainObject( windows ) ) {
list = windows;
}
// Add windows
for ( name in list ) {
win = list[ name ];
this.windows[ name ] = win.toggle( false );
this.$element.append( win.$element );
win.setManager( this );
}
};
/**
* Remove the specified windows from the windows manager.
*
* Windows will be closed before they are removed. If you wish to remove all windows, you may wish to use
* the #clearWindows method instead. If you no longer need the window manager and want to ensure that it no
* longer listens to events, use the #destroy method.
*
* @param {string[]} names Symbolic names of windows to remove
* @return {jQuery.Promise} Promise resolved when window is closed and removed
* @throws {Error} An error is thrown if the named windows are not managed by the window manager.
*/
OO.ui.WindowManager.prototype.removeWindows = function ( names ) {
var i, len, win, name, cleanupWindow,
manager = this,
promises = [],
cleanup = function ( name, win ) {
delete manager.windows[ name ];
win.$element.detach();
};
for ( i = 0, len = names.length; i < len; i++ ) {
name = names[ i ];
win = this.windows[ name ];
if ( !win ) {
throw new Error( 'Cannot remove window' );
}
cleanupWindow = cleanup.bind( null, name, win );
promises.push( this.closeWindow( name ).then( cleanupWindow, cleanupWindow ) );
}
return $.when.apply( $, promises );
};
/**
* Remove all windows from the window manager.
*
* Windows will be closed before they are removed. Note that the window manager, though not in use, will still
* listen to events. If the window manager will not be used again, you may wish to use the #destroy method instead.
* To remove just a subset of windows, use the #removeWindows method.
*
* @return {jQuery.Promise} Promise resolved when all windows are closed and removed
*/
OO.ui.WindowManager.prototype.clearWindows = function () {
return this.removeWindows( Object.keys( this.windows ) );
};
/**
* Set dialog size. In general, this method should not be called directly.
*
* Fullscreen mode will be used if the dialog is too wide to fit in the screen.
*
* @param {OO.ui.Window} win Window to update, should be the current window
* @chainable
*/
OO.ui.WindowManager.prototype.updateWindowSize = function ( win ) {
var isFullscreen;
// Bypass for non-current, and thus invisible, windows
if ( win !== this.currentWindow ) {
return;
}
isFullscreen = win.getSize() === 'full';
this.$element.toggleClass( 'oo-ui-windowManager-fullscreen', isFullscreen );
this.$element.toggleClass( 'oo-ui-windowManager-floating', !isFullscreen );
win.setDimensions( win.getSizeProperties() );
this.emit( 'resize', win );
return this;
};
/**
* Bind or unbind global events for scrolling.
*
* @private
* @param {boolean} [on] Bind global events
* @chainable
*/
OO.ui.WindowManager.prototype.toggleGlobalEvents = function ( on ) {
var scrollWidth, bodyMargin,
$body = $( this.getElementDocument().body ),
// We could have multiple window managers open so only modify
// the body css at the bottom of the stack
stackDepth = $body.data( 'windowManagerGlobalEvents' ) || 0;
on = on === undefined ? !!this.globalEvents : !!on;
if ( on ) {
if ( !this.globalEvents ) {
$( this.getElementWindow() ).on( {
// Start listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
if ( stackDepth === 0 ) {
scrollWidth = window.innerWidth - document.documentElement.clientWidth;
bodyMargin = parseFloat( $body.css( 'margin-right' ) ) || 0;
$body.css( {
overflow: 'hidden',
'margin-right': bodyMargin + scrollWidth
} );
}
stackDepth++;
this.globalEvents = true;
}
} else if ( this.globalEvents ) {
$( this.getElementWindow() ).off( {
// Stop listening for top-level window dimension changes
'orientationchange resize': this.onWindowResizeHandler
} );
stackDepth--;
if ( stackDepth === 0 ) {
$body.css( {
overflow: '',
'margin-right': ''
} );
}
this.globalEvents = false;
}
$body.data( 'windowManagerGlobalEvents', stackDepth );
return this;
};
/**
* Toggle screen reader visibility of content other than the window manager.
*
* @private
* @param {boolean} [isolate] Make only the window manager visible to screen readers
* @chainable
*/
OO.ui.WindowManager.prototype.toggleAriaIsolation = function ( isolate ) {
isolate = isolate === undefined ? !this.$ariaHidden : !!isolate;
if ( isolate ) {
if ( !this.$ariaHidden ) {
// Hide everything other than the window manager from screen readers
this.$ariaHidden = $( 'body' )
.children()
.not( this.$element.parentsUntil( 'body' ).last() )
.attr( 'aria-hidden', '' );
}
} else if ( this.$ariaHidden ) {
// Restore screen reader visibility
this.$ariaHidden.removeAttr( 'aria-hidden' );
this.$ariaHidden = null;
}
return this;
};
/**
* Destroy the window manager.
*
* Destroying the window manager ensures that it will no longer listen to events. If you would like to
* continue using the window manager, but wish to remove all windows from it, use the #clearWindows method
* instead.
*/
OO.ui.WindowManager.prototype.destroy = function () {
this.toggleGlobalEvents( false );
this.toggleAriaIsolation( false );
this.clearWindows();
this.$element.remove();
};
/**
* A window is a container for elements that are in a child frame. They are used with
* a window manager (OO.ui.WindowManager), which is used to open and close the window and control
* its presentation. The size of a window is specified using a symbolic name (e.g., ‘small’, ‘medium’,
* ‘large’), which is interpreted by the window manager. If the requested size is not recognized,
* the window manager will choose a sensible fallback.
*
* The lifecycle of a window has three primary stages (opening, opened, and closing) in which
* different processes are executed:
*
* **opening**: The opening stage begins when the window manager's {@link OO.ui.WindowManager#openWindow
* openWindow} or the window's {@link #open open} methods are used, and the window manager begins to open
* the window.
*
* - {@link #getSetupProcess} method is called and its result executed
* - {@link #getReadyProcess} method is called and its result executed
*
* **opened**: The window is now open
*
* **closing**: The closing stage begins when the window manager's
* {@link OO.ui.WindowManager#closeWindow closeWindow}
* or the window's {@link #close} methods are used, and the window manager begins to close the window.
*
* - {@link #getHoldProcess} method is called and its result executed
* - {@link #getTeardownProcess} method is called and its result executed. The window is now closed
*
* Each of the window's processes (setup, ready, hold, and teardown) can be extended in subclasses
* by overriding the window's #getSetupProcess, #getReadyProcess, #getHoldProcess and #getTeardownProcess
* methods. Note that each {@link OO.ui.Process process} is executed in series, so asynchronous
* processing can complete. Always assume window processes are executed asynchronously.
*
* For more information, please see the [OOjs UI documentation on MediaWiki] [1].
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows
*
* @abstract
* @class
* @extends OO.ui.Element
* @mixins OO.EventEmitter
*
* @constructor
* @param {Object} [config] Configuration options
* @cfg {string} [size] Symbolic name of the dialog size: `small`, `medium`, `large`, `larger` or
* `full`. If omitted, the value of the {@link #static-size static size} property will be used.
*/
OO.ui.Window = function OoUiWindow( config ) {
// Configuration initialization
config = config || {};
// Parent constructor
OO.ui.Window.parent.call( this, config );
// Mixin constructors
OO.EventEmitter.call( this );
// Properties
this.manager = null;
this.size = config.size || this.constructor.static.size;
this.$frame = $( '<div>' );
/**
* Overlay element to use for the `$overlay` configuration option of widgets that support it.
* Things put inside of it are overlaid on top of the window and are not bound to its dimensions.
* See <https://www.mediawiki.org/wiki/OOjs_UI/Concepts#Overlays>.
*
* MyDialog.prototype.initialize = function () {
* ...
* var popupButton = new OO.ui.PopupButtonWidget( {
* $overlay: this.$overlay,
* label: 'Popup button',
* popup: {
* $content: $( '<p>Popup contents.</p><p>Popup contents.</p><p>Popup contents.</p>' ),
* padded: true
* }
* } );
* ...
* };
*
* @property {jQuery}
*/
this.$overlay = $( '<div>' );
this.$content = $( '<div>' );
this.$focusTrapBefore = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTrapAfter = $( '<div>' ).prop( 'tabIndex', 0 );
this.$focusTraps = this.$focusTrapBefore.add( this.$focusTrapAfter );
// Initialization
this.$overlay.addClass( 'oo-ui-window-overlay' );
this.$content
.addClass( 'oo-ui-window-content' )
.attr( 'tabindex', 0 );
this.$frame
.addClass( 'oo-ui-window-frame' )
.append( this.$focusTrapBefore, this.$content, this.$focusTrapAfter );
this.$element
.addClass( 'oo-ui-window' )
.append( this.$frame, this.$overlay );
// Initially hidden - using #toggle may cause errors if subclasses override toggle with methods
// that reference properties not initialized at that time of parent class construction
// TODO: Find a better way to handle post-constructor setup
this.visible = false;
this.$element.addClass( 'oo-ui-element-hidden' );
};
/* Setup */
OO.inheritClass( OO.ui.Window, OO.ui.Element );
OO.mixinClass( OO.ui.Window, OO.EventEmitter );
/* Static Properties */
/**
* Symbolic name of the window size: `small`, `medium`, `large`, `larger` or `full`.
*
* The static size is used if no #size is configured during construction.
*
* @static
* @inheritable
* @property {string}
*/
OO.ui.Window.static.size = 'medium';
/* Methods */
/**
* Handle mouse down events.
*
* @private
* @param {jQuery.Event} e Mouse down event
*/
OO.ui.Window.prototype.onMouseDown = function ( e ) {
// Prevent clicking on the click-block from stealing focus
if ( e.target === this.$element[ 0 ] ) {
return false;
}
};
/**
* Check if the window has been initialized.
*
* Initialization occurs when a window is added to a manager.
*
* @return {boolean} Window has been initialized
*/
OO.ui.Window.prototype.isInitialized = function () {
return !!this.manager;
};
/**
* Check if the window is visible.
*
* @return {boolean} Window is visible
*/
OO.ui.Window.prototype.isVisible = function () {
return this.visible;
};
/**
* Check if the window is opening.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpening isOpening}
* method.
*
* @return {boolean} Window is opening
*/
OO.ui.Window.prototype.isOpening = function () {
return this.manager.isOpening( this );
};
/**
* Check if the window is closing.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isClosing isClosing} method.
*
* @return {boolean} Window is closing
*/
OO.ui.Window.prototype.isClosing = function () {
return this.manager.isClosing( this );
};
/**
* Check if the window is opened.
*
* This method is a wrapper around the window manager's {@link OO.ui.WindowManager#isOpened isOpened} method.
*
* @return {boolean} Window is opened
*/
OO.ui.Window.prototype.isOpened = function () {
return this.manager.isOpened( this );
};
/**
* Get the window manager.
*
* All windows must be attached to a window manager, which is used to open
* and close the window and control its presentation.
*
* @return {OO.ui.WindowManager} Manager of window
*/
OO.ui.Window.prototype.getManager = function () {
return this.manager;
};
/**
* Get the symbolic name of the window size (e.g., `small` or `medium`).
*
* @return {string} Symbolic name of the size: `small`, `medium`, `large`, `larger`, `full`
*/
OO.ui.Window.prototype.getSize = function () {
var viewport = OO.ui.Element.static.getDimensions( this.getElementWindow() ),
sizes = this.manager.constructor.static.sizes,
size = this.size;
if ( !sizes[ size ] ) {
size = this.manager.constructor.static.defaultSize;
}
if ( size !== 'full' && viewport.rect.right - viewport.rect.left < sizes[ size ].width ) {
size = 'full';
}
return size;
};
/**
* Get the size properties associated with the current window size
*
* @return {Object} Size properties
*/
OO.ui.Window.prototype.getSizeProperties = function () {
return this.manager.constructor.static.sizes[ this.getSize() ];
};
/**
* Disable transitions on window's frame for the duration of the callback function, then enable them
* back.
*
* @private
* @param {Function} callback Function to call while transitions are disabled
*/
OO.ui.Window.prototype.withoutSizeTransitions = function ( callback ) {
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
// We need to build the transition CSS properties using these specific properties since
// Firefox doesn't return anything useful when asked just for 'transition'.
var oldTransition = this.$frame.css( 'transition-property' ) + ' ' +
this.$frame.css( 'transition-duration' ) + ' ' +
this.$frame.css( 'transition-timing-function' ) + ' ' +
this.$frame.css( 'transition-delay' );
this.$frame.css( 'transition', 'none' );
callback();
// Force reflow to make sure the style changes done inside callback
// really are not transitioned
this.$frame.height();
this.$frame.css( 'transition', oldTransition );
};
/**
* Get the height of the full window contents (i.e., the window head, body and foot together).
*
* What consistitutes the head, body, and foot varies depending on the window type.
* A {@link OO.ui.MessageDialog message dialog} displays a title and message in its body,
* and any actions in the foot. A {@link OO.ui.ProcessDialog process dialog} displays a title
* and special actions in the head, and dialog content in the body.
*
* To get just the height of the dialog body, use the #getBodyHeight method.
*
* @return {number} The height of the window contents (the dialog head, body and foot) in pixels
*/
OO.ui.Window.prototype.getContentHeight = function () {
var bodyHeight,
win = this,
bodyStyleObj = this.$body[ 0 ].style,
frameStyleObj = this.$frame[ 0 ].style;
// Temporarily resize the frame so getBodyHeight() can use scrollHeight measurements.
// Disable transitions first, otherwise we'll get values from when the window was animating.
this.withoutSizeTransitions( function () {
var oldHeight = frameStyleObj.height,
oldPosition = bodyStyleObj.position;
frameStyleObj.height = '1px';
// Force body to resize to new width
bodyStyleObj.position = 'relative';
bodyHeight = win.getBodyHeight();
frameStyleObj.height = oldHeight;
bodyStyleObj.position = oldPosition;
} );
return (
// Add buffer for border
( this.$frame.outerHeight() - this.$frame.innerHeight() ) +
// Use combined heights of children
( this.$head.outerHeight( true ) + bodyHeight + this.$foot.outerHeight( true ) )
);
};
/**
* Get the height of the window body.
*
* To get the height of the full window contents (the window body, head, and foot together),
* use #getContentHeight.
*
* When this function is called, the window will temporarily have been resized
* to height=1px, so .scrollHeight measurements can be taken accurately.
*
* @return {number} Height of the window body in pixels
*/
OO.ui.Window.prototype.getBodyHeight = function () {
return this.$body[ 0 ].scrollHeight;
};
/**
* Get the directionality of the frame (right-to-left or left-to-right).
*
* @return {string} Directionality: `'ltr'` or `'rtl'`
*/
OO.ui.Window.prototype.getDir = function () {
return OO.ui.Element.static.getDir( this.$content ) || 'ltr';
};
/**
* Get the 'setup' process.
*
* The setup process is used to set up a window for use in a particular context,
* based on the `data` argument. This method is called during the opening phase of the window’s
* lifecycle.
*
* Override this method to add additional steps to the ‘setup’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* To add window content that persists between openings, you may wish to use the #initialize method
* instead.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Setup process
*/
OO.ui.Window.prototype.getSetupProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘ready’ process.
*
* The ready process is used to ready a window for use in a particular
* context, based on the `data` argument. This method is called during the opening phase of
* the window’s lifecycle, after the window has been {@link #getSetupProcess setup}.
*
* Override this method to add additional steps to the ‘ready’ process the parent method
* provides using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next}
* methods of OO.ui.Process.
*
* @param {Object} [data] Window opening data
* @return {OO.ui.Process} Ready process
*/
OO.ui.Window.prototype.getReadyProcess = function () {
return new OO.ui.Process();
};
/**
* Get the 'hold' process.
*
* The hold process is used to keep a window from being used in a particular context,
* based on the `data` argument. This method is called during the closing phase of the window’s
* lifecycle.
*
* Override this method to add additional steps to the 'hold' process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Hold process
*/
OO.ui.Window.prototype.getHoldProcess = function () {
return new OO.ui.Process();
};
/**
* Get the ‘teardown’ process.
*
* The teardown process is used to teardown a window after use. During teardown,
* user interactions within the window are conveyed and the window is closed, based on the `data`
* argument. This method is called during the closing phase of the window’s lifecycle.
*
* Override this method to add additional steps to the ‘teardown’ process the parent method provides
* using the {@link OO.ui.Process#first first} and {@link OO.ui.Process#next next} methods
* of OO.ui.Process.
*
* @param {Object} [data] Window closing data
* @return {OO.ui.Process} Teardown process
*/
OO.ui.Window.prototype.getTeardownProcess = function () {
return new OO.ui.Process();
};
/**
* Set the window manager.
*
* This will cause the window to initialize. Calling it more than once will cause an error.
*
* @param {OO.ui.WindowManager} manager Manager for this window
* @throws {Error} An error is thrown if the method is called more than once
* @chainable
*/
OO.ui.Window.prototype.setManager = function ( manager ) {
if ( this.manager ) {
throw new Error( 'Cannot set window manager, window already has a manager' );
}
this.manager = manager;
this.initialize();
return this;
};
/**
* Set the window size by symbolic name (e.g., 'small' or 'medium')
*
* @param {string} size Symbolic name of size: `small`, `medium`, `large`, `larger` or
* `full`
* @chainable
*/
OO.ui.Window.prototype.setSize = function ( size ) {
this.size = size;
this.updateSize();
return this;
};
/**
* Update the window size.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
*/
OO.ui.Window.prototype.updateSize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot update window size, must be attached to a manager' );
}
this.manager.updateWindowSize( this );
return this;
};
/**
* Set window dimensions. This method is called by the {@link OO.ui.WindowManager window manager}
* when the window is opening. In general, setDimensions should not be called directly.
*
* To set the size of the window, use the #setSize method.
*
* @param {Object} dim CSS dimension properties
* @param {string|number} [dim.width] Width
* @param {string|number} [dim.minWidth] Minimum width
* @param {string|number} [dim.maxWidth] Maximum width
* @param {string|number} [dim.height] Height, omit to set based on height of contents
* @param {string|number} [dim.minHeight] Minimum height
* @param {string|number} [dim.maxHeight] Maximum height
* @chainable
*/
OO.ui.Window.prototype.setDimensions = function ( dim ) {
var height,
win = this,
styleObj = this.$frame[ 0 ].style;
// Calculate the height we need to set using the correct width
if ( dim.height === undefined ) {
this.withoutSizeTransitions( function () {
var oldWidth = styleObj.width;
win.$frame.css( 'width', dim.width || '' );
height = win.getContentHeight();
styleObj.width = oldWidth;
} );
} else {
height = dim.height;
}
this.$frame.css( {
width: dim.width || '',
minWidth: dim.minWidth || '',
maxWidth: dim.maxWidth || '',
height: height || '',
minHeight: dim.minHeight || '',
maxHeight: dim.maxHeight || ''
} );
return this;
};
/**
* Initialize window contents.
*
* Before the window is opened for the first time, #initialize is called so that content that
* persists between openings can be added to the window.
*
* To set up a window with new content each time the window opens, use #getSetupProcess.
*
* @throws {Error} An error is thrown if the window is not attached to a window manager
* @chainable
*/
OO.ui.Window.prototype.initialize = function () {
if ( !this.manager ) {
throw new Error( 'Cannot initialize window, must be attached to a manager' );
}
// Properties
this.$head = $( '<div>' );
this.$body = $( '<div>' );
this.$foot = $( '<div>' );
this.$document = $( this.getElementDocument() );
// Events
this.$element.on( 'mousedown', this.onMouseDown.bind( this ) );
// Initialization
this.$head.addClass( 'oo-ui-window-head' );
this.$body.addClass( 'oo-ui-window-body' );
this.$foot.addClass( 'oo-ui-window-foot' );
this.$content.append( this.$head, this.$body, this.$foot );
return this;
};
/**
* Called when someone tries to focus the hidden element at the end of the dialog.
* Sends focus back to the start of the dialog.
*
* @param {jQuery.Event} event Focus event
*/
OO.ui.Window.prototype.onFocusTrapFocused = function ( event ) {
var backwards = this.$focusTrapBefore.is( event.target ),
element = OO.ui.findFocusable( this.$content, backwards );
if ( element ) {
// There's a focusable element inside the content, at the front or
// back depending on which focus trap we hit; select it.
element.focus();
} else {
// There's nothing focusable inside the content. As a fallback,
// this.$content is focusable, and focusing it will keep our focus
// properly trapped. It's not a *meaningful* focus, since it's just
// the content-div for the Window, but it's better than letting focus
// escape into the page.
this.$content.focus();
}
};
/**
* Open the window.
*
* This method is a wrapper around a call to the window manager’s {@link OO.ui.WindowManager#openWindow openWindow}
* method, which returns a promise resolved when the window is done opening.
*
* To customize the window each time it opens, use #getSetupProcess or #getReadyProcess.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved with a value when the window is opened, or rejected
* if the window fails to open. When the promise is resolved successfully, the first argument of the
* value is a new promise, which is resolved when the window begins closing.
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.open = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot open window, must be attached to a manager' );
}
return this.manager.openWindow( this, data );
};
/**
* Close the window.
*
* This method is a wrapper around a call to the window
* manager’s {@link OO.ui.WindowManager#closeWindow closeWindow} method,
* which returns a closing promise resolved when the window is done closing.
*
* The window's #getHoldProcess and #getTeardownProcess methods are called during the closing
* phase of the window’s lifecycle and can be used to specify closing behavior each time
* the window closes.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is closed
* @throws {Error} An error is thrown if the window is not attached to a window manager
*/
OO.ui.Window.prototype.close = function ( data ) {
if ( !this.manager ) {
throw new Error( 'Cannot close window, must be attached to a manager' );
}
return this.manager.closeWindow( this, data );
};
/**
* Setup window.
*
* This is called by OO.ui.WindowManager during window opening, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is setup
*/
OO.ui.Window.prototype.setup = function ( data ) {
var win = this;
this.toggle( true );
this.focusTrapHandler = OO.ui.bind( this.onFocusTrapFocused, this );
this.$focusTraps.on( 'focus', this.focusTrapHandler );
return this.getSetupProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.addClass( 'oo-ui-window-content-setup' ).width();
} );
};
/**
* Ready window.
*
* This is called by OO.ui.WindowManager during window opening, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window opening data
* @return {jQuery.Promise} Promise resolved when window is ready
*/
OO.ui.Window.prototype.ready = function ( data ) {
var win = this;
this.$content.focus();
return this.getReadyProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.addClass( 'oo-ui-window-ready' ).width();
win.$content.addClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Hold window.
*
* This is called by OO.ui.WindowManager during window closing, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is held
*/
OO.ui.Window.prototype.hold = function ( data ) {
var win = this;
return this.getHoldProcess( data ).execute().then( function () {
// Get the focused element within the window's content
var $focus = win.$content.find( OO.ui.Element.static.getDocument( win.$content ).activeElement );
// Blur the focused element
if ( $focus.length ) {
$focus[ 0 ].blur();
}
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-ready' ).width();
win.$content.removeClass( 'oo-ui-window-content-ready' ).width();
} );
};
/**
* Teardown window.
*
* This is called by OO.ui.WindowManager during window closing, and should not be called directly
* by other systems.
*
* @param {Object} [data] Window closing data
* @return {jQuery.Promise} Promise resolved when window is torn down
*/
OO.ui.Window.prototype.teardown = function ( data ) {
var win = this;
return this.getTeardownProcess( data ).execute().then( function () {
// Force redraw by asking the browser to measure the elements' widths
win.$element.removeClass( 'oo-ui-window-active oo-ui-window-setup' ).width();
win.$content.removeClass( 'oo-ui-window-content-setup' ).width();
win.$focusTraps.off( 'focus', win.focusTrapHandler );
win.toggle( false );
} );
};
/**
* The Dialog class serves as the base class for the other types of dialogs.
* Unless extended to include controls, the rendered dialog box is a simple window
* that users can close by hitting the ‘Esc’ key. Dialog windows are used with OO.ui.WindowManager,
* which opens, closes, and controls the presentation of the window. See the
* [OOjs UI documentation on MediaWiki] [1] for more information.
*
* @example
* // A simple dialog window.
* function MyDialog( config ) {
* MyDialog.parent.call( this, config );
* }
* OO.inheritClass( MyDialog, OO.ui.Dialog );
* MyDialog.static.name = 'myDialog';
* MyDialog.prototype.initialize = function () {
* MyDialog.parent.prototype.initialize.call( this );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>A simple dialog window. Press \'Esc\' to close.</p>' );
* this.$body.append( this.content.$element );
* };
* MyDialog.prototype.getBodyHeight = function () {
* return this.content.$element.outerHeight( true );
* };
* var myDialog = new MyDialog( {
* size: 'medium'
* } );
* // Create and append a window manager, which opens and closes the window.
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* windowManager.addWindows( [ myDialog ] );
* // Open the window!
* windowManager.openWindow( myDialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Dialogs
*
* @abstract
* @class
* @extends OO.ui.Window
* @mixins OO.ui.mixin.PendingElement
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.Dialog = function OoUiDialog( config ) {
// Parent constructor
OO.ui.Dialog.parent.call( this, config );
// Mixin constructors
OO.ui.mixin.PendingElement.call( this );
// Properties
this.actions = new OO.ui.ActionSet();
this.attachedActions = [];
this.currentAction = null;
this.onDialogKeyDownHandler = this.onDialogKeyDown.bind( this );
// Events
this.actions.connect( this, {
click: 'onActionClick',
change: 'onActionsChange'
} );
// Initialization
this.$element
.addClass( 'oo-ui-dialog' )
.attr( 'role', 'dialog' );
};
/* Setup */
OO.inheritClass( OO.ui.Dialog, OO.ui.Window );
OO.mixinClass( OO.ui.Dialog, OO.ui.mixin.PendingElement );
/* Static Properties */
/**
* Symbolic name of dialog.
*
* The dialog class must have a symbolic name in order to be registered with OO.Factory.
* Please see the [OOjs UI documentation on MediaWiki] [3] for more information.
*
* [3]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Window_managers
*
* @abstract
* @static
* @inheritable
* @property {string}
*/
OO.ui.Dialog.static.name = '';
/**
* The dialog title.
*
* The title can be specified as a plaintext string, a {@link OO.ui.mixin.LabelElement Label} node, or a function
* that will produce a Label node or string. The title can also be specified with data passed to the
* constructor (see #getSetupProcess). In this case, the static value will be overridden.
*
* @abstract
* @static
* @inheritable
* @property {jQuery|string|Function}
*/
OO.ui.Dialog.static.title = '';
/**
* An array of configured {@link OO.ui.ActionWidget action widgets}.
*
* Actions can also be specified with data passed to the constructor (see #getSetupProcess). In this case, the static
* value will be overridden.
*
* [2]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs#Action_sets
*
* @static
* @inheritable
* @property {Object[]}
*/
OO.ui.Dialog.static.actions = [];
/**
* Close the dialog when the 'Esc' key is pressed.
*
* @static
* @abstract
* @inheritable
* @property {boolean}
*/
OO.ui.Dialog.static.escapable = true;
/* Methods */
/**
* Handle frame document key down events.
*
* @private
* @param {jQuery.Event} e Key down event
*/
OO.ui.Dialog.prototype.onDialogKeyDown = function ( e ) {
var actions;
if ( e.which === OO.ui.Keys.ESCAPE && this.constructor.static.escapable ) {
this.executeAction( '' );
e.preventDefault();
e.stopPropagation();
} else if ( e.which === OO.ui.Keys.ENTER && ( e.ctrlKey || e.metaKey ) ) {
actions = this.actions.get( { flags: 'primary', visible: true, disabled: false } );
if ( actions.length > 0 ) {
this.executeAction( actions[ 0 ].getAction() );
e.preventDefault();
e.stopPropagation();
}
}
};
/**
* Handle action click events.
*
* @private
* @param {OO.ui.ActionWidget} action Action that was clicked
*/
OO.ui.Dialog.prototype.onActionClick = function ( action ) {
if ( !this.isPending() ) {
this.executeAction( action.getAction() );
}
};
/**
* Handle actions change event.
*
* @private
*/
OO.ui.Dialog.prototype.onActionsChange = function () {
this.detachActions();
if ( !this.isClosing() ) {
this.attachActions();
}
};
/**
* Get the set of actions used by the dialog.
*
* @return {OO.ui.ActionSet}
*/
OO.ui.Dialog.prototype.getActions = function () {
return this.actions;
};
/**
* Get a process for taking action.
*
* When you override this method, you can create a new OO.ui.Process and return it, or add additional
* accept steps to the process the parent method provides using the {@link OO.ui.Process#first 'first'}
* and {@link OO.ui.Process#next 'next'} methods of OO.ui.Process.
*
* @param {string} [action] Symbolic name of action
* @return {OO.ui.Process} Action process
*/
OO.ui.Dialog.prototype.getActionProcess = function ( action ) {
return new OO.ui.Process()
.next( function () {
if ( !action ) {
// An empty action always closes the dialog without data, which should always be
// safe and make no changes
this.close();
}
}, this );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Dialog title, omit to use
* the {@link #static-title static title}
* @param {Object[]} [data.actions] List of configuration options for each
* {@link OO.ui.ActionWidget action widget}, omit to use {@link #static-actions static actions}.
*/
OO.ui.Dialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.Dialog.parent.prototype.getSetupProcess.call( this, data )
.next( function () {
var config = this.constructor.static,
actions = data.actions !== undefined ? data.actions : config.actions,
title = data.title !== undefined ? data.title : config.title;
this.title.setLabel( title ).setTitle( title );
this.actions.add( this.getActionWidgets( actions ) );
this.$element.on( 'keydown', this.onDialogKeyDownHandler );
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.Dialog.parent.prototype.getTeardownProcess.call( this, data )
.first( function () {
this.$element.off( 'keydown', this.onDialogKeyDownHandler );
this.actions.clear();
this.currentAction = null;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.Dialog.prototype.initialize = function () {
// Parent method
OO.ui.Dialog.parent.prototype.initialize.call( this );
// Properties
this.title = new OO.ui.LabelWidget();
// Initialization
this.$content.addClass( 'oo-ui-dialog-content' );
this.$element.attr( 'aria-labelledby', this.title.getElementId() );
this.setPendingElement( this.$head );
};
/**
* Get action widgets from a list of configs
*
* @param {Object[]} actions Action widget configs
* @return {OO.ui.ActionWidget[]} Action widgets
*/
OO.ui.Dialog.prototype.getActionWidgets = function ( actions ) {
var i, len, widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
widgets.push(
new OO.ui.ActionWidget( actions[ i ] )
);
}
return widgets;
};
/**
* Attach action actions.
*
* @protected
*/
OO.ui.Dialog.prototype.attachActions = function () {
// Remember the list of potentially attached actions
this.attachedActions = this.actions.get();
};
/**
* Detach action actions.
*
* @protected
* @chainable
*/
OO.ui.Dialog.prototype.detachActions = function () {
var i, len;
// Detach all actions that may have been previously attached
for ( i = 0, len = this.attachedActions.length; i < len; i++ ) {
this.attachedActions[ i ].$element.detach();
}
this.attachedActions = [];
};
/**
* Execute an action.
*
* @param {string} action Symbolic name of action to execute
* @return {jQuery.Promise} Promise resolved when action completes, rejected if it fails
*/
OO.ui.Dialog.prototype.executeAction = function ( action ) {
this.pushPending();
this.currentAction = action;
return this.getActionProcess( action ).execute()
.always( this.popPending.bind( this ) );
};
/**
* MessageDialogs display a confirmation or alert message. By default, the rendered dialog box
* consists of a header that contains the dialog title, a body with the message, and a footer that
* contains any {@link OO.ui.ActionWidget action widgets}. The MessageDialog class is the only type
* of {@link OO.ui.Dialog dialog} that is usually instantiated directly.
*
* There are two basic types of message dialogs, confirmation and alert:
*
* - **confirmation**: the dialog title describes what a progressive action will do and the message provides
* more details about the consequences.
* - **alert**: the dialog title describes which event occurred and the message provides more information
* about why the event occurred.
*
* The MessageDialog class specifies two actions: ‘accept’, the primary
* action (e.g., ‘ok’) and ‘reject,’ the safe action (e.g., ‘cancel’). Both will close the window,
* passing along the selected action.
*
* For more information and examples, please see the [OOjs UI documentation on MediaWiki][1].
*
* @example
* // Example: Creating and opening a message dialog window.
* var messageDialog = new OO.ui.MessageDialog();
*
* // Create and append a window manager.
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
* windowManager.addWindows( [ messageDialog ] );
* // Open the window.
* windowManager.openWindow( messageDialog, {
* title: 'Basic message dialog',
* message: 'This is the message'
* } );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Message_Dialogs
*
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.MessageDialog = function OoUiMessageDialog( config ) {
// Parent constructor
OO.ui.MessageDialog.parent.call( this, config );
// Properties
this.verticalActionLayout = null;
// Initialization
this.$element.addClass( 'oo-ui-messageDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.MessageDialog, OO.ui.Dialog );
/* Static Properties */
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.name = 'message';
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.size = 'small';
/**
* Dialog title.
*
* The title of a confirmation dialog describes what a progressive action will do. The
* title of an alert dialog describes which event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.title = null;
/**
* The message displayed in the dialog body.
*
* A confirmation message describes the consequences of a progressive action. An alert
* message describes why an event occurred.
*
* @static
* @inheritable
* @property {jQuery|string|Function|null}
*/
OO.ui.MessageDialog.static.message = null;
/**
* @static
* @inheritdoc
*/
OO.ui.MessageDialog.static.actions = [
// Note that OO.ui.alert() and OO.ui.confirm() rely on these.
{ action: 'accept', label: OO.ui.deferMsg( 'ooui-dialog-message-accept' ), flags: 'primary' },
{ action: 'reject', label: OO.ui.deferMsg( 'ooui-dialog-message-reject' ), flags: 'safe' }
];
/* Methods */
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setManager = function ( manager ) {
OO.ui.MessageDialog.parent.prototype.setManager.call( this, manager );
// Events
this.manager.connect( this, {
resize: 'onResize'
} );
return this;
};
/**
* Handle window resized events.
*
* @private
*/
OO.ui.MessageDialog.prototype.onResize = function () {
var dialog = this;
dialog.fitActions();
// Wait for CSS transition to finish and do it again :(
setTimeout( function () {
dialog.fitActions();
}, 300 );
};
/**
* Toggle action layout between vertical and horizontal.
*
* @private
* @param {boolean} [value] Layout actions vertically, omit to toggle
* @chainable
*/
OO.ui.MessageDialog.prototype.toggleVerticalActionLayout = function ( value ) {
value = value === undefined ? !this.verticalActionLayout : !!value;
if ( value !== this.verticalActionLayout ) {
this.verticalActionLayout = value;
this.$actions
.toggleClass( 'oo-ui-messageDialog-actions-vertical', value )
.toggleClass( 'oo-ui-messageDialog-actions-horizontal', !value );
}
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getActionProcess = function ( action ) {
if ( action ) {
return new OO.ui.Process( function () {
this.close( { action: action } );
}, this );
}
return OO.ui.MessageDialog.parent.prototype.getActionProcess.call( this, action );
};
/**
* @inheritdoc
*
* @param {Object} [data] Dialog opening data
* @param {jQuery|string|Function|null} [data.title] Description of the action being confirmed
* @param {jQuery|string|Function|null} [data.message] Description of the action's consequence
* @param {string} [data.size] Symbolic name of the dialog size, see OO.ui.Window
* @param {Object[]} [data.actions] List of OO.ui.ActionOptionWidget configuration options for each
* action item
*/
OO.ui.MessageDialog.prototype.getSetupProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.parent.prototype.getSetupProcess.call( this, data )
.next( function () {
this.title.setLabel(
data.title !== undefined ? data.title : this.constructor.static.title
);
this.message.setLabel(
data.message !== undefined ? data.message : this.constructor.static.message
);
this.size = data.size !== undefined ? data.size : this.constructor.static.size;
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getReadyProcess = function ( data ) {
data = data || {};
// Parent method
return OO.ui.MessageDialog.parent.prototype.getReadyProcess.call( this, data )
.next( function () {
// Focus the primary action button
var actions = this.actions.get();
actions = actions.filter( function ( action ) {
return action.getFlags().indexOf( 'primary' ) > -1;
} );
if ( actions.length > 0 ) {
actions[ 0 ].$button.focus();
}
}, this );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.getBodyHeight = function () {
var bodyHeight, oldOverflow,
$scrollable = this.container.$element;
oldOverflow = $scrollable[ 0 ].style.overflow;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
bodyHeight = this.text.$element.outerHeight( true );
$scrollable[ 0 ].style.overflow = oldOverflow;
return bodyHeight;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.setDimensions = function ( dim ) {
var $scrollable = this.container.$element;
OO.ui.MessageDialog.parent.prototype.setDimensions.call( this, dim );
// Twiddle the overflow property, otherwise an unnecessary scrollbar will be produced.
// Need to do it after transition completes (250ms), add 50ms just in case.
setTimeout( function () {
var oldOverflow = $scrollable[ 0 ].style.overflow,
activeElement = document.activeElement;
$scrollable[ 0 ].style.overflow = 'hidden';
OO.ui.Element.static.reconsiderScrollbars( $scrollable[ 0 ] );
// Check reconsiderScrollbars didn't destroy our focus, as we
// are doing this after the ready process.
if ( activeElement && activeElement !== document.activeElement && activeElement.focus ) {
activeElement.focus();
}
$scrollable[ 0 ].style.overflow = oldOverflow;
}, 300 );
return this;
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.initialize = function () {
// Parent method
OO.ui.MessageDialog.parent.prototype.initialize.call( this );
// Properties
this.$actions = $( '<div>' );
this.container = new OO.ui.PanelLayout( {
scrollable: true, classes: [ 'oo-ui-messageDialog-container' ]
} );
this.text = new OO.ui.PanelLayout( {
padded: true, expanded: false, classes: [ 'oo-ui-messageDialog-text' ]
} );
this.message = new OO.ui.LabelWidget( {
classes: [ 'oo-ui-messageDialog-message' ]
} );
// Initialization
this.title.$element.addClass( 'oo-ui-messageDialog-title' );
this.$content.addClass( 'oo-ui-messageDialog-content' );
this.container.$element.append( this.text.$element );
this.text.$element.append( this.title.$element, this.message.$element );
this.$body.append( this.container.$element );
this.$actions.addClass( 'oo-ui-messageDialog-actions' );
this.$foot.append( this.$actions );
};
/**
* @inheritdoc
*/
OO.ui.MessageDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.MessageDialog.parent.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.safe ) {
this.$actions.append( special.safe.$element );
special.safe.toggleFramed( false );
}
if ( others.length ) {
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$actions.append( other.$element );
other.toggleFramed( false );
}
}
if ( special.primary ) {
this.$actions.append( special.primary.$element );
special.primary.toggleFramed( false );
}
if ( !this.isOpening() ) {
// If the dialog is currently opening, this will be called automatically soon.
// This also calls #fitActions.
this.updateSize();
}
};
/**
* Fit action actions into columns or rows.
*
* Columns will be used if all labels can fit without overflow, otherwise rows will be used.
*
* @private
*/
OO.ui.MessageDialog.prototype.fitActions = function () {
var i, len, action,
previous = this.verticalActionLayout,
actions = this.actions.get();
// Detect clipping
this.toggleVerticalActionLayout( false );
for ( i = 0, len = actions.length; i < len; i++ ) {
action = actions[ i ];
if ( action.$element.innerWidth() < action.$label.outerWidth( true ) ) {
this.toggleVerticalActionLayout( true );
break;
}
}
// Move the body out of the way of the foot
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
if ( this.verticalActionLayout !== previous ) {
// We changed the layout, window height might need to be updated.
this.updateSize();
}
};
/**
* ProcessDialog windows encapsulate a {@link OO.ui.Process process} and all of the code necessary
* to complete it. If the process terminates with an error, a customizable {@link OO.ui.Error error
* interface} alerts users to the trouble, permitting the user to dismiss the error and try again when
* relevant. The ProcessDialog class is always extended and customized with the actions and content
* required for each process.
*
* The process dialog box consists of a header that visually represents the ‘working’ state of long
* processes with an animation. The header contains the dialog title as well as
* two {@link OO.ui.ActionWidget action widgets}: a ‘safe’ action on the left (e.g., ‘Cancel’) and
* a ‘primary’ action on the right (e.g., ‘Done’).
*
* Like other windows, the process dialog is managed by a {@link OO.ui.WindowManager window manager}.
* Please see the [OOjs UI documentation on MediaWiki][1] for more information and examples.
*
* @example
* // Example: Creating and opening a process dialog window.
* function MyProcessDialog( config ) {
* MyProcessDialog.parent.call( this, config );
* }
* OO.inheritClass( MyProcessDialog, OO.ui.ProcessDialog );
*
* MyProcessDialog.static.name = 'myProcessDialog';
* MyProcessDialog.static.title = 'Process dialog';
* MyProcessDialog.static.actions = [
* { action: 'save', label: 'Done', flags: 'primary' },
* { label: 'Cancel', flags: 'safe' }
* ];
*
* MyProcessDialog.prototype.initialize = function () {
* MyProcessDialog.parent.prototype.initialize.apply( this, arguments );
* this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
* this.content.$element.append( '<p>This is a process dialog window. The header contains the title and two buttons: \'Cancel\' (a safe action) on the left and \'Done\' (a primary action) on the right.</p>' );
* this.$body.append( this.content.$element );
* };
* MyProcessDialog.prototype.getActionProcess = function ( action ) {
* var dialog = this;
* if ( action ) {
* return new OO.ui.Process( function () {
* dialog.close( { action: action } );
* } );
* }
* return MyProcessDialog.parent.prototype.getActionProcess.call( this, action );
* };
*
* var windowManager = new OO.ui.WindowManager();
* $( 'body' ).append( windowManager.$element );
*
* var dialog = new MyProcessDialog();
* windowManager.addWindows( [ dialog ] );
* windowManager.openWindow( dialog );
*
* [1]: https://www.mediawiki.org/wiki/OOjs_UI/Windows/Process_Dialogs
*
* @abstract
* @class
* @extends OO.ui.Dialog
*
* @constructor
* @param {Object} [config] Configuration options
*/
OO.ui.ProcessDialog = function OoUiProcessDialog( config ) {
// Parent constructor
OO.ui.ProcessDialog.parent.call( this, config );
// Properties
this.fitOnOpen = false;
// Initialization
this.$element.addClass( 'oo-ui-processDialog' );
};
/* Setup */
OO.inheritClass( OO.ui.ProcessDialog, OO.ui.Dialog );
/* Methods */
/**
* Handle dismiss button click events.
*
* Hides errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onDismissErrorButtonClick = function () {
this.hideErrors();
};
/**
* Handle retry button click events.
*
* Hides errors and then tries again.
*
* @private
*/
OO.ui.ProcessDialog.prototype.onRetryButtonClick = function () {
this.hideErrors();
this.executeAction( this.currentAction );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.initialize = function () {
// Parent method
OO.ui.ProcessDialog.parent.prototype.initialize.call( this );
// Properties
this.$navigation = $( '<div>' );
this.$location = $( '<div>' );
this.$safeActions = $( '<div>' );
this.$primaryActions = $( '<div>' );
this.$otherActions = $( '<div>' );
this.dismissButton = new OO.ui.ButtonWidget( {
label: OO.ui.msg( 'ooui-dialog-process-dismiss' )
} );
this.retryButton = new OO.ui.ButtonWidget();
this.$errors = $( '<div>' );
this.$errorsTitle = $( '<div>' );
// Events
this.dismissButton.connect( this, { click: 'onDismissErrorButtonClick' } );
this.retryButton.connect( this, { click: 'onRetryButtonClick' } );
// Initialization
this.title.$element.addClass( 'oo-ui-processDialog-title' );
this.$location
.append( this.title.$element )
.addClass( 'oo-ui-processDialog-location' );
this.$safeActions.addClass( 'oo-ui-processDialog-actions-safe' );
this.$primaryActions.addClass( 'oo-ui-processDialog-actions-primary' );
this.$otherActions.addClass( 'oo-ui-processDialog-actions-other' );
this.$errorsTitle
.addClass( 'oo-ui-processDialog-errors-title' )
.text( OO.ui.msg( 'ooui-dialog-process-error' ) );
this.$errors
.addClass( 'oo-ui-processDialog-errors oo-ui-element-hidden' )
.append( this.$errorsTitle, this.dismissButton.$element, this.retryButton.$element );
this.$content
.addClass( 'oo-ui-processDialog-content' )
.append( this.$errors );
this.$navigation
.addClass( 'oo-ui-processDialog-navigation' )
// Note: Order of appends below is important. These are in the order
// we want tab to go through them. Display-order is handled entirely
// by CSS absolute-positioning. As such, primary actions like "done"
// should go first.
.append( this.$primaryActions, this.$location, this.$safeActions );
this.$head.append( this.$navigation );
this.$foot.append( this.$otherActions );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getActionWidgets = function ( actions ) {
var i, len, config,
isMobile = OO.ui.isMobile(),
widgets = [];
for ( i = 0, len = actions.length; i < len; i++ ) {
config = $.extend( { framed: !OO.ui.isMobile() }, actions[ i ] );
if ( isMobile &&
( config.flags === 'back' || ( Array.isArray( config.flags ) && config.flags.indexOf( 'back' ) !== -1 ) )
) {
$.extend( config, {
icon: 'previous',
label: ''
} );
}
widgets.push(
new OO.ui.ActionWidget( config )
);
}
return widgets;
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.attachActions = function () {
var i, len, other, special, others;
// Parent method
OO.ui.ProcessDialog.parent.prototype.attachActions.call( this );
special = this.actions.getSpecial();
others = this.actions.getOthers();
if ( special.primary ) {
this.$primaryActions.append( special.primary.$element );
}
for ( i = 0, len = others.length; i < len; i++ ) {
other = others[ i ];
this.$otherActions.append( other.$element );
}
if ( special.safe ) {
this.$safeActions.append( special.safe.$element );
}
this.fitLabel();
this.$body.css( 'bottom', this.$foot.outerHeight( true ) );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.executeAction = function ( action ) {
var process = this;
return OO.ui.ProcessDialog.parent.prototype.executeAction.call( this, action )
.fail( function ( errors ) {
process.showErrors( errors || [] );
} );
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.setDimensions = function () {
// Parent method
OO.ui.ProcessDialog.parent.prototype.setDimensions.apply( this, arguments );
this.fitLabel();
};
/**
* Fit label between actions.
*
* @private
* @chainable
*/
OO.ui.ProcessDialog.prototype.fitLabel = function () {
var safeWidth, primaryWidth, biggerWidth, labelWidth, navigationWidth, leftWidth, rightWidth,
size = this.getSizeProperties();
if ( typeof size.width !== 'number' ) {
if ( this.isOpened() ) {
navigationWidth = this.$head.width() - 20;
} else if ( this.isOpening() ) {
if ( !this.fitOnOpen ) {
// Size is relative and the dialog isn't open yet, so wait.
this.manager.opening.done( this.fitLabel.bind( this ) );
this.fitOnOpen = true;
}
return;
} else {
return;
}
} else {
navigationWidth = size.width - 20;
}
safeWidth = this.$safeActions.is( ':visible' ) ? this.$safeActions.width() : 0;
primaryWidth = this.$primaryActions.is( ':visible' ) ? this.$primaryActions.width() : 0;
biggerWidth = Math.max( safeWidth, primaryWidth );
labelWidth = this.title.$element.width();
if ( 2 * biggerWidth + labelWidth < navigationWidth ) {
// We have enough space to center the label
leftWidth = rightWidth = biggerWidth;
} else {
// Let's hope we at least have enough space not to overlap, because we can't wrap the label…
if ( this.getDir() === 'ltr' ) {
leftWidth = safeWidth;
rightWidth = primaryWidth;
} else {
leftWidth = primaryWidth;
rightWidth = safeWidth;
}
}
this.$location.css( { paddingLeft: leftWidth, paddingRight: rightWidth } );
return this;
};
/**
* Handle errors that occurred during accept or reject processes.
*
* @private
* @param {OO.ui.Error[]|OO.ui.Error} errors Errors to be handled
*/
OO.ui.ProcessDialog.prototype.showErrors = function ( errors ) {
var i, len, $item, actions,
items = [],
abilities = {},
recoverable = true,
warning = false;
if ( errors instanceof OO.ui.Error ) {
errors = [ errors ];
}
for ( i = 0, len = errors.length; i < len; i++ ) {
if ( !errors[ i ].isRecoverable() ) {
recoverable = false;
}
if ( errors[ i ].isWarning() ) {
warning = true;
}
$item = $( '<div>' )
.addClass( 'oo-ui-processDialog-error' )
.append( errors[ i ].getMessage() );
items.push( $item[ 0 ] );
}
this.$errorItems = $( items );
if ( recoverable ) {
abilities[ this.currentAction ] = true;
// Copy the flags from the first matching action
actions = this.actions.get( { actions: this.currentAction } );
if ( actions.length ) {
this.retryButton.clearFlags().setFlags( actions[ 0 ].getFlags() );
}
} else {
abilities[ this.currentAction ] = false;
this.actions.setAbilities( abilities );
}
if ( warning ) {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-continue' ) );
} else {
this.retryButton.setLabel( OO.ui.msg( 'ooui-dialog-process-retry' ) );
}
this.retryButton.toggle( recoverable );
this.$errorsTitle.after( this.$errorItems );
this.$errors.removeClass( 'oo-ui-element-hidden' ).scrollTop( 0 );
};
/**
* Hide errors.
*
* @private
*/
OO.ui.ProcessDialog.prototype.hideErrors = function () {
this.$errors.addClass( 'oo-ui-element-hidden' );
if ( this.$errorItems ) {
this.$errorItems.remove();
this.$errorItems = null;
}
};
/**
* @inheritdoc
*/
OO.ui.ProcessDialog.prototype.getTeardownProcess = function ( data ) {
// Parent method
return OO.ui.ProcessDialog.parent.prototype.getTeardownProcess.call( this, data )
.first( function () {
// Make sure to hide errors
this.hideErrors();
this.fitOnOpen = false;
}, this );
};
/**
* @class OO.ui
*/
/**
* Lazy-initialize and return a global OO.ui.WindowManager instance, used by OO.ui.alert and
* OO.ui.confirm.
*
* @private
* @return {OO.ui.WindowManager}
*/
OO.ui.getWindowManager = function () {
if ( !OO.ui.windowManager ) {
OO.ui.windowManager = new OO.ui.WindowManager();
$( 'body' ).append( OO.ui.windowManager.$element );
OO.ui.windowManager.addWindows( [ new OO.ui.MessageDialog() ] );
}
return OO.ui.windowManager;
};
/**
* Display a quick modal alert dialog, using a OO.ui.MessageDialog. While the dialog is open, the
* rest of the page will be dimmed out and the user won't be able to interact with it. The dialog
* has only one action button, labelled "OK", clicking it will simply close the dialog.
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.alert( 'Something happened!' ).done( function () {
* console.log( 'User closed the dialog.' );
* } );
*
* OO.ui.alert( 'Something larger happened!', { size: 'large' } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog
*/
OO.ui.alert = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text,
actions: [ OO.ui.MessageDialog.static.actions[ 0 ] ]
}, options ) ).then( function ( opened ) {
return opened.then( function ( closing ) {
return closing.then( function () {
return $.Deferred().resolve();
} );
} );
} );
};
/**
* Display a quick modal confirmation dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has two action buttons, one to confirm an operation (labelled "OK") and one to cancel it
* (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.confirm( 'Are you sure?' ).done( function ( confirmed ) {
* if ( confirmed ) {
* console.log( 'User clicked "OK"!' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve to boolean `true`; otherwise, it will resolve to boolean
* `false`.
*/
OO.ui.confirm = function ( text, options ) {
return OO.ui.getWindowManager().openWindow( 'message', $.extend( {
message: text
}, options ) ).then( function ( opened ) {
return opened.then( function ( closing ) {
return closing.then( function ( data ) {
return $.Deferred().resolve( !!( data && data.action === 'accept' ) );
} );
} );
} );
};
/**
* Display a quick modal prompt dialog, using a OO.ui.MessageDialog. While the dialog is open,
* the rest of the page will be dimmed out and the user won't be able to interact with it. The
* dialog has a text input widget and two action buttons, one to confirm an operation (labelled "OK")
* and one to cancel it (labelled "Cancel").
*
* A window manager is created automatically when this function is called for the first time.
*
* @example
* OO.ui.prompt( 'Choose a line to go to', { textInput: { placeholder: 'Line number' } } ).done( function ( result ) {
* if ( result !== null ) {
* console.log( 'User typed "' + result + '" then clicked "OK".' );
* } else {
* console.log( 'User clicked "Cancel" or closed the dialog.' );
* }
* } );
*
* @param {jQuery|string} text Message text to display
* @param {Object} [options] Additional options, see OO.ui.MessageDialog#getSetupProcess
* @param {Object} [options.textInput] Additional options for text input widget, see OO.ui.TextInputWidget
* @return {jQuery.Promise} Promise resolved when the user closes the dialog. If the user chose to
* confirm, the promise will resolve with the value of the text input widget; otherwise, it will
* resolve to `null`.
*/
OO.ui.prompt = function ( text, options ) {
var manager = OO.ui.getWindowManager(),
textInput = new OO.ui.TextInputWidget( ( options && options.textInput ) || {} ),
textField = new OO.ui.FieldLayout( textInput, {
align: 'top',
label: text
} );
// TODO: This is a little hacky, and could be done by extending MessageDialog instead.
return manager.openWindow( 'message', $.extend( {
message: textField.$element
}, options ) ).then( function ( opened ) {
// After ready
textInput.on( 'enter', function () {
manager.getCurrentWindow().close( { action: 'accept' } );
} );
textInput.focus();
return opened.then( function ( closing ) {
return closing.then( function ( data ) {
return $.Deferred().resolve( data && data.action === 'accept' ? textInput.getValue() : null );
} );
} );
} );
};
}( OO ) );
|
/** @module myModule */
/** An event (has listeners).
* @event MyEvent
* @memberof module:myModule
* @param {number} foo - asdf. */
/** A handler.
* @listens module:myModule.MyEvent
* @listens module:myModule~Events.event:Event2
* @listens fakeEvent
*/
function MyHandler() {
}
/** Another handler.
* @listens module:myModule.MyEvent
*/
function AnotherHandler() {
}
/** a namespace.
* @namespace */
var Events = {
};
/** Another event (has listeners).
* @event Event2
* @memberof module:myModule~Events
*/
/** An event with no listeners.
* @event module:myModule#Event3 */
|
'use strict';
const xcode = require('xcode');
const PbxFile = require('xcode/lib/pbxFile');
const addProjectToLibraries = require('../../ios/addProjectToLibraries');
const removeProjectFromLibraries = require('../../ios/removeProjectFromLibraries');
const last = require('lodash').last;
const path = require('path');
const project = xcode.project(
path.join(__dirname, '../../__fixtures__/project.pbxproj')
);
describe('ios::removeProjectFromLibraries', () => {
beforeEach(() => {
project.parseSync();
addProjectToLibraries(
project.pbxGroupByName('Libraries'),
new PbxFile('fakePath')
);
});
it('should remove file from Libraries group', () => {
const file = new PbxFile('fakePath');
const libraries = project.pbxGroupByName('Libraries');
removeProjectFromLibraries(libraries, file);
const child = last(libraries.children);
expect(child.comment).not.toBe(file.basename);
});
});
|
/*jshint sub:true*/
'use strict';
angular.module('com.module.events')
.controller('EventsCtrl', function($scope, $state, $stateParams, CoreService,
Event, gettextCatalog) {
var eventId = $stateParams.id;
var createDate = function(date, time) {
console.log(date);
console.log(time);
if (!date || !time) {
return date || time;
}
var out = angular.copy(time);
out.setFullYear(date.getFullYear());
out.setMonth(date.getMonth());
out.setDate(date.getDate());
return out;
};
var splitDate = function() {
var event = $scope.event;
event.sDate = event.sTime = event.startTime;
event.eDate = event.eTime = Date.parse(event['end_time']);
// event['start_time'] = event['end_time'] = null;
};
if (eventId) {
$scope.event = Event.findById({
id: eventId
}, function() {
splitDate();
}, function(err) {
console.log(err);
});
} else {
$scope.event = {};
}
function loadItems() {
$scope.events = Event.find();
}
loadItems();
$scope.delete = function(id) {
CoreService.confirm(gettextCatalog.getString('Are you sure?'),
gettextCatalog.getString('Deleting this cannot be undone'),
function() {
Event.deleteById(id, function() {
CoreService.toastSuccess(gettextCatalog.getString(
'Event deleted'), gettextCatalog.getString(
'Your event is deleted!'));
loadItems();
$state.go('app.events.list');
console.log();
}, function(err) {
CoreService.toastError(gettextCatalog.getString(
'Error deleting event'), gettextCatalog.getString(
'Your event is not deleted: ') + err);
});
},
function() {
return false;
});
};
var dateOpen = function($event) {
$event.preventDefault();
$event.stopPropagation();
this.opened = true;
};
$scope.formFields = [{
key: 'name',
label: gettextCatalog.getString('Name'),
type: 'text',
required: true
}, {
key: 'description',
type: 'text',
label: gettextCatalog.getString('Description'),
required: true
}, {
key: 'sDate',
required: true,
label: gettextCatalog.getString('Start Date'),
type: 'date',
format: gettextCatalog.getString('dd/MM/yyyy'),
opened: false,
switchOpen: dateOpen
}, {
key: 'sTime',
required: true,
label: gettextCatalog.getString('Start Time'),
type: 'time',
hstep: 1,
mstep: 5,
ismeridian: true
}, {
key: 'eDate',
label: gettextCatalog.getString('End'),
type: 'date',
format: gettextCatalog.getString('dd/MM/yyyy'),
opened: false,
switchOpen: dateOpen
}, {
key: 'eTime',
required: true,
label: gettextCatalog.getString('End Time'),
type: 'time',
hstep: 1,
mstep: 5,
ismeridian: true
}
];
$scope.formOptions = {
uniqueFormId: true,
hideSubmit: false,
submitCopy: gettextCatalog.getString('Save')
};
$scope.alerts = [];
$scope.onSubmit = function() {
var event = $scope.event;
event['start_time'] = createDate(event.sDate, event.sTime);
event.sDate = null;
event.sTime = null;
event['end_time'] = createDate(event.eDate, event.eTime);
event.eDate = null;
event.eTime = null;
Event.upsert($scope.event, function() {
CoreService.toastSuccess(gettextCatalog.getString('Event saved'),
gettextCatalog.getString('Your event is safe with us!'));
$state.go('^.list');
}, function(err) {
$scope.alerts.push({
type: 'danger',
msg: err.data.error.message
});
CoreService.toastError(gettextCatalog.getString(
'Event not added'), err.data.error.message);
console.log(err);
});
};
});
|
define([], function() {
var util = hello.utils.param;
describe('utils.param', function() {
var test = {
param: 'param1',
param2: 'param2',
hyperlink: 'https://example.com?a=1&b=2',
jsonp: '?'
};
it('should accept an object and return a string', function() {
var value = util({});
expect(value).to.be.a('string');
});
it('should accept a string and return an object', function() {
var value = util('');
expect(value).to.be.an(Object);
});
it('should turn URL query into an object', function() {
// Convert there and back
var value = util(util(test));
expect(value).to.eql(test);
});
it('should turn an object into a URL string', function() {
// Convert there and back
var value = util(test);
expect(value).to.be.a('string');
});
it('should only include hasOwnProperties from an object', function() {
// Convert there and back
var obj = Object.create({ignore:'this should be excluded'});
obj.included = 'this is included';
var value = util(util(obj));
expect(value).to.have.property('included').and.not.to.have.property('ignore');
});
});
});
|
var isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('./isArrayLike'),
isFunction = require('./isFunction'),
isString = require('./isString');
/** Used for built-in method references. */
var objectProto = global.Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Checks if `value` is empty. A value is considered empty unless it's an
* `arguments` object, array, string, or jQuery-like collection with a length
* greater than `0` or an object with own enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (isArrayLike(value) &&
(isArray(value) || isString(value) || isFunction(value.splice) || isArguments(value))) {
return !value.length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
module.exports = isEmpty;
|
"use strict";
exports.__esModule = true;
exports.RESPONSE_CYCLE_TIME = exports.RES_TIMEOUT = exports.ACK_TIMEOUT_KNOWN = exports.ACK_TIMEOUT = exports.CHILD_WINDOW_TIMEOUT = exports.BRIDGE_TIMEOUT = void 0;
const BRIDGE_TIMEOUT = 5000;
exports.BRIDGE_TIMEOUT = BRIDGE_TIMEOUT;
const CHILD_WINDOW_TIMEOUT = 5000;
exports.CHILD_WINDOW_TIMEOUT = CHILD_WINDOW_TIMEOUT;
const ACK_TIMEOUT = 2000;
exports.ACK_TIMEOUT = ACK_TIMEOUT;
const ACK_TIMEOUT_KNOWN = 10000;
exports.ACK_TIMEOUT_KNOWN = ACK_TIMEOUT_KNOWN;
const RES_TIMEOUT = __TEST__ ? 2000 : -1;
exports.RES_TIMEOUT = RES_TIMEOUT;
const RESPONSE_CYCLE_TIME = 500;
exports.RESPONSE_CYCLE_TIME = RESPONSE_CYCLE_TIME; |
'use strict';
var get = require('get-value');
var _ = require('lodash');
/**
* Convenience method for debugging.
*
* **Examples**
*
* ```js
* {%= log(debug("app")) %}
* {%= log(debug("app.cache.data")) %}
*
* {%= log(debug("file")) %}
* {%= log(debug("file.data")) %}
*
* {%= log(debug()) %}
* {%= log(debug("this")) %}
* {%= log(debug("this.dest")) %}
* ```
* @todo move to a helper
*/
module.exports = function (app) {
return function(file, next) {
file.data.debug = file.data.debug || {};
file.data.debug = function (prop) {
var segs, root, type = typeof prop;
if (type !== 'undefined') {
segs = prop.split('.');
root = segs.shift();
segs = segs.join('.');
}
// get the (pseudo) context
if (root === 'this' || root === 'context' || type === 'undefined') {
var ctx = app.cache.data;
_.merge(ctx, file.data);
return filter(ctx, segs);
}
// get the file object
if (root === 'file') {
return filter(file, segs);
}
// get the app
if (root === 'app') {
return filter(app, segs);
}
};
next();
};
};
function filter(obj, prop) {
var omitKeys = ['debug', '_contents', 'fn'];
if (typeof prop !== 'string' || prop === '') {
return _.omit(_.cloneDeep(obj), omitKeys);
}
return _.omit(_.cloneDeep(get(obj, prop)), omitKeys);
}
|
/*
* Test utils.betterErrors. utils.betterErrors should provide sensible error messages even when the error does not
* contain expected, actual or operator.
*/
var assert = require("../lib/assert");
var should = require("should");
var types = require("../lib/types");
var util = require('util');
var utils = require("../lib/utils");
function betterErrorStringFromError(error) {
var assertion = types.assertion({error: error});
var better = utils.betterErrors(assertion);
return better.error.stack.toString();
}
function performBasicChecks(betterErrorString) {
betterErrorString.should.containEql("AssertionError");
betterErrorString.should.containEql("test-bettererrors");
//betterErrorString.should.not.include("undefined");
}
/**
* Control test. Provide an AssertionError that contains actual, expected operator values.
* @param test the test object from nodeunit
*/
exports.testEqual = function (test) {
try {
assert.equal(true, false);
} catch (error) {
var betterErrorString = betterErrorStringFromError(error);
performBasicChecks(betterErrorString);
betterErrorString.should.containEql("true");
betterErrorString.should.containEql("false");
betterErrorString.should.containEql("==");
test.done();
}
};
/**
* Test an AssertionError that does not contain actual, expected or operator values.
* @param test the test object from nodeunit
*/
exports.testAssertThrows = function (test) {
try {
assert.throws(function () {
});
} catch (error) {
var betterErrorString = betterErrorStringFromError(error);
performBasicChecks(betterErrorString);
test.done();
}
};
/**
* Test with an error that is not an AssertionError.
*
* This function name MUST NOT include "AssertionError" because one of the
* tests it performs asserts that the returned error string does not contain
* the "AssertionError" term. If this function name does include that term, it
* will show up in the stack trace and the test will fail!
* @param test the test object from nodeunit
*/
exports.testErrorIsNotAssertion = function (test) {
try {
throw new Error("test error");
} catch (error) {
var betterErrorString = betterErrorStringFromError(error);
betterErrorString.should.not.containEql("AssertionError");
betterErrorString.should.containEql("Error");
betterErrorString.should.containEql("test error");
betterErrorString.should.containEql("test-bettererrors");
betterErrorString.should.not.containEql("undefined");
test.done();
}
};
|
/**
* @author Mat Groves http://matgroves.com/ @Doormat23
*/
PIXI.WebGLShaderManager = function(gl)
{
this.setContext(gl);
// the final one is used for the rendering strips
//this.stripShader = new PIXI.StripShader(gl);
};
PIXI.WebGLShaderManager.prototype.setContext = function(gl)
{
this.gl = gl;
// the next one is used for rendering primatives
this.primitiveShader = new PIXI.PrimitiveShader(gl);
// this shader is used for the default sprite rendering
this.defaultShader = new PIXI.PixiShader(gl);
var shaderProgram = this.defaultShader.program;
gl.useProgram(shaderProgram);
gl.enableVertexAttribArray(this.defaultShader.aVertexPosition);
gl.enableVertexAttribArray(this.defaultShader.colorAttribute);
gl.enableVertexAttribArray(this.defaultShader.aTextureCoord);
};
PIXI.WebGLShaderManager.prototype.activatePrimitiveShader = function()
{
var gl = this.gl;
gl.useProgram(this.primitiveShader.program);
gl.disableVertexAttribArray(this.defaultShader.aVertexPosition);
gl.disableVertexAttribArray(this.defaultShader.colorAttribute);
gl.disableVertexAttribArray(this.defaultShader.aTextureCoord);
gl.enableVertexAttribArray(this.primitiveShader.aVertexPosition);
gl.enableVertexAttribArray(this.primitiveShader.colorAttribute);
};
PIXI.WebGLShaderManager.prototype.deactivatePrimitiveShader = function()
{
var gl = this.gl;
gl.useProgram(this.defaultShader.program);
gl.disableVertexAttribArray(this.primitiveShader.aVertexPosition);
gl.disableVertexAttribArray(this.primitiveShader.colorAttribute);
gl.enableVertexAttribArray(this.defaultShader.aVertexPosition);
gl.enableVertexAttribArray(this.defaultShader.colorAttribute);
gl.enableVertexAttribArray(this.defaultShader.aTextureCoord);
}; |
/*
Copyright (C) 2011 by MarkLogic Corporation
Author: Mike Brevoort <mike@brevoort.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
CodeMirror.defineMode("xquery", function(config, parserConfig) {
// The keywords object is set to the result of this self executing
// function. Each keyword is a property of the keywords object whose
// value is {type: atype, style: astyle}
var keywords = function(){
// conveinence functions used to build keywords object
function kw(type) {return {type: type, style: "keyword"};}
var A = kw("keyword a")
, B = kw("keyword b")
, C = kw("keyword c")
, operator = kw("operator")
, atom = {type: "atom", style: "atom"}
, punctuation = {type: "punctuation", style: ""}
, qualifier = {type: "axis_specifier", style: "qualifier"};
// kwObj is what is return from this function at the end
var kwObj = {
'if': A, 'switch': A, 'while': A, 'for': A,
'else': B, 'then': B, 'try': B, 'finally': B, 'catch': B,
'element': C, 'attribute': C, 'let': C, 'implements': C, 'import': C, 'module': C, 'namespace': C,
'return': C, 'super': C, 'this': C, 'throws': C, 'where': C, 'private': C,
',': punctuation,
'null': atom, 'fn:false()': atom, 'fn:true()': atom
};
// a list of 'basic' keywords. For each add a property to kwObj with the value of
// {type: basic[i], style: "keyword"} e.g. 'after' --> {type: "after", style: "keyword"}
var basic = ['after','ancestor','ancestor-or-self','and','as','ascending','assert','attribute','before',
'by','case','cast','child','comment','declare','default','define','descendant','descendant-or-self',
'descending','document','document-node','element','else','eq','every','except','external','following',
'following-sibling','follows','for','function','if','import','in','instance','intersect','item',
'let','module','namespace','node','node','of','only','or','order','parent','precedes','preceding',
'preceding-sibling','processing-instruction','ref','return','returns','satisfies','schema','schema-element',
'self','some','sortby','stable','text','then','to','treat','typeswitch','union','variable','version','where',
'xquery', 'empty-sequence'];
for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);};
// a list of types. For each add a property to kwObj with the value of
// {type: "atom", style: "atom"}
var types = ['xs:string', 'xs:float', 'xs:decimal', 'xs:double', 'xs:integer', 'xs:boolean', 'xs:date', 'xs:dateTime',
'xs:time', 'xs:duration', 'xs:dayTimeDuration', 'xs:time', 'xs:yearMonthDuration', 'numeric', 'xs:hexBinary',
'xs:base64Binary', 'xs:anyURI', 'xs:QName', 'xs:byte','xs:boolean','xs:anyURI','xf:yearMonthDuration'];
for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;};
// each operator will add a property to kwObj with value of {type: "operator", style: "keyword"}
var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-'];
for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;};
// each axis_specifiers will add a property to kwObj with value of {type: "axis_specifier", style: "qualifier"}
var axis_specifiers = ["self::", "attribute::", "child::", "descendant::", "descendant-or-self::", "parent::",
"ancestor::", "ancestor-or-self::", "following::", "preceding::", "following-sibling::", "preceding-sibling::"];
for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; };
return kwObj;
}();
// Used as scratch variables to communicate multiple values without
// consing up tons of objects.
var type, content;
function ret(tp, style, cont) {
type = tp; content = cont;
return style;
}
function chain(stream, state, f) {
state.tokenize = f;
return f(stream, state);
}
// the primary mode tokenizer
function tokenBase(stream, state) {
var ch = stream.next(),
mightBeFunction = false,
isEQName = isEQNameAhead(stream);
// an XML tag (if not in some sub, chained tokenizer)
if (ch == "<") {
if(stream.match("!--", true))
return chain(stream, state, tokenXMLComment);
if(stream.match("![CDATA", false)) {
state.tokenize = tokenCDATA;
return ret("tag", "tag");
}
if(stream.match("?", false)) {
return chain(stream, state, tokenPreProcessing);
}
var isclose = stream.eat("/");
stream.eatSpace();
var tagName = "", c;
while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c;
return chain(stream, state, tokenTag(tagName, isclose));
}
// start code block
else if(ch == "{") {
pushStateStack(state,{ type: "codeblock"});
return ret("", "");
}
// end code block
else if(ch == "}") {
popStateStack(state);
return ret("", "");
}
// if we're in an XML block
else if(isInXmlBlock(state)) {
if(ch == ">")
return ret("tag", "tag");
else if(ch == "/" && stream.eat(">")) {
popStateStack(state);
return ret("tag", "tag");
}
else
return ret("word", "variable");
}
// if a number
else if (/\d/.test(ch)) {
stream.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/);
return ret("number", "atom");
}
// comment start
else if (ch === "(" && stream.eat(":")) {
pushStateStack(state, { type: "comment"});
return chain(stream, state, tokenComment);
}
// quoted string
else if ( !isEQName && (ch === '"' || ch === "'"))
return chain(stream, state, tokenString(ch));
// variable
else if(ch === "$") {
return chain(stream, state, tokenVariable);
}
// assignment
else if(ch ===":" && stream.eat("=")) {
return ret("operator", "keyword");
}
// open paren
else if(ch === "(") {
pushStateStack(state, { type: "paren"});
return ret("", "");
}
// close paren
else if(ch === ")") {
popStateStack(state);
return ret("", "");
}
// open paren
else if(ch === "[") {
pushStateStack(state, { type: "bracket"});
return ret("", "");
}
// close paren
else if(ch === "]") {
popStateStack(state);
return ret("", "");
}
else {
var known = keywords.propertyIsEnumerable(ch) && keywords[ch];
// if there's a EQName ahead, consume the rest of the string portion, it's likely a function
if(isEQName && ch === '\"') while(stream.next() !== '"'){}
if(isEQName && ch === '\'') while(stream.next() !== '\''){}
// gobble up a word if the character is not known
if(!known) stream.eatWhile(/[\w\$_-]/);
// gobble a colon in the case that is a lib func type call fn:doc
var foundColon = stream.eat(":");
// if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier
// which should get matched as a keyword
if(!stream.eat(":") && foundColon) {
stream.eatWhile(/[\w\$_-]/);
}
// if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort)
if(stream.match(/^[ \t]*\(/, false)) {
mightBeFunction = true;
}
// is the word a keyword?
var word = stream.current();
known = keywords.propertyIsEnumerable(word) && keywords[word];
// if we think it's a function call but not yet known,
// set style to variable for now for lack of something better
if(mightBeFunction && !known) known = {type: "function_call", style: "variable def"};
// if the previous word was element, attribute, axis specifier, this word should be the name of that
if(isInXmlConstructor(state)) {
popStateStack(state);
return ret("word", "variable", word);
}
// as previously checked, if the word is element,attribute, axis specifier, call it an "xmlconstructor" and
// push the stack so we know to look for it on the next word
if(word == "element" || word == "attribute" || known.type == "axis_specifier") pushStateStack(state, {type: "xmlconstructor"});
// if the word is known, return the details of that else just call this a generic 'word'
return known ? ret(known.type, known.style, word) :
ret("word", "variable", word);
}
}
// handle comments, including nested
function tokenComment(stream, state) {
var maybeEnd = false, maybeNested = false, nestedCount = 0, ch;
while (ch = stream.next()) {
if (ch == ")" && maybeEnd) {
if(nestedCount > 0)
nestedCount--;
else {
popStateStack(state);
break;
}
}
else if(ch == ":" && maybeNested) {
nestedCount++;
}
maybeEnd = (ch == ":");
maybeNested = (ch == "(");
}
return ret("comment", "comment");
}
// tokenizer for string literals
// optionally pass a tokenizer function to set state.tokenize back to when finished
function tokenString(quote, f) {
return function(stream, state) {
var ch;
if(isInString(state) && stream.current() == quote) {
popStateStack(state);
if(f) state.tokenize = f;
return ret("string", "string");
}
pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) });
// if we're in a string and in an XML block, allow an embedded code block
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
while (ch = stream.next()) {
if (ch == quote) {
popStateStack(state);
if(f) state.tokenize = f;
break;
}
else {
// if we're in a string and in an XML block, allow an embedded code block in an attribute
if(stream.match("{", false) && isInXmlAttributeBlock(state)) {
state.tokenize = tokenBase;
return ret("string", "string");
}
}
}
return ret("string", "string");
};
}
// tokenizer for variables
function tokenVariable(stream, state) {
var isVariableChar = /[\w\$_-]/;
// a variable may start with a quoted EQName so if the next character is quote, consume to the next quote
if(stream.eat("\"")) {
while(stream.next() !== '\"'){};
stream.eat(":");
} else {
stream.eatWhile(isVariableChar);
if(!stream.match(":=", false)) stream.eat(":");
}
stream.eatWhile(isVariableChar);
state.tokenize = tokenBase;
return ret("variable", "variable");
}
// tokenizer for XML tags
function tokenTag(name, isclose) {
return function(stream, state) {
stream.eatSpace();
if(isclose && stream.eat(">")) {
popStateStack(state);
state.tokenize = tokenBase;
return ret("tag", "tag");
}
// self closing tag without attributes?
if(!stream.eat("/"))
pushStateStack(state, { type: "tag", name: name, tokenize: tokenBase});
if(!stream.eat(">")) {
state.tokenize = tokenAttribute;
return ret("tag", "tag");
}
else {
state.tokenize = tokenBase;
}
return ret("tag", "tag");
};
}
// tokenizer for XML attributes
function tokenAttribute(stream, state) {
var ch = stream.next();
if(ch == "/" && stream.eat(">")) {
if(isInXmlAttributeBlock(state)) popStateStack(state);
if(isInXmlBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == ">") {
if(isInXmlAttributeBlock(state)) popStateStack(state);
return ret("tag", "tag");
}
if(ch == "=")
return ret("", "");
// quoted string
if (ch == '"' || ch == "'")
return chain(stream, state, tokenString(ch, tokenAttribute));
if(!isInXmlAttributeBlock(state))
pushStateStack(state, { type: "attribute", name: name, tokenize: tokenAttribute});
stream.eat(/[a-zA-Z_:]/);
stream.eatWhile(/[-a-zA-Z0-9_:.]/);
stream.eatSpace();
// the case where the attribute has not value and the tag was closed
if(stream.match(">", false) || stream.match("/", false)) {
popStateStack(state);
state.tokenize = tokenBase;
}
return ret("attribute", "attribute");
}
// handle comments, including nested
function tokenXMLComment(stream, state) {
var ch;
while (ch = stream.next()) {
if (ch == "-" && stream.match("->", true)) {
state.tokenize = tokenBase;
return ret("comment", "comment");
}
}
}
// handle CDATA
function tokenCDATA(stream, state) {
var ch;
while (ch = stream.next()) {
if (ch == "]" && stream.match("]", true)) {
state.tokenize = tokenBase;
return ret("comment", "comment");
}
}
}
// handle preprocessing instructions
function tokenPreProcessing(stream, state) {
var ch;
while (ch = stream.next()) {
if (ch == "?" && stream.match(">", true)) {
state.tokenize = tokenBase;
return ret("comment", "comment meta");
}
}
}
// functions to test the current context of the state
function isInXmlBlock(state) { return isIn(state, "tag"); }
function isInXmlAttributeBlock(state) { return isIn(state, "attribute"); }
function isInCodeBlock(state) { return isIn(state, "codeblock"); }
function isInXmlConstructor(state) { return isIn(state, "xmlconstructor"); }
function isInString(state) { return isIn(state, "string"); }
function isEQNameAhead(stream) {
// assume we've already eaten a quote (")
if(stream.current() === '"')
return stream.match(/^[^\"]+\"\:/, false);
else if(stream.current() === '\'')
return stream.match(/^[^\"]+\'\:/, false);
else
return false;
}
function isIn(state, type) {
return (state.stack.length && state.stack[state.stack.length - 1].type == type);
}
function pushStateStack(state, newState) {
state.stack.push(newState);
}
function popStateStack(state) {
var popped = state.stack.pop();
var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize;
state.tokenize = reinstateTokenize || tokenBase;
}
// the interface for the mode API
return {
startState: function(basecolumn) {
return {
tokenize: tokenBase,
cc: [],
stack: []
};
},
token: function(stream, state) {
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
return style;
}
};
});
CodeMirror.defineMIME("application/xquery", "xquery");
|
// A simple tracker dependency that we invalidate every time the window is
// resized. This is used to reactively re-calculate the popup position in case
// of a window resize. This is the equivalent of a "Signal" in some other
// programming environments (eg, elm).
const windowResizeDep = new Tracker.Dependency();
$(window).on('resize', () => windowResizeDep.changed());
window.Popup = new class {
constructor() {
// The template we use to render popups
this.template = Template.popup;
// We only want to display one popup at a time and we keep the view object
// in this `Popup._current` variable. If there is no popup currently opened
// the value is `null`.
this._current = null;
// It's possible to open a sub-popup B from a popup A. In that case we keep
// the data of popup A so we can return back to it. Every time we open a new
// popup the stack grows, every time we go back the stack decrease, and if
// we close the popup the stack is reseted to the empty stack [].
this._stack = [];
// We invalidate this internal dependency every time the top of the stack
// has changed and we want to re-render a popup with the new top-stack data.
this._dep = new Tracker.Dependency();
}
/// This function returns a callback that can be used in an event map:
/// Template.tplName.events({
/// 'click .elementClass': Popup.open("popupName"),
/// });
/// The popup inherit the data context of its parent.
open(name) {
const self = this;
const popupName = `${name}Popup`;
function clickFromPopup(evt) {
return $(evt.target).closest('.js-pop-over').length !== 0;
}
return function(evt) {
// If a popup is already opened, clicking again on the opener element
// should close it -- and interrupt the current `open` function.
if (self.isOpen()) {
const previousOpenerElement = self._getTopStack().openerElement;
if (previousOpenerElement === evt.currentTarget) {
return self.close();
} else {
$(previousOpenerElement).removeClass('is-active');
}
}
// We determine the `openerElement` (the DOM element that is being clicked
// and the one we take in reference to position the popup) from the event
// if the popup has no parent, or from the parent `openerElement` if it
// has one. This allows us to position a sub-popup exactly at the same
// position than its parent.
let openerElement;
if (clickFromPopup(evt)) {
openerElement = self._getTopStack().openerElement;
} else {
self._stack = [];
openerElement = evt.currentTarget;
}
$(openerElement).addClass('is-active');
evt.preventDefault();
// We push our popup data to the stack. The top of the stack is always
// used as the data source for our current popup.
self._stack.push({
popupName,
openerElement,
hasPopupParent: clickFromPopup(evt),
title: self._getTitle(popupName),
depth: self._stack.length,
offset: self._getOffset(openerElement),
dataContext: this.currentData && this.currentData() || this,
});
// If there are no popup currently opened we use the Blaze API to render
// one into the DOM. We use a reactive function as the data parameter that
// return the the complete along with its top element and depends on our
// internal dependency that is being invalidated every time the top
// element of the stack has changed and we want to update the popup.
//
// Otherwise if there is already a popup open we just need to invalidate
// our internal dependency, and since we just changed the top element of
// our internal stack, the popup will be updated with the new data.
if (!self.isOpen()) {
self.current = Blaze.renderWithData(self.template, () => {
self._dep.depend();
return _.extend(self._getTopStack(), { stack: self._stack });
}, document.body);
} else {
self._dep.changed();
}
};
}
/// This function returns a callback that can be used in an event map:
/// Template.tplName.events({
/// 'click .elementClass': Popup.afterConfirm("popupName", function() {
/// // What to do after the user has confirmed the action
/// }),
/// });
afterConfirm(name, action) {
const self = this;
return function(evt, tpl) {
const context = this.currentData && this.currentData() || this;
context.__afterConfirmAction = action;
self.open(name).call(context, evt, tpl);
};
}
/// The public reactive state of the popup.
isOpen() {
this._dep.changed();
return Boolean(this.current);
}
/// In case the popup was opened from a parent popup we can get back to it
/// with this `Popup.back()` function. You can go back several steps at once
/// by providing a number to this function, e.g. `Popup.back(2)`. In this case
/// intermediate popup won't even be rendered on the DOM. If the number of
/// steps back is greater than the popup stack size, the popup will be closed.
back(n = 1) {
if (this._stack.length > n) {
_.times(n, () => this._stack.pop());
this._dep.changed();
} else {
this.close();
}
}
/// Close the current opened popup.
close() {
if (this.isOpen()) {
Blaze.remove(this.current);
this.current = null;
const openerElement = this._getTopStack().openerElement;
$(openerElement).removeClass('is-active');
this._stack = [];
}
}
// An utility fonction that returns the top element of the internal stack
_getTopStack() {
return this._stack[this._stack.length - 1];
}
// We automatically calculate the popup offset from the reference element
// position and dimensions. We also reactively use the window dimensions to
// ensure that the popup is always visible on the screen.
_getOffset(element) {
const $element = $(element);
return () => {
windowResizeDep.depend();
const offset = $element.offset();
const popupWidth = 300 + 15;
return {
left: Math.min(offset.left, $(window).width() - popupWidth),
top: offset.top + $element.outerHeight(),
};
};
}
// We get the title from the translation files. Instead of returning the
// result, we return a function that compute the result and since `TAPi18n.__`
// is a reactive data source, the title will be changed reactively.
_getTitle(popupName) {
return () => {
const translationKey = `${popupName}-title`;
// XXX There is no public API to check if there is an available
// translation for a given key. So we try to translate the key and if the
// translation output equals the key input we deduce that no translation
// was available and returns `false`. There is a (small) risk a false
// positives.
const title = TAPi18n.__(translationKey);
return title !== translationKey ? title : false;
};
}
};
// We close a potential opened popup on any left click on the document, or go
// one step back by pressing escape.
const escapeActions = ['back', 'close'];
_.each(escapeActions, (actionName) => {
EscapeActions.register(`popup-${actionName}`,
() => Popup[actionName](),
() => Popup.isOpen(),
{
noClickEscapeOn: '.js-pop-over',
enabledOnClick: actionName === 'close',
}
);
});
|
'use strict';
var implementation = require('./implementation');
module.exports = function getPolyfill() {
if (!String.prototype.trimStart && !String.prototype.trimLeft) {
return implementation;
}
var zeroWidthSpace = '\u200b';
var trimmed = zeroWidthSpace.trimStart ? zeroWidthSpace.trimStart() : zeroWidthSpace.trimLeft();
if (trimmed !== zeroWidthSpace) {
return implementation;
}
return String.prototype.trimStart || String.prototype.trimLeft;
};
|
'use strict';
var lint = require('./_lint');
//////////////////////////////
// SCSS syntax tests
//////////////////////////////
describe('space before colon - scss', function () {
var file = lint.file('space-before-colon.scss');
it('[include: false]', function (done) {
lint.test(file, {
'space-before-colon': 1
}, function (data) {
lint.assert.equal(3, data.warningCount);
done();
});
});
it('[include: true]', function (done) {
lint.test(file, {
'space-before-colon': [
1,
{
'include': true
}
]
}, function (data) {
lint.assert.equal(4, data.warningCount);
done();
});
});
});
//////////////////////////////
// Sass syntax tests
//////////////////////////////
describe('space before colon - sass', function () {
var file = lint.file('space-before-colon.sass');
it('[include: false]', function (done) {
lint.test(file, {
'space-before-colon': 1
}, function (data) {
lint.assert.equal(3, data.warningCount);
done();
});
});
it('[include: true]', function (done) {
lint.test(file, {
'space-before-colon': [
1,
{
'include': true
}
]
}, function (data) {
lint.assert.equal(4, data.warningCount);
done();
});
});
});
|
"use strict";
var $__ScopeChainBuilderWithReferences_46_js__;
var ScopeChainBuilderWithReferences = ($__ScopeChainBuilderWithReferences_46_js__ = require("./ScopeChainBuilderWithReferences.js"), $__ScopeChainBuilderWithReferences_46_js__ && $__ScopeChainBuilderWithReferences_46_js__.__esModule && $__ScopeChainBuilderWithReferences_46_js__ || {default: $__ScopeChainBuilderWithReferences_46_js__}).ScopeChainBuilderWithReferences;
var FreeVariableChecker = function($__super) {
function FreeVariableChecker(reporter, global) {
$traceurRuntime.superConstructor(FreeVariableChecker).call(this, reporter);
this.global_ = global;
}
return ($traceurRuntime.createClass)(FreeVariableChecker, {referenceFound: function(tree, name) {
if (this.scope.getBinding(tree))
return;
if (!(name in this.global_)) {
this.reporter.reportError(tree.location, (name + " is not defined"));
}
}}, {}, $__super);
}(ScopeChainBuilderWithReferences);
function validate(tree, reporter) {
var global = arguments[2] !== (void 0) ? arguments[2] : Reflect.global;
var checker = new FreeVariableChecker(reporter, global);
checker.visitAny(tree);
}
Object.defineProperties(module.exports, {
validate: {get: function() {
return validate;
}},
__esModule: {value: true}
});
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'pagebreak', 'pl', {
alt: 'Wstaw podział strony',
toolbar: 'Wstaw podział strony'
} );
|
Package.describe({
summary: "Password support for accounts",
version: "1.1.3"
});
Package.onUse(function(api) {
api.use('npm-bcrypt@=0.7.8_2');
api.use([
'accounts-base',
'srp',
'sha',
'ejson',
'ddp'
], ['client', 'server']);
// Export Accounts (etc) to packages using this one.
api.imply('accounts-base', ['client', 'server']);
api.use('email', ['server']);
api.use('random', ['server']);
api.use('check');
api.use('underscore');
api.addFiles('email_templates.js', 'server');
api.addFiles('password_server.js', 'server');
api.addFiles('password_client.js', 'client');
});
Package.onTest(function(api) {
api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker',
'accounts-base', 'random', 'email', 'underscore', 'check',
'ddp']);
api.addFiles('password_tests_setup.js', 'server');
api.addFiles('password_tests.js', ['client', 'server']);
api.addFiles('email_tests_setup.js', 'server');
api.addFiles('email_tests.js', 'client');
});
|
/* */
(function(Buffer) {
var assert = require("assert");
var BN = require("../../lib/bn").BN;
var fixtures = require("../fixtures");
describe('BN.js/Slow DH test', function() {
var groups = fixtures.dhGroups;
Object.keys(groups).forEach(function(name) {
it('should match public key for ' + name + ' group', function() {
var group = groups[name];
this.timeout(3600 * 1000);
var base = new BN(2);
var mont = BN.red(new BN(group.prime, 16));
var priv = new BN(group.priv, 16);
var multed = base.toRed(mont).redPow(priv).fromRed();
var actual = new Buffer(multed.toArray());
assert.equal(actual.toString('hex'), group.pub);
});
});
});
})(require("buffer").Buffer);
|
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Defines a 2-element vector class that can be used for
* coordinate math, useful for animation systems and point manipulation.
*
* Vec2 objects inherit from goog.math.Coordinate and may be used wherever a
* Coordinate is required. Where appropriate, Vec2 functions accept both Vec2
* and Coordinate objects as input.
*
* @author brenneman@google.com (Shawn Brenneman)
*/
goog.provide('goog.math.Vec2');
goog.require('goog.math');
goog.require('goog.math.Coordinate');
/**
* Class for a two-dimensional vector object and assorted functions useful for
* manipulating points.
*
* @param {number} x The x coordinate for the vector.
* @param {number} y The y coordinate for the vector.
* @struct
* @constructor
* @extends {goog.math.Coordinate}
*/
goog.math.Vec2 = function(x, y) {
/**
* X-value
* @type {number}
*/
this.x = x;
/**
* Y-value
* @type {number}
*/
this.y = y;
};
goog.inherits(goog.math.Vec2, goog.math.Coordinate);
/**
* @return {!goog.math.Vec2} A random unit-length vector.
*/
goog.math.Vec2.randomUnit = function() {
var angle = Math.random() * Math.PI * 2;
return new goog.math.Vec2(Math.cos(angle), Math.sin(angle));
};
/**
* @return {!goog.math.Vec2} A random vector inside the unit-disc.
*/
goog.math.Vec2.random = function() {
var mag = Math.sqrt(Math.random());
var angle = Math.random() * Math.PI * 2;
return new goog.math.Vec2(Math.cos(angle) * mag, Math.sin(angle) * mag);
};
/**
* Returns a new Vec2 object from a given coordinate.
* @param {!goog.math.Coordinate} a The coordinate.
* @return {!goog.math.Vec2} A new vector object.
*/
goog.math.Vec2.fromCoordinate = function(a) {
return new goog.math.Vec2(a.x, a.y);
};
/**
* @return {!goog.math.Vec2} A new vector with the same coordinates as this one.
* @override
*/
goog.math.Vec2.prototype.clone = function() {
return new goog.math.Vec2(this.x, this.y);
};
/**
* Returns the magnitude of the vector measured from the origin.
* @return {number} The length of the vector.
*/
goog.math.Vec2.prototype.magnitude = function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/**
* Returns the squared magnitude of the vector measured from the origin.
* NOTE(brenneman): Leaving out the square root is not a significant
* optimization in JavaScript.
* @return {number} The length of the vector, squared.
*/
goog.math.Vec2.prototype.squaredMagnitude = function() {
return this.x * this.x + this.y * this.y;
};
/**
* @return {!goog.math.Vec2} This coordinate after scaling.
* @override
*/
goog.math.Vec2.prototype.scale =
/** @type {function(number, number=):!goog.math.Vec2} */
(goog.math.Coordinate.prototype.scale);
/**
* Reverses the sign of the vector. Equivalent to scaling the vector by -1.
* @return {!goog.math.Vec2} The inverted vector.
*/
goog.math.Vec2.prototype.invert = function() {
this.x = -this.x;
this.y = -this.y;
return this;
};
/**
* Normalizes the current vector to have a magnitude of 1.
* @return {!goog.math.Vec2} The normalized vector.
*/
goog.math.Vec2.prototype.normalize = function() {
return this.scale(1 / this.magnitude());
};
/**
* Adds another vector to this vector in-place.
* @param {!goog.math.Coordinate} b The vector to add.
* @return {!goog.math.Vec2} This vector with {@code b} added.
*/
goog.math.Vec2.prototype.add = function(b) {
this.x += b.x;
this.y += b.y;
return this;
};
/**
* Subtracts another vector from this vector in-place.
* @param {!goog.math.Coordinate} b The vector to subtract.
* @return {!goog.math.Vec2} This vector with {@code b} subtracted.
*/
goog.math.Vec2.prototype.subtract = function(b) {
this.x -= b.x;
this.y -= b.y;
return this;
};
/**
* Rotates this vector in-place by a given angle, specified in radians.
* @param {number} angle The angle, in radians.
* @return {!goog.math.Vec2} This vector rotated {@code angle} radians.
*/
goog.math.Vec2.prototype.rotate = function(angle) {
var cos = Math.cos(angle);
var sin = Math.sin(angle);
var newX = this.x * cos - this.y * sin;
var newY = this.y * cos + this.x * sin;
this.x = newX;
this.y = newY;
return this;
};
/**
* Rotates a vector by a given angle, specified in radians, relative to a given
* axis rotation point. The returned vector is a newly created instance - no
* in-place changes are done.
* @param {!goog.math.Vec2} v A vector.
* @param {!goog.math.Vec2} axisPoint The rotation axis point.
* @param {number} angle The angle, in radians.
* @return {!goog.math.Vec2} The rotated vector in a newly created instance.
*/
goog.math.Vec2.rotateAroundPoint = function(v, axisPoint, angle) {
var res = v.clone();
return res.subtract(axisPoint).rotate(angle).add(axisPoint);
};
/**
* Compares this vector with another for equality.
* @param {!goog.math.Vec2} b The other vector.
* @return {boolean} Whether this vector has the same x and y as the given
* vector.
*/
goog.math.Vec2.prototype.equals = function(b) {
return this == b || !!b && this.x == b.x && this.y == b.y;
};
/**
* Returns the distance between two vectors.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {number} The distance.
*/
goog.math.Vec2.distance = goog.math.Coordinate.distance;
/**
* Returns the squared distance between two vectors.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {number} The squared distance.
*/
goog.math.Vec2.squaredDistance = goog.math.Coordinate.squaredDistance;
/**
* Compares vectors for equality.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {boolean} Whether the vectors have the same x and y coordinates.
*/
goog.math.Vec2.equals = goog.math.Coordinate.equals;
/**
* Returns the sum of two vectors as a new Vec2.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {!goog.math.Vec2} The sum vector.
*/
goog.math.Vec2.sum = function(a, b) {
return new goog.math.Vec2(a.x + b.x, a.y + b.y);
};
/**
* Returns the difference between two vectors as a new Vec2.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {!goog.math.Vec2} The difference vector.
*/
goog.math.Vec2.difference = function(a, b) {
return new goog.math.Vec2(a.x - b.x, a.y - b.y);
};
/**
* Returns the dot-product of two vectors.
* @param {!goog.math.Coordinate} a The first vector.
* @param {!goog.math.Coordinate} b The second vector.
* @return {number} The dot-product of the two vectors.
*/
goog.math.Vec2.dot = function(a, b) {
return a.x * b.x + a.y * b.y;
};
/**
* Returns the determinant of two vectors.
* @param {!goog.math.Vec2} a The first vector.
* @param {!goog.math.Vec2} b The second vector.
* @return {number} The determinant of the two vectors.
*/
goog.math.Vec2.determinant = function(a, b) {
return a.x * b.y - a.y * b.x;
};
/**
* Returns a new Vec2 that is the linear interpolant between vectors a and b at
* scale-value x.
* @param {!goog.math.Coordinate} a Vector a.
* @param {!goog.math.Coordinate} b Vector b.
* @param {number} x The proportion between a and b.
* @return {!goog.math.Vec2} The interpolated vector.
*/
goog.math.Vec2.lerp = function(a, b, x) {
return new goog.math.Vec2(
goog.math.lerp(a.x, b.x, x), goog.math.lerp(a.y, b.y, x));
};
|
(function() {
// Based on http://vis.stanford.edu/protovis/ex/qqplot.html
d3.qq = function() {
var width = 1,
height = 1,
duration = 0,
domain = null,
tickFormat = null,
n = 100,
x = qqX,
y = qqY;
// For each small multiple…
function qq(g) {
g.each(function(d, i) {
var g = d3.select(this),
qx = qqQuantiles(n, x.call(this, d, i)),
qy = qqQuantiles(n, y.call(this, d, i)),
xd = domain && domain.call(this, d, i) || [d3.min(qx), d3.max(qx)], // new x-domain
yd = domain && domain.call(this, d, i) || [d3.min(qy), d3.max(qy)], // new y-domain
x0, // old x-scale
y0; // old y-scale
// Compute the new x-scale.
var x1 = d3.scale.linear()
.domain(xd)
.range([0, width]);
// Compute the new y-scale.
var y1 = d3.scale.linear()
.domain(yd)
.range([height, 0]);
// Retrieve the old scales, if this is an update.
if (this.__chart__) {
x0 = this.__chart__.x;
y0 = this.__chart__.y;
} else {
x0 = d3.scale.linear().domain([0, Infinity]).range(x1.range());
y0 = d3.scale.linear().domain([0, Infinity]).range(y1.range());
}
// Stash the new scales.
this.__chart__ = {x: x1, y: y1};
// Update diagonal line.
var diagonal = g.selectAll("line.diagonal")
.data([null]);
diagonal.enter().append("svg:line")
.attr("class", "diagonal")
.attr("x1", x1(yd[0]))
.attr("y1", y1(xd[0]))
.attr("x2", x1(yd[1]))
.attr("y2", y1(xd[1]));
diagonal.transition()
.duration(duration)
.attr("x1", x1(yd[0]))
.attr("y1", y1(xd[0]))
.attr("x2", x1(yd[1]))
.attr("y2", y1(xd[1]));
// Update quantile plots.
var circle = g.selectAll("circle")
.data(d3.range(n).map(function(i) {
return {x: qx[i], y: qy[i]};
}));
circle.enter().append("svg:circle")
.attr("class", "quantile")
.attr("r", 4.5)
.attr("cx", function(d) { return x0(d.x); })
.attr("cy", function(d) { return y0(d.y); })
.style("opacity", 1e-6)
.transition()
.duration(duration)
.attr("cx", function(d) { return x1(d.x); })
.attr("cy", function(d) { return y1(d.y); })
.style("opacity", 1);
circle.transition()
.duration(duration)
.attr("cx", function(d) { return x1(d.x); })
.attr("cy", function(d) { return y1(d.y); })
.style("opacity", 1);
circle.exit().transition()
.duration(duration)
.attr("cx", function(d) { return x1(d.x); })
.attr("cy", function(d) { return y1(d.y); })
.style("opacity", 1e-6)
.remove();
var xformat = tickFormat || x1.tickFormat(4),
yformat = tickFormat || y1.tickFormat(4),
tx = function(d) { return "translate(" + x1(d) + "," + height + ")"; },
ty = function(d) { return "translate(0," + y1(d) + ")"; };
// Update x-ticks.
var xtick = g.selectAll("g.x.tick")
.data(x1.ticks(4), function(d) {
return this.textContent || xformat(d);
});
var xtickEnter = xtick.enter().append("svg:g")
.attr("class", "x tick")
.attr("transform", function(d) { return "translate(" + x0(d) + "," + height + ")"; })
.style("opacity", 1e-6);
xtickEnter.append("svg:line")
.attr("y1", 0)
.attr("y2", -6);
xtickEnter.append("svg:text")
.attr("text-anchor", "middle")
.attr("dy", "1em")
.text(xformat);
// Transition the entering ticks to the new scale, x1.
xtickEnter.transition()
.duration(duration)
.attr("transform", tx)
.style("opacity", 1);
// Transition the updating ticks to the new scale, x1.
xtick.transition()
.duration(duration)
.attr("transform", tx)
.style("opacity", 1);
// Transition the exiting ticks to the new scale, x1.
xtick.exit().transition()
.duration(duration)
.attr("transform", tx)
.style("opacity", 1e-6)
.remove();
// Update ticks.
var ytick = g.selectAll("g.y.tick")
.data(y1.ticks(4), function(d) {
return this.textContent || yformat(d);
});
var ytickEnter = ytick.enter().append("svg:g")
.attr("class", "y tick")
.attr("transform", function(d) { return "translate(0," + y0(d) + ")"; })
.style("opacity", 1e-6);
ytickEnter.append("svg:line")
.attr("x1", 0)
.attr("x2", 6);
ytickEnter.append("svg:text")
.attr("text-anchor", "end")
.attr("dx", "-.5em")
.attr("dy", ".3em")
.text(yformat);
// Transition the entering ticks to the new scale, y1.
ytickEnter.transition()
.duration(duration)
.attr("transform", ty)
.style("opacity", 1);
// Transition the updating ticks to the new scale, y1.
ytick.transition()
.duration(duration)
.attr("transform", ty)
.style("opacity", 1);
// Transition the exiting ticks to the new scale, y1.
ytick.exit().transition()
.duration(duration)
.attr("transform", ty)
.style("opacity", 1e-6)
.remove();
});
}
qq.width = function(x) {
if (!arguments.length) return width;
width = x;
return qq;
};
qq.height = function(x) {
if (!arguments.length) return height;
height = x;
return qq;
};
qq.duration = function(x) {
if (!arguments.length) return duration;
duration = x;
return qq;
};
qq.domain = function(x) {
if (!arguments.length) return domain;
domain = x == null ? x : d3.functor(x);
return qq;
};
qq.count = function(z) {
if (!arguments.length) return n;
n = z;
return qq;
};
qq.x = function(z) {
if (!arguments.length) return x;
x = z;
return qq;
};
qq.y = function(z) {
if (!arguments.length) return y;
y = z;
return qq;
};
qq.tickFormat = function(x) {
if (!arguments.length) return tickFormat;
tickFormat = x;
return qq;
};
return qq;
};
function qqQuantiles(n, values) {
var m = values.length - 1;
values = values.slice().sort(d3.ascending);
return d3.range(n).map(function(i) {
return values[~~(i * m / n)];
});
}
function qqX(d) {
return d.x;
}
function qqY(d) {
return d.y;
}
})();
|
/*! hyperform.js.org */
'use strict';
function trigger_event (element, event) {
var _ref = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var _ref$bubbles = _ref.bubbles;
var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles;
var _ref$cancelable = _ref.cancelable;
var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable;
if (!(event instanceof window.Event)) {
var _event = document.createEvent('Event');
_event.initEvent(event, bubbles, cancelable);
event = _event;
}
element.dispatchEvent(event);
return event;
}
/* and datetime-local? Spec says “Nah!” */
var dates = ['datetime', 'date', 'month', 'week', 'time'];
var plain_numbers = ['number', 'range'];
/* everything that returns something meaningful for valueAsNumber and
* can have the step attribute */
var numbers = dates.concat(plain_numbers, 'datetime-local');
/* the spec says to only check those for syntax in validity.typeMismatch.
* ¯\_(ツ)_/¯ */
var type_checked = ['email', 'url'];
/* check these for validity.badInput */
var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color'];
var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked);
/* input element types, that are candidates for the validation API.
* Missing from this set are: button, hidden, menu (from <button>), reset and
* the types for non-<input> elements. */
var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types);
/* all known types of <input> */
var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates);
/* apparently <select> and <textarea> have types of their own */
var non_inputs = ['select-one', 'select-multiple', 'textarea'];
/**
* mark an object with a '__hyperform=true' property
*
* We use this to distinguish our properties from the native ones. Usage:
* js> mark(obj);
* js> assert(obj.__hyperform === true)
*/
function mark (obj) {
if (['object', 'function'].indexOf(typeof obj) > -1) {
delete obj.__hyperform;
Object.defineProperty(obj, '__hyperform', {
configurable: true,
enumerable: false,
value: true
});
}
return obj;
}
/**
* the internal storage for messages
*/
var store = new WeakMap();
/* jshint -W053 */
var message_store = {
set: function set(element, message) {
var is_custom = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
if (element instanceof window.HTMLFieldSetElement) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && !wrapped_form.settings.extend_fieldset) {
/* make this a no-op for <fieldset> in strict mode */
return message_store;
}
}
if (typeof message === 'string') {
message = new String(message);
}
if (is_custom) {
message.is_custom = true;
}
mark(message);
store.set(element, message);
/* allow the :invalid selector to match */
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity(message.toString());
}
return message_store;
},
get: function get(element) {
var message = store.get(element);
if (message === undefined && '_original_validationMessage' in element) {
/* get the browser's validation message, if we have none. Maybe it
* knows more than we. */
message = new String(element._original_validationMessage);
}
return message ? message : new String('');
},
delete: function _delete(element) {
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity('');
}
return store.delete(element);
}
};
/**
* counter that will be incremented with every call
*
* Will enforce uniqueness, as long as no more than 1 hyperform scripts
* are loaded. (In that case we still have the "random" part below.)
*/
var uid = 0;
/**
* generate a random ID
*
* @see https://gist.github.com/gordonbrander/2230317
*/
function generate_id () {
var prefix = arguments.length <= 0 || arguments[0] === undefined ? 'hf_' : arguments[0];
return prefix + uid++ + Math.random().toString(36).substr(2);
}
var warnings_cache = new WeakMap();
var DefaultRenderer = {
/**
* called when a warning should become visible
*/
attach_warning: function attach_warning(warning, element) {
/* should also work, if element is last,
* http://stackoverflow.com/a/4793630/113195 */
element.parentNode.insertBefore(warning, element.nextSibling);
},
/**
* called when a warning should vanish
*/
detach_warning: function detach_warning(warning, element) {
warning.parentNode.removeChild(warning);
},
/**
* called when feedback to an element's state should be handled
*
* i.e., showing and hiding warnings
*/
show_warning: function show_warning(element) {
var sub_radio = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var msg = message_store.get(element).toString();
var warning = warnings_cache.get(element);
if (msg) {
if (!warning) {
var wrapper = get_wrapper(element);
warning = document.createElement('div');
warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning';
warning.id = generate_id();
warning.setAttribute('aria-live', 'polite');
warnings_cache.set(element, warning);
}
element.setAttribute('aria-errormessage', warning.id);
warning.textContent = msg;
Renderer.attach_warning(warning, element);
} else if (warning && warning.parentNode) {
element.removeAttribute('aria-errormessage');
Renderer.detach_warning(warning, element);
}
if (!sub_radio && element.type === 'radio' && element.form) {
/* render warnings for all other same-name radios, too */
Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form;
}).map(function (radio) {
return Renderer.show_warning(radio, 'sub_radio');
});
}
}
};
var Renderer = {
attach_warning: DefaultRenderer.attach_warning,
detach_warning: DefaultRenderer.detach_warning,
show_warning: DefaultRenderer.show_warning,
set: function set(renderer, action) {
if (!action) {
action = DefaultRenderer[renderer];
}
Renderer[renderer] = action;
}
};
/**
* check element's validity and report an error back to the user
*/
function reportValidity(element) {
/* if this is a <form>, report validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, reportValidity).every(function (b) {
return b;
});
}
/* we copy checkValidity() here, b/c we have to check if the "invalid"
* event was canceled. */
var valid = ValidityState(element).valid;
var event;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.valid_event) {
event = trigger_event(element, 'valid', { cancelable: true });
}
} else {
event = trigger_event(element, 'invalid', { cancelable: true });
}
if (!event || !event.defaultPrevented) {
Renderer.show_warning(element);
}
return valid;
}
function check(event) {
event.preventDefault();
/* trigger a "validate" event on the form to be submitted */
var val_event = trigger_event(event.target.form, 'validate', { cancelable: true });
if (val_event.defaultPrevented) {
/* skip the whole submit thing, if the validation is canceled. A user
* can still call form.submit() afterwards. */
return;
}
var valid = true;
var first_invalid;
Array.prototype.map.call(event.target.form.elements, function (element) {
if (!reportValidity(element)) {
valid = false;
if (!first_invalid && 'focus' in element) {
first_invalid = element;
}
}
});
if (valid) {
/* apparently, the submit event is not triggered in most browsers on
* the submit() method, so we do it manually here to model a natural
* submit as closely as possible. */
var submit_event = trigger_event(event.target.form, 'submit', { cancelable: true });
if (!submit_event.defaultPrevented) {
event.target.form.submit();
}
} else if (first_invalid) {
/* focus the first invalid element, if validation went south */
first_invalid.focus();
}
}
/**
* test if node is a submit button
*/
function is_submit_button(node) {
return(
/* must be an input or button element... */
(node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && (
/* ...and have a submitting type */
node.type === 'image' || node.type === 'submit')
);
}
/**
* test, if the click event would trigger a submit
*/
function is_submitting_click(event) {
return(
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* left button or middle button (submits in Chrome) */
!('button' in event) || event.button < 2) &&
/* must be a submit button... */
is_submit_button(event.target) &&
/* if validation should be ignored, we're not interested anyhow */
!event.target.hasAttribute('formnovalidate') &&
/* the button needs a form, that's going to be submitted */
event.target.form &&
/* again, if the form should not be validated, we're out of the game */
!event.target.form.hasAttribute('novalidate')
);
}
/**
* test, if the keypress event would trigger a submit
*/
function is_submitting_keypress(event) {
return(
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* <Enter> was pressed... */
event.keyCode === 13 &&
/* ...on an <input> or <button> */
event.target.nodeName === 'INPUT' &&
/* this is a standard text input field (not checkbox, ...) */
text_types.indexOf(event.target.type) > -1 ||
/* or <Enter> or <Space> was pressed... */
(event.keyCode === 13 || event.keyCode === 32) &&
/* ...on a submit button */
is_submit_button(event.target)) &&
/* there's a form... */
event.target.form &&
/* ...and the form allows validation */
!event.target.form.hasAttribute('novalidate')
);
}
/**
* catch explicit submission by click on a button
*/
function click_handler(event) {
if (is_submitting_click(event)) {
check(event);
}
}
/**
* catch explicit submission by click on a button, but circumvent validation
*/
function ignored_click_handler(event) {
if (is_submitting_click(event)) {
event.target.form.submit();
}
}
/**
* catch implicit submission by pressing <Enter> in some situations
*/
function keypress_handler(event) {
if (is_submitting_keypress(event)) {
/* check, that there is no submit button in the form. Otherwise
* that should be clicked. */
var el = event.target.form.elements.length;
var submit;
for (var i = 0; i < el; i++) {
if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) {
submit = event.target.form.elements[i];
break;
}
}
if (submit) {
event.preventDefault();
submit.click();
} else {
check(event);
}
}
}
/**
* catch implicit submission by pressing <Enter> in some situations, but circumvent validation
*/
function ignored_keypress_handler(event) {
if (is_submitting_keypress(event)) {
/* check, that there is no submit button in the form. Otherwise
* that should be clicked. */
var el = event.target.form.elements.length;
var submit;
for (var i = 0; i < el; i++) {
if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) {
submit = event.target.form.elements[i];
break;
}
}
if (submit) {
event.preventDefault();
submit.click();
} else {
event.target.form.submit();
}
}
}
/**
* catch all relevant events _prior_ to a form being submitted
*
* @param bool ignore bypass validation, when an attempt to submit the
* form is detected.
*/
function catch_submit(listening_node) {
var ignore = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (ignore) {
listening_node.addEventListener('click', ignored_click_handler);
listening_node.addEventListener('keypress', ignored_keypress_handler);
} else {
listening_node.addEventListener('click', click_handler);
listening_node.addEventListener('keypress', keypress_handler);
}
}
/**
* decommission the event listeners from catch_submit() again
*/
function uncatch_submit(listening_node) {
listening_node.removeEventListener('click', ignored_click_handler);
listening_node.removeEventListener('keypress', ignored_keypress_handler);
listening_node.removeEventListener('click', click_handler);
listening_node.removeEventListener('keypress', keypress_handler);
}
/**
* remove `property` from element and restore _original_property, if present
*/
function uninstall_property (element, property) {
delete element[property];
var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property);
if (original_descriptor) {
Object.defineProperty(element, property, original_descriptor);
}
}
/**
* add `property` to an element
*
* js> installer(element, 'foo', { value: 'bar' });
* js> assert(element.foo === 'bar');
*/
function install_property (element, property, descriptor) {
descriptor.configurable = true;
descriptor.enumerable = true;
if ('value' in descriptor) {
descriptor.writable = true;
}
var original_descriptor = Object.getOwnPropertyDescriptor(element, property);
if (original_descriptor) {
/* we already installed that property... */
if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) {
return;
}
/* publish existing property under new name, if it's not from us */
Object.defineProperty(element, '_original_' + property, original_descriptor);
}
delete element[property];
Object.defineProperty(element, property, descriptor);
}
/**
* set a custom validity message or delete it with an empty string
*/
function setCustomValidity(element, msg) {
message_store.set(element, msg, true);
}
function sprintf (str) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var args_length = args.length;
var global_index = 0;
return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) {
var local_index = global_index;
if (position) {
local_index = Number(position.replace(/\$$/, '')) - 1;
}
global_index += 1;
var arg = '';
if (args_length > local_index) {
arg = args[local_index];
}
if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) {
/* try getting a localized representation of dates and numbers, if the
* browser supports this */
if (type === 'l') {
arg = (arg.toLocaleString || arg.toString).call(arg);
} else {
arg = arg.toString();
}
}
return arg;
});
}
/* For a given date, get the ISO week number
*
* Source: http://stackoverflow.com/a/6117889/113195
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function get_week_of_year (d) {
/* Copy date so don't modify original */
d = new Date(+d);
d.setUTCHours(0, 0, 0);
/* Set to nearest Thursday: current date + 4 - current day number
* Make Sunday's day number 7 */
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
/* Get first day of year */
var yearStart = new Date(d.getUTCFullYear(), 0, 1);
/* Calculate full weeks to nearest Thursday */
var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
/* Return array of year and week number */
return [d.getUTCFullYear(), weekNo];
}
function pad(num) {
var size = arguments.length <= 1 || arguments[1] === undefined ? 2 : arguments[1];
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
/**
* calculate a string from a date according to HTML5
*/
function date_to_string(date, element_type) {
if (!(date instanceof Date)) {
return null;
}
switch (element_type) {
case 'datetime':
return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time');
case 'datetime-local':
return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
case 'date':
return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate()));
case 'month':
return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1));
case 'week':
var params = get_week_of_year(date);
return sprintf.call(null, '%s-W%s', params[0], pad(params[1]));
case 'time':
return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
}
return null;
}
/**
* return a new Date() representing the ISO date for a week number
*
* @see http://stackoverflow.com/a/16591175/113195
*/
function get_date_from_week (week, year) {
var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7));
if (date.getUTCDay() <= 4 /* thursday */) {
date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1);
} else {
date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay());
}
return date;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_date (string, element_type) {
var date = new Date(0);
var ms;
switch (element_type) {
case 'datetime':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$7 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms));
return date;
case 'date':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
return date;
case 'month':
if (!/^([0-9]{4,})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, 1);
return date;
case 'week':
if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) {
return null;
}
return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1));
case 'time':
if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$4 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(ms));
return date;
}
return null;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_number (string, element_type) {
var rval = string_to_date(string, element_type);
if (rval !== null) {
return +rval;
}
/* not parseFloat, because we want NaN for invalid values like "1.2xxy" */
return Number(string);
}
/**
* get the element's type in a backwards-compatible way
*/
function get_type (element) {
if (element instanceof window.HTMLTextAreaElement) {
return 'textarea';
} else if (element instanceof window.HTMLSelectElement) {
return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one';
} else if (element instanceof window.HTMLButtonElement) {
return (element.getAttribute('type') || 'submit').toLowerCase();
} else if (element instanceof window.HTMLInputElement) {
var attr = (element.getAttribute('type') || '').toLowerCase();
if (attr && inputs.indexOf(attr) > -1) {
return attr;
} else {
/* perhaps the DOM has in-depth knowledge. Take that before returning
* 'text'. */
return element.type || 'text';
}
}
return '';
}
/**
* the following validation messages are from Firefox source,
* http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties
* released under MPL license, http://mozilla.org/MPL/2.0/.
*/
var catalog = {
en: {
TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).',
ValueMissing: 'Please fill out this field.',
CheckboxMissing: 'Please check this box if you want to proceed.',
RadioMissing: 'Please select one of these options.',
FileMissing: 'Please select a file.',
SelectMissing: 'Please select an item in the list.',
InvalidEmail: 'Please enter an email address.',
InvalidURL: 'Please enter a URL.',
PatternMismatch: 'Please match the requested format.',
PatternMismatchWithTitle: 'Please match the requested format: %l.',
NumberRangeOverflow: 'Please select a value that is no more than %l.',
DateRangeOverflow: 'Please select a value that is no later than %l.',
TimeRangeOverflow: 'Please select a value that is no later than %l.',
NumberRangeUnderflow: 'Please select a value that is no less than %l.',
DateRangeUnderflow: 'Please select a value that is no earlier than %l.',
TimeRangeUnderflow: 'Please select a value that is no earlier than %l.',
StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.',
StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.',
BadInputNumber: 'Please enter a number.'
}
};
var language = 'en';
function set_language(newlang) {
language = newlang;
}
function add_translation(lang, new_catalog) {
if (!(lang in catalog)) {
catalog[lang] = {};
}
for (var key in new_catalog) {
if (new_catalog.hasOwnProperty(key)) {
catalog[lang][key] = new_catalog[key];
}
}
}
function _ (s) {
if (language in catalog && s in catalog[language]) {
return catalog[language][s];
} else if (s in catalog.en) {
return catalog.en[s];
}
return s;
}
var default_step = {
'datetime-local': 60,
datetime: 60,
time: 60
};
var step_scale_factor = {
'datetime-local': 1000,
datetime: 1000,
date: 86400000,
week: 604800000,
time: 1000
};
var default_step_base = {
week: -259200000
};
var default_min = {
range: 0
};
var default_max = {
range: 100
};
/**
* get previous and next valid values for a stepped input element
*/
function get_next_valid (element) {
var n = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
var type = get_type(element);
var aMin = element.getAttribute('min');
var min = default_min[type] || NaN;
if (aMin) {
var pMin = string_to_number(aMin, type);
if (!isNaN(pMin)) {
min = pMin;
}
}
var aMax = element.getAttribute('max');
var max = default_max[type] || NaN;
if (aMax) {
var pMax = string_to_number(aMax, type);
if (!isNaN(pMax)) {
max = pMax;
}
}
var aStep = element.getAttribute('step');
var step = default_step[type] || 1;
if (aStep && aStep.toLowerCase() === 'any') {
/* quick return: we cannot calculate prev and next */
return [_('any value'), _('any value')];
} else if (aStep) {
var pStep = string_to_number(aStep, type);
if (!isNaN(pStep)) {
step = pStep;
}
}
var default_value = string_to_number(element.getAttribute('value'), type);
var value = string_to_number(element.value || element.getAttribute('value'), type);
if (isNaN(value)) {
/* quick return: we cannot calculate without a solid base */
return [_('any valid value'), _('any valid value')];
}
var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0;
var scale = step_scale_factor[type] || 1;
var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n;
var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n;
if (prev < min) {
prev = null;
} else if (prev > max) {
prev = max;
}
if (next > max) {
next = null;
} else if (next < min) {
next = min;
}
/* convert to date objects, if appropriate */
if (dates.indexOf(type) > -1) {
prev = date_to_string(new Date(prev), type);
next = date_to_string(new Date(next), type);
}
return [prev, next];
}
/**
* implement the valueAsDate functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
*/
function valueAsDate(element) {
var value = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];
var type = get_type(element);
if (dates.indexOf(type) > -1) {
if (value !== undefined) {
/* setter: value must be null or a Date() */
if (value === null) {
element.value = '';
} else if (value instanceof Date) {
if (isNaN(value.getTime())) {
element.value = '';
} else {
element.value = date_to_string(value, type);
}
} else {
throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError');
}
return;
}
var value_date = string_to_date(element.value, type);
return value_date instanceof Date ? value_date : null;
} else if (value !== undefined) {
/* trying to set a date on a not-date input fails */
throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError');
}
return null;
}
/**
* implement the valueAsNumber functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber
*/
function valueAsNumber(element) {
var value = arguments.length <= 1 || arguments[1] === undefined ? undefined : arguments[1];
var type = get_type(element);
if (numbers.indexOf(type) > -1) {
if (type === 'range' && element.hasAttribute('multiple')) {
/* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */
return NaN;
}
if (value !== undefined) {
/* setter: value must be NaN or a finite number */
if (isNaN(value)) {
element.value = '';
} else if (typeof value === 'number' && window.isFinite(value)) {
try {
/* try setting as a date, but... */
valueAsDate(element, new Date(value));
} catch (e) {
/* ... when valueAsDate is not responsible, ... */
if (!(e instanceof window.DOMException)) {
throw e;
}
/* ... set it via Number.toString(). */
element.value = value.toString();
}
} else {
throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError');
}
return;
}
return string_to_number(element.value, type);
} else if (value !== undefined) {
/* trying to set a number on a not-number input fails */
throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError');
}
return NaN;
}
/**
*
*/
function stepDown(element) {
var n = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError');
}
var _get_next_valid = get_next_valid(element, n);
var prev = _get_next_valid.prev;
var next = _get_next_valid.next;
if (prev !== null) {
valueAsNumber(element, prev);
}
}
/**
*
*/
function stepUp(element) {
var n = arguments.length <= 1 || arguments[1] === undefined ? 1 : arguments[1];
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError');
}
var _get_next_valid = get_next_valid(element, n);
var prev = _get_next_valid.prev;
var next = _get_next_valid.next;
if (next !== null) {
valueAsNumber(element, next);
}
}
/**
* get the validation message for an element, empty string, if the element
* satisfies all constraints.
*/
function validationMessage(element) {
var msg = message_store.get(element);
if (!msg) {
return '';
}
/* make it a primitive again, since message_store returns String(). */
return msg.toString();
}
/**
* check, if an element will be subject to HTML5 validation at all
*/
function willValidate(element) {
return is_validation_candidate(element);
}
var gA = function gA(prop) {
return function () {
return this.getAttribute(prop);
};
};
var sA = function sA(prop) {
return function (value) {
this.setAttribute(prop, value);
};
};
var gAb = function gAb(prop) {
return function () {
return this.hasAttribute(prop);
};
};
var sAb = function sAb(prop) {
return function (value) {
if (value) {
this.setAttribute(prop, prop);
} else {
this.removeAttribute(prop);
}
};
};
var gAn = function gAn(prop) {
return function () {
return Math.max(0, Number(this.getAttribute(prop)));
};
};
var sAn = function sAn(prop) {
return function (value) {
if (/^[0-9]+$/.test(value)) {
this.setAttribute(prop, value);
}
};
};
function install_properties(element) {
var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step'];
for (var _i = 0; _i < _arr.length; _i++) {
var prop = _arr[_i];
install_property(element, prop, {
get: gA(prop),
set: sA(prop)
});
}
var _arr2 = ['multiple', 'required', 'readOnly'];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var _prop = _arr2[_i2];
install_property(element, _prop, {
get: gAb(_prop.toLowerCase()),
set: sAb(_prop.toLowerCase())
});
}
var _arr3 = ['minLength', 'maxLength'];
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var _prop2 = _arr3[_i3];
install_property(element, _prop2, {
get: gAn(_prop2.toLowerCase()),
set: sAn(_prop2.toLowerCase())
});
}
}
function uninstall_properties(element) {
var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength'];
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var prop = _arr4[_i4];
uninstall_property(element, prop);
}
}
var polyfills = {
checkValidity: {
value: mark(function () {
return checkValidity(this);
})
},
reportValidity: {
value: mark(function () {
return reportValidity(this);
})
},
setCustomValidity: {
value: mark(function (msg) {
return setCustomValidity(this, msg);
})
},
stepDown: {
value: mark(function () {
var n = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
return stepDown(this, n);
})
},
stepUp: {
value: mark(function () {
var n = arguments.length <= 0 || arguments[0] === undefined ? 1 : arguments[0];
return stepUp(this, n);
})
},
validationMessage: {
get: mark(function () {
return validationMessage(this);
})
},
validity: {
get: mark(function () {
return ValidityState(this);
})
},
valueAsDate: {
get: mark(function () {
return valueAsDate(this);
}),
set: mark(function (value) {
valueAsDate(this, value);
})
},
valueAsNumber: {
get: mark(function () {
return valueAsNumber(this);
}),
set: mark(function (value) {
valueAsNumber(this, value);
})
},
willValidate: {
get: mark(function () {
return willValidate(this);
})
}
};
function polyfill (element) {
if (element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement) {
for (var prop in polyfills) {
install_property(element, prop, polyfills[prop]);
}
install_properties(element);
} else if (element instanceof window.HTMLFormElement) {
install_property(element, 'checkValidity', polyfills.checkValidity);
install_property(element, 'reportValidity', polyfills.reportValidity);
}
}
function polyunfill (element) {
if (element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
uninstall_property(element, 'setCustomValidity');
uninstall_property(element, 'stepDown');
uninstall_property(element, 'stepUp');
uninstall_property(element, 'validationMessage');
uninstall_property(element, 'validity');
uninstall_property(element, 'valueAsDate');
uninstall_property(element, 'valueAsNumber');
uninstall_property(element, 'willValidate');
uninstall_properties(element);
} else if (element instanceof window.HTMLFormElement) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
}
}
var instances = new WeakMap();
/**
* wrap <form>s, window or document, that get treated with the global
* hyperform()
*/
function Wrapper(form, settings) {
/* do not allow more than one instance per form. Otherwise we'd end
* up with double event handlers, polyfills re-applied, ... */
var existing = instances.get(form);
if (existing) {
existing.settings = settings;
return existing;
}
this.form = form;
this.settings = settings;
this.revalidator = this.revalidate.bind(this);
instances.set(form, this);
catch_submit(form, settings.revalidate === 'never');
if (form === window || form instanceof window.HTMLDocument) {
/* install on the prototypes, when called for the whole document */
this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyfill(window.HTMLFormElement);
} else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) {
this.install(form.elements);
if (form instanceof window.HTMLFormElement) {
polyfill(form);
}
}
if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') {
/* in a perfect world we'd just bind to "input", but support here is
* abysmal: http://caniuse.com/#feat=input-event */
form.addEventListener('keyup', this.revalidator);
form.addEventListener('change', this.revalidator);
}
if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') {
/* useCapture=true, because `blur` doesn't bubble. See
* https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation
* for a discussion */
form.addEventListener('blur', this.revalidator, true);
}
}
Wrapper.prototype = {
destroy: function destroy() {
uncatch_submit(this.form);
instances.delete(this.form);
this.form.removeEventListener('keyup', this.revalidator);
this.form.removeEventListener('change', this.revalidator);
this.form.removeEventListener('blur', this.revalidator, true);
if (this.form === window || this.form instanceof window.HTMLDocument) {
this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyunfill(window.HTMLFormElement);
} else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) {
this.uninstall(this.form.elements);
if (this.form instanceof window.HTMLFormElement) {
polyunfill(this.form);
}
}
},
/**
* revalidate an input element
*/
revalidate: function revalidate(event) {
if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) {
if (this.settings.revalidate === 'hybrid') {
/* "hybrid" somewhat simulates what browsers do. See for example
* Firefox's :-moz-ui-invalid pseudo-class:
* https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */
if (event.type === 'blur' && event.target.value !== event.target.defaultValue || event.target.validity.valid) {
/* on blur, update the report when the value has changed from the
* default or when the element is valid (possibly removing a still
* standing invalidity report). */
reportValidity(event.target);
} else if (event.type === 'keyup' || event.type === 'change') {
if (event.target.validity.valid) {
// report instantly, when an element becomes valid,
// postpone report to blur event, when an element is invalid
reportValidity(event.target);
}
}
} else {
reportValidity(event.target);
}
}
},
/**
* install the polyfills on each given element
*
* If you add elements dynamically, you have to call install() on them
* yourself:
*
* js> var form = hyperform(document.forms[0]);
* js> document.forms[0].appendChild(input);
* js> form.install(input);
*
* You can skip this, if you called hyperform on window or document.
*/
install: function install(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyfill(els[i]);
}
},
uninstall: function uninstall(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyunfill(els[i]);
}
}
};
/**
* try to get the appropriate wrapper for a specific element by looking up
* its parent chain
*
* @return Wrapper | undefined
*/
function get_wrapper(element) {
var wrapped;
if (element.form) {
/* try a shortcut with the element's <form> */
wrapped = instances.get(element.form);
}
/* walk up the parent nodes until document (including) */
while (!wrapped && element) {
wrapped = instances.get(element);
element = element.parentNode;
}
if (!wrapped) {
/* try the global instance, if exists. This may also be undefined. */
wrapped = instances.get(window);
}
return wrapped;
}
/**
* check if an element is a candidate for constraint validation
*
* @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation
*/
function is_validation_candidate (element) {
/* it must be any of those elements */
if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) {
var type = get_type(element);
/* its type must be in the whitelist or missing (select, textarea) */
if (!type || non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) {
/* it mustn't be disabled or readonly */
if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) {
var wrapped_form = get_wrapper(element);
/* it hasn't got the (non-standard) attribute 'novalidate' or its
* parent form has got the strict parameter */
if (wrapped_form && wrapped_form.settings.novalidate_on_elements || !element.hasAttribute('novalidate') || !element.noValidate) {
/* it isn't part of a <fieldset disabled> */
var p = element.parentNode;
while (p && p.nodeType === 1) {
if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) {
/* quick return, if it's a child of a disabled fieldset */
return false;
} else if (p.nodeName.toUpperCase() === 'DATALIST') {
/* quick return, if it's a child of a datalist
* Do not use HTMLDataListElement to support older browsers,
* too.
* @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation
*/
return false;
} else if (p === element.form) {
/* the outer boundary. We can stop looking for relevant
* fieldsets. */
break;
}
p = p.parentNode;
}
/* then it's a candidate */
return true;
}
}
}
}
/* this is no HTML5 validation candidate... */
return false;
}
/**
* patch String.length to account for non-BMP characters
*
* @see https://mathiasbynens.be/notes/javascript-unicode
* We do not use the simple [...str].length, because it needs a ton of
* polyfills in older browsers.
*/
function unicode_string_length (str) {
return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length;
}
/**
* internal storage for custom error messages
*/
var store$1 = new WeakMap();
/**
* register custom error messages per element
*/
var custom_messages = {
set: function set(element, validator, message) {
var messages = store$1.get(element) || {};
messages[validator] = message;
store$1.set(element, messages);
return custom_messages;
},
get: function get(element, validator) {
var _default = arguments.length <= 2 || arguments[2] === undefined ? undefined : arguments[2];
var messages = store$1.get(element);
if (messages === undefined || !(validator in messages)) {
var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase();
if (element.hasAttribute(data_id)) {
/* if the element has a data-validator attribute, use this as fallback.
* E.g., if validator == 'valueMissing', the element can specify a
* custom validation message like this:
* <input data-value-missing="Oh noes!">
*/
return element.getAttribute(data_id);
}
return _default;
}
return messages[validator];
},
delete: function _delete(element) {
var validator = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
if (!validator) {
return store$1.delete(element);
}
var messages = store$1.get(element) || {};
if (validator in messages) {
delete messages[validator];
store$1.set(element, messages);
return true;
}
return false;
}
};
var internal_registry = new WeakMap();
/**
* A registry for custom validators
*
* slim wrapper around a WeakMap to ensure the values are arrays
* (hence allowing > 1 validators per element)
*/
var custom_validator_registry = {
set: function set(element, validator) {
var current = internal_registry.get(element) || [];
current.push(validator);
internal_registry.set(element, current);
return custom_validator_registry;
},
get: function get(element) {
return internal_registry.get(element) || [];
},
delete: function _delete(element) {
return internal_registry.delete(element);
}
};
/**
* test whether the element suffers from bad input
*/
function test_bad_input (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || input_checked.indexOf(type) === -1) {
/* we're not interested, thanks! */
return true;
}
/* the browser hides some bad input from the DOM, e.g. malformed numbers,
* email addresses with invalid punycode representation, ... We try to resort
* to the original method here. The assumption is, that a browser hiding
* bad input will hopefully also always support a proper
* ValidityState.badInput */
if (!element.value) {
if ('_original_validity' in element && !element._original_validity.__hyperform) {
return !element._original_validity.badInput;
}
/* no value and no original badInput: Assume all's right. */
return true;
}
var result = true;
switch (type) {
case 'color':
result = /^#[a-f0-9]{6}$/.test(element.value);
break;
case 'number':
case 'range':
result = !isNaN(Number(element.value));
break;
case 'datetime':
case 'date':
case 'month':
case 'week':
case 'time':
result = string_to_date(element.value, type) !== null;
break;
case 'datetime-local':
result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value);
break;
case 'tel':
/* spec says No! Phone numbers can have all kinds of formats, so this
* is expected to be a free-text field. */
// TODO we could allow a setting 'phone_regex' to be evaluated here.
break;
case 'email':
break;
}
return result;
}
/**
* test the max attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_max (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) {
/* we're not responsible here */
return true;
}
var value = void 0,
max = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
max = 1 * (string_to_date(element.getAttribute('max'), type) || NaN);
} else {
value = Number(element.value);
max = Number(element.getAttribute('max'));
}
return isNaN(max) || value <= max;
}
/**
* test the maxlength attribute
*/
function test_maxlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength=""
) {
return true;
}
var maxlength = parseInt(element.getAttribute('maxlength'), 10);
/* check, if the maxlength value is usable at all.
* We allow maxlength === 0 to basically disable input (Firefox does, too).
*/
if (isNaN(maxlength) || maxlength < 0) {
return true;
}
return unicode_string_length(element.value) <= maxlength;
}
/**
* test the min attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_min (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) {
/* we're not responsible here */
return true;
}
var value = void 0,
min = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
min = 1 * (string_to_date(element.getAttribute('min'), type) || NaN);
} else {
value = Number(element.value);
min = Number(element.getAttribute('min'));
}
return isNaN(min) || value >= min;
}
/**
* test the minlength attribute
*/
function test_minlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength=""
) {
return true;
}
var minlength = parseInt(element.getAttribute('minlength'), 10);
/* check, if the minlength value is usable at all. */
if (isNaN(minlength) || minlength < 0) {
return true;
}
return unicode_string_length(element.value) >= minlength;
}
/**
* test the pattern attribute
*/
function test_pattern (element) {
return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value);
}
/**
* test the required attribute
*/
function test_required (element) {
if (!is_validation_candidate(element) || !element.hasAttribute('required')) {
/* nothing to do */
return true;
}
/* we don't need get_type() for element.type, because "checkbox" and "radio"
* are well supported. */
switch (element.type) {
case 'checkbox':
return element.checked;
//break;
case 'radio':
/* radio inputs have "required" fulfilled, if _any_ other radio
* with the same name in this form is checked. */
return !!(element.checked || element.form && Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form && radio.checked;
}).length > 0);
//break;
default:
return !!element.value;
}
}
/**
* test the step attribute
*/
function test_step (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') {
/* we're not responsible here. Note: If no step attribute is given, we
* need to validate against the default step as per spec. */
return true;
}
var step = element.getAttribute('step');
if (step) {
step = string_to_number(step, type);
} else {
step = default_step[type] || 1;
}
if (step <= 0 || isNaN(step)) {
/* error in specified "step". We cannot validate against it, so the value
* is true. */
return true;
}
var scale = step_scale_factor[type] || 1;
var value = string_to_number(element.value, type);
var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type);
if (isNaN(min)) {
min = default_step_base[type] || 0;
}
if (type === 'month') {
/* type=month has month-wide steps. See
* https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29
*/
min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth();
value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth();
}
var result = Math.abs(min - value) % (step * scale);
return result < 0.00000001 ||
/* crappy floating-point arithmetics! */
result > step * scale - 0.00000001;
}
var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
/**
* trim a string of whitespace
*
* We don't use String.trim() to remove the need to polyfill it.
*/
function trim (str) {
return str.replace(ws_on_start_or_end, '');
}
/**
* split a string on comma and trim the components
*
* As specified at
* https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas
* plus removing empty entries.
*/
function comma_split (str) {
return str.split(',').map(function (item) {
return trim(item);
}).filter(function (b) {
return b;
});
}
/* we use a dummy <a> where we set the href to test URL validity
* The definition is out of the "global" scope so that JSDOM can be instantiated
* after loading Hyperform for tests.
*/
var url_canary;
/* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */
var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* test the type-inherent syntax
*/
function test_type (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) {
/* we're not responsible for this element */
return true;
}
var is_valid = true;
switch (type) {
case 'url':
if (!url_canary) {
url_canary = document.createElement('a');
}
var value = trim(element.value);
url_canary.href = value;
is_valid = url_canary.href === value || url_canary.href === value + '/';
break;
case 'email':
if (element.hasAttribute('multiple')) {
is_valid = comma_split(element.value).every(function (value) {
return email_pattern.test(value);
});
} else {
is_valid = email_pattern.test(trim(element.value));
}
break;
case 'file':
if ('files' in element && element.files.length && element.hasAttribute('accept')) {
var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) {
if (/^(audio|video|image)\/\*$/.test(pattern)) {
pattern = new RegExp('^' + RegExp.$1 + '/.+$');
}
return pattern;
});
if (!patterns.length) {
break;
}
fileloop: for (var i = 0; i < element.files.length; i++) {
/* we need to match a whitelist, so pre-set with false */
var file_valid = false;
patternloop: for (var j = 0; j < patterns.length; j++) {
var file = element.files[i];
var pattern = patterns[j];
var fileprop = file.type;
if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') {
if (file.name.search('.') === -1) {
/* no match with any file ending */
continue patternloop;
}
fileprop = file.name.substr(file.name.lastIndexOf('.'));
}
if (fileprop.search(pattern) === 0) {
/* we found one match and can quit looking */
file_valid = true;
break patternloop;
}
}
if (!file_valid) {
is_valid = false;
break fileloop;
}
}
}
}
return is_valid;
}
/**
* boilerplate function for all tests but customError
*/
function check$1(test, react) {
return function (element) {
var invalid = !test(element);
if (invalid) {
react(element);
}
return invalid;
};
}
/**
* create a common function to set error messages
*/
function set_msg(element, msgtype, _default) {
message_store.set(element, custom_messages.get(element, msgtype, _default));
}
var badInput = check$1(test_bad_input, function (element) {
return set_msg(element, 'badInput', _('Please match the requested type.'));
});
function customError(element) {
/* check, if there are custom validators in the registry, and call
* them. */
var custom_validators = custom_validator_registry.get(element);
var cvl = custom_validators.length;
var valid = true;
if (cvl) {
for (var i = 0; i < cvl; i++) {
var result = custom_validators[i](element);
if (result !== undefined && !result) {
valid = false;
/* break on first invalid response */
break;
}
}
}
/* check, if there are other validity messages already */
if (valid) {
var msg = message_store.get(element);
valid = !(msg.toString() && 'is_custom' in msg);
}
return !valid;
}
var patternMismatch = check$1(test_pattern, function (element) {
set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch'));
});
var rangeOverflow = check$1(test_max, function (element) {
var type = get_type(element);
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeOverflow'), string_to_date(element.getAttribute('max'), type));
break;
case 'time':
msg = sprintf(_('TimeRangeOverflow'), string_to_date(element.getAttribute('max'), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type));
break;
}
set_msg(element, 'rangeOverflow', msg);
});
var rangeUnderflow = check$1(test_min, function (element) {
var type = get_type(element);
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeUnderflow'), string_to_date(element.getAttribute('min'), type));
break;
case 'time':
msg = sprintf(_('TimeRangeUnderflow'), string_to_date(element.getAttribute('min'), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type));
break;
}
set_msg(element, 'rangeUnderflow', msg);
});
var stepMismatch = check$1(test_step, function (element) {
var list = get_next_valid(element);
var min = list[0];
var max = list[1];
var sole = false;
var msg = void 0;
if (min === null) {
sole = max;
} else if (max === null) {
sole = min;
}
if (sole !== false) {
msg = sprintf(_('StepMismatchOneValue'), sole);
} else {
msg = sprintf(_('StepMismatch'), min, max);
}
set_msg(element, 'stepMismatch', msg);
});
var tooLong = check$1(test_maxlength, function (element) {
set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value)));
});
var tooShort = check$1(test_minlength, function (element) {
set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('maxlength'), unicode_string_length(element.value)));
});
var typeMismatch = check$1(test_type, function (element) {
var msg = _('Please use the appropriate format.');
var type = get_type(element);
if (type === 'email') {
if (element.hasAttribute('multiple')) {
msg = _('Please enter a comma separated list of email addresses.');
} else {
msg = _('InvalidEmail');
}
} else if (type === 'url') {
msg = _('InvalidURL');
} else if (type === 'file') {
msg = _('Please select a file of the correct type.');
}
set_msg(element, 'typeMismatch', msg);
});
var valueMissing = check$1(test_required, function (element) {
var msg = _('ValueMissing');
var type = get_type(element);
if (type === 'checkbox') {
msg = _('CheckboxMissing');
} else if (type === 'radio') {
msg = _('RadioMissing');
} else if (type === 'file') {
if (element.hasAttribute('multiple')) {
msg = _('Please select one or more files.');
} else {
msg = _('FileMissing');
}
} else if (element instanceof window.HTMLSelectElement) {
msg = _('SelectMissing');
}
set_msg(element, 'valueMissing', msg);
});
var validity_state_checkers = {
badInput: badInput,
customError: customError,
patternMismatch: patternMismatch,
rangeOverflow: rangeOverflow,
rangeUnderflow: rangeUnderflow,
stepMismatch: stepMismatch,
tooLong: tooLong,
tooShort: tooShort,
typeMismatch: typeMismatch,
valueMissing: valueMissing
};
/**
* the validity state constructor
*/
var ValidityState = function ValidityState(element) {
if (!(element instanceof window.HTMLElement)) {
throw new Error('cannot create a ValidityState for a non-element');
}
var cached = ValidityState.cache.get(element);
if (cached) {
return cached;
}
if (!(this instanceof ValidityState)) {
/* working around a forgotten `new` */
return new ValidityState(element);
}
this.element = element;
ValidityState.cache.set(element, this);
};
/**
* the prototype for new validityState instances
*/
var ValidityStatePrototype = {};
ValidityState.prototype = ValidityStatePrototype;
ValidityState.cache = new WeakMap();
/**
* copy functionality from the validity checkers to the ValidityState
* prototype
*/
for (var prop in validity_state_checkers) {
Object.defineProperty(ValidityStatePrototype, prop, {
configurable: true,
enumerable: true,
get: function (func) {
return function () {
return func(this.element);
};
}(validity_state_checkers[prop]),
set: undefined
});
}
/**
* the "valid" property calls all other validity checkers and returns true,
* if all those return false.
*
* This is the major access point for _all_ other API methods, namely
* (check|report)Validity().
*/
Object.defineProperty(ValidityStatePrototype, 'valid', {
configurable: true,
enumerable: true,
get: function get() {
var wrapper = get_wrapper(this.element);
var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid';
var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid';
var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated';
this.element.classList.add(validatedClass);
if (is_validation_candidate(this.element)) {
for (var _prop in validity_state_checkers) {
if (validity_state_checkers[_prop](this.element)) {
this.element.classList.add(invalidClass);
this.element.classList.remove(validClass);
this.element.setAttribute('aria-invalid', 'true');
return false;
}
}
}
message_store.delete(this.element);
this.element.classList.remove(invalidClass);
this.element.classList.add(validClass);
this.element.setAttribute('aria-invalid', 'false');
return true;
},
set: undefined
});
/**
* mark the validity prototype, because that is what the client-facing
* code deals with mostly, not the property descriptor thing */
mark(ValidityStatePrototype);
/**
* check an element's validity with respect to it's form
*/
function checkValidity(element) {
/* if this is a <form>, check validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, checkValidity).every(function (b) {
return b;
});
}
/* default is true, also for elements that are no validation candidates */
var valid = ValidityState(element).valid;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.valid_event) {
trigger_event(element, 'valid');
}
} else {
trigger_event(element, 'invalid', { cancelable: true });
}
return valid;
}
var version = '0.7.6';
/**
* public hyperform interface:
*/
function hyperform(form) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$strict = _ref.strict;
var strict = _ref$strict === undefined ? false : _ref$strict;
var revalidate = _ref.revalidate;
var valid_event = _ref.valid_event;
var extend_fieldset = _ref.extend_fieldset;
var novalidate_on_elements = _ref.novalidate_on_elements;
var classes = _ref.classes;
if (revalidate === undefined) {
/* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */
revalidate = strict ? 'onsubmit' : 'hybrid';
}
if (valid_event === undefined) {
valid_event = !strict;
}
if (extend_fieldset === undefined) {
extend_fieldset = !strict;
}
if (novalidate_on_elements === undefined) {
novalidate_on_elements = !strict;
}
if (!classes) {
classes = {};
}
var settings = { strict: strict, revalidate: revalidate, valid_event: valid_event, extend_fieldset: extend_fieldset, classes: classes };
if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) {
return Array.prototype.map.call(form, function (element) {
return hyperform(element, settings);
});
}
return new Wrapper(form, settings);
}
hyperform.version = version;
hyperform.checkValidity = checkValidity;
hyperform.reportValidity = reportValidity;
hyperform.setCustomValidity = setCustomValidity;
hyperform.stepDown = stepDown;
hyperform.stepUp = stepUp;
hyperform.validationMessage = validationMessage;
hyperform.ValidityState = ValidityState;
hyperform.valueAsDate = valueAsDate;
hyperform.valueAsNumber = valueAsNumber;
hyperform.willValidate = willValidate;
hyperform.set_language = function (lang) {
set_language(lang);return hyperform;
};
hyperform.add_translation = function (lang, catalog) {
add_translation(lang, catalog);return hyperform;
};
hyperform.set_renderer = function (renderer, action) {
Renderer.set(renderer, action);return hyperform;
};
hyperform.register = function (element, validator) {
custom_validator_registry.set(element, validator);return hyperform;
};
hyperform.set_message = function (element, validator, message) {
custom_messages.set(element, validator, message);return hyperform;
};
module.exports = hyperform; |
/*!
* anyjs tiny ver 1.0.0 beta2 - any-tiny.js
* (c) 2016, any-js - https://github.com/any-js/anyjs/ (Released under the MIT license)
*/
/**
* anyjs - any-tiny.js
* (c) any-js - https://github.com/any-js/
* Released under the MIT license
*/
var $any = {};
(function(any){
'use strict';
any.define = {};
/**
* Private methods
*/
/**
* @ignore
*/
function trim(v){
return v.replace(/^(\s)+|(\s)+$/g, '');
}
/**
* @ignore
*/
function keys(nm){
return String(nm).split('.').map(trim);
}
/**
* @ignore
*/
function arrArg(vs){
if (vs != null){
if(!(vs instanceof Array)){
if (Object.prototype.toString.call(vs) === '[object Arguments]'){
vs = Array.prototype.slice.call(vs);
}else{
vs = [vs];
}
}
}else{
vs = [];
}
return vs;
}
/**
* @ignore
*/
function none(){
}
/**
* Manage "Profile", store and read options, merge default options.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | All methods | Yes | Yes | Yes |
*
* @namespace $any.profile
* @see Profile
*
* @tutorial static-profile
* @tutorial demo-various
*
* @example
* example = $any.profile.create({a: 1, b: 2});
* example.setProfile('abc', {a: '1', b: '2'});
*
* opt = $any.profile.getProfile(example, 'abc'); //Get 'abc'
* opt = $any.profile.getProfile(example, null); //Get default
*/
any.profile = {};
/**
* Profile object by created $any.profile.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | All methods | Yes | Yes | Yes |
*
* @class Profile
*
* @see $any.profile
* @tutorial static-profile
* @tutorial demo-various
*
* @example
* example = $any.profile.create({a: 1, b: 2});
* example.setProfile('abc', {a: '1', b: '2'});
*
* opt = $any.profile.getProfile(example, 'abc'); //Get 'abc'
* opt = $any.profile.getProfile(example, null); //Get default
*/
/**
* Create profile object.
* @function create
* @memberof $any.profile
*
* @param {assoc} defaults Default option.
* @returns {Profile}
*
* @see Profile
*
* @tutorial static-profile
*
* @example
* example = $any.profile.create({a: 1, b: 2});
*/
any.profile.create = function(defaults){
info('profile.create');
/**
* @ignore
*/
var pfl = {
define: {},
defaults: defaults,
profiles: {}
};
/**
* Set profile option.
* @memberof Profile
* @instance
* @function
* @name setProfile
*
* @param {string} name Profile name.
* @param {assoc} opt Profile's options.
*
* @see $any.profile.setProfile
*
* @tutorial static-profile
* @example
* example.setProfile('abc', {a: '1', b: '2'});
*/
pfl.setProfile = function(name, opt){
any.profile.setProfile(pfl, name, opt);
};
/**
* Get profile option.
* @memberof Profile
* @instance
* @function
* @name getProfile
*
* @param {assoc|string} opt Profile name or override options.
* @param {assoc} defaults Default options.
* @returns {assoc}
*
* @see $any.profile.getProfile
*
* @tutorial static-profile
* @example
* opts = example.getProfile('abc');
*/
pfl.getProfile = function(opt, defaults){
return any.profile.getProfile(pfl, opt, defaults);
};
return pfl;
};
/**
* Set profile option.
* @function setProfile
* @memberof $any.profile
*
* @param {object} scope Scope.
* @param {string} name Profile name.
* @param {assoc} opt Profile's options.
*
* @see Profile
*
* @tutorial static-profile
* @example
* $any.profile.setProfile(example, 'abc', {b: 3, c: 5}); //Set 'abc'
* $any.profile.setProfile(example, null, {b: 3, c: 5}); //Set default
*/
any.profile.setProfile = function(scope, name, opt){
info('profile.setProfile');
if (name == null || name === 'default'){
scope.defaults = scope.defaults || {};
ext(scope.defaults, opt);
}else{
scope.profiles[name] = ext(ext({}, scope.defaults, true), opt, true);
}
};
/**
* Get profile option.
* @function getProfile
* @memberof $any.profile
*
* @param {object} scope Scope.
* @param {string|assoc|array} opt Profile name or override options.
* @param {assoc} defaults Default options.
* @returns {assoc}
*
* @see Profile
*
* @tutorial static-profile
* @example
* opt = $any.profile.getProfile(example, 'abc'); //Get 'abc'
* opt = $any.profile.getProfile(example, null); //Get default
* opt = $any.profile.getProfile(example, ['abc', {a: 1000, y: 1000}]); //Get 'abc' and override option.
*/
any.profile.getProfile = function(scope, opt, defaults){
var pfs = scope.profiles;
defaults = defaults || {};
if (opt instanceof Array){
var nm = opt[0];
if (opt.length == 2 && typeof nm === 'string'){
if (pfs[nm] == null){
error('profile none', opt);
}
return ext(ext(defaults, pfs[nm], true), opt[1], true);
}else{
error('illegal format', opt);
}
} else if (opt instanceof Object){
return ext(ext(defaults, scope.defaults, true), opt, true);
} else if (opt == null || opt === 'default'){
return ext(defaults, scope.defaults, true);
} else if (typeof opt === 'string'){
if (pfs[opt] == null){
error('profile none', opt);
}
return ext(defaults, pfs[opt], true);
}
return opt;
};
/**
* any($any) static methods. Helper methods for data operation.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | ready | - | Yes | - |
* | detectClick | Yes | - | - |
* | Others | Yes | Yes | Yes |
*
* @namespace $any
*
* @tutorial static-any
* @example
* //See tutorials.
*/
/**
* any($any) defines.
*
* @namespace $any.define
*/
/**
* $any.info mode
*
* | Value | Description |
* |:---|:---|
* | <code>0</code> | none |
* | <code>1</code> | info |
* | <code>2</code> | info+trace |
*
* @memberof $any.define
*
* @type {number}
* @default 0
* @see $any.info
* @see {@link $any.log}
*/
any.define.info = 0; //0:none, 1:info, 2:info+trace
/**
* @ignore
*/
function csOut(f, vs){
vs = arrArg(vs);
vs.unshift(console);
Function.prototype.call.apply(f, vs);
}
/**
* Output info.
* @function info
* @memberof $any
*
* @param {...*} v Arguments.
*
* @see $any.define.info
* @see {@link $any.log}
*
* @tutorial static-any
* @example
* $any.info(1, 2, 3);
*/
any.info = function(v){
switch (any.define.info){
case 1:
csOut(console.log, arguments);
break;
case 2:
csOut(console.log, arguments);
console.trace();
break;
default:
break;
}
};
/**
* $any.error mode
*
* | Value | Description |
* |:---|:---|
* | <code>0</code> | none |
* | <code>1</code> | error |
* | <code>2</code> | error+trace |
*
* @memberof $any.define
* @type {number}
* @default 1
*
* @see $any.error
* @see {@link $any.log}
*/
any.define.error = 1; //0:none, 1:error, 2:error+trace
/**
* If error occurs, throw error.
* @memberof $any.define
* @type {boolean}
* @default false
*
* @see $any.error
* @see {@link $any.log}
*/
any.define.throwError = false;
/**
* Check existence of selector's target. If none, error occurs.
* @memberof $any.define
* @type {boolean}
* @default false
* @see {@link $any.log}
*/
any.define.targetExist = false;
/**
* Output error.
* @function error
* @memberof $any
*
* @param {...*} v Arguments.
*
* @see $any.define.error
* @see {@link $any.log}
*
* @tutorial static-any
* @example
* $any.error(1, 2, 3);
*/
any.error = function(v){
switch (any.define.error){
case 1:
csOut(console.error, arguments);
break;
case 2:
csOut(console.error, arguments);
console.trace();
break;
default:
break;
}
if (any.define.throwError){
throw new Error(v);
}
};
/**
* @ignore
*/
function ext(v, s, deep){
if(!s){
return v;
}
for (var k in s){
if (s.hasOwnProperty(k)){
if (deep && s[k] instanceof Object && s[k].constructor === Object){
if (v[k] == null){
v[k] = {};
}
v[k] = ext(v[k], s[k], deep);
}else{
v[k] = s[k];
}
}
}
return v;
}
/**
* Extend values. Support deep-copy.
* @param {assoc|array|object} dest Destination. Override values by source.
* @param {assoc|array|object} src Source.
* @param {boolean} [deep=false] Is deep-copy.
* @returns {assoc|array|object}
*
* @example
* $.any.extend(dest, src);
* $.any.extend(dest, src, true);
* dest = $.any.extend(dest, src);
*/
any.extend = function(dest, src, deep){
return ext(dest, src, deep);
};
/**
* Get object keys.
* @function keys
* @memberof $any
*
* @param {assoc|array} vs Values.
* @return {array}
*
* @tutorial static-any
* @example
* ks = $any.keys([1, 2, 3, 4]);
* ks = $any.keys({a:1, b:2, c:3});
*/
any.keys = function(vs){
var ks = 0;
try {
ks = Object.keys(vs);
}catch(e){
ks = [];
if (vs){
any.each(vs, function(k, v){
ks.push(k);
});
}
}
return ks;
};
/**
* Get object length.
* @function size
* @memberof $any
*
* @param {assoc|array} vs Values.
* @return {number}
*
* @tutorial static-any
* @example
* n = $any.size({a:1, b:2, c:3});
*/
any.size = function(vs){
return any.keys(vs).length;
};
/**
* Check blank value.
* @function blank
* @memberof $any
* @param {*} v Value.
* @returns {boolean} <code>true</code> false, null, undefined, '' <code>false</code> 0, or other any data.
*
* @tutorial static-any
* @example
* r = $any.blank(v);
* if ($any.blank(v)){ ... }
*/
any.blank = function(v){
return (!v && v !== 0);
};
/**
* Clone object.
* @function clone
* @memberof $any
* @param {assoc|array} v Assoc or array value.
* @param {boolean} [isArr=false] If true, return value type is array.
* @returns {*}
*
* @tutorial static-any
* @example
* v = $any.clone({a:1, b:2, c:3});
* v = $any.clone([1, 2, 3, 4, 5], true);
*/
any.clone = function(v, isArr){
var bs = {};
if (isArr){
bs = [];
}
return ext(bs, v, true);
};
/**
* Simple object's loop.
* @function each
* @memberof $any
* @param {assoc|object} vs Assoc or object.
* @param {function} fn Function. <code>function(key, value){ }</code>
* @param {*} [ctx=null] this object
*
* @tutorial static-any
* @example
* $any.each({a:1, b:2, c:3}, function(k, v){
* console.log(k, v);
* });
* $any.each({a:1, b:2, c:3}, function(k, v){
* $(this).val(v);
* }, this);
*/
any.each = function(vs, fn, ctx){
for(var k in vs){
if (vs.hasOwnProperty(k)){
fn.call(ctx, k, vs[k]);
}
}
};
/**
* @ignore
*/
var gbs = {};
/**
* Bind function or value by name.
* @function global
* @memberof $any
*
* @param {string|null} name Name.
* @param {function|string|number|object} [v] Various value or function.
* @returns {*}
*
* @tutorial static-any
* @example
* fn = $any.global(null, function(v){ ... });
* fn(v);
* $any.global('abc', function(v){ ... });
* $any.global('abc')(v);
*/
any.global = function(name, v){
if (v === undefined){
if (gbs[name]){
return gbs[name];
}else{
error('none');
return none;
}
}
if (name === undefined){
name = null;
}
if (v !== null){
gbs[name] = v;
}else{
delete gbs[name];
return;
}
return gbs[name];
};
/**
* @ignore
*/
function gtRcs(ks, vs){
var v, k = ks.shift();
v = vs[k];
if (v == null){
return null;
}
if (ks[0] !== undefined){
return gtRcs(ks, v);
}
return v;
}
/**
* Get value from assoc.
*
* <b>name format</b> <code>a, a.b, a.b.c, a.0</code>
*
* @function get
* @memberof $any
* @param {assoc|array} vs Values object.
* @param {string} name Value name. Child name of assoc can be specified. - 'a.b.1'.
* @returns {*}
*
* @tutorial static-any
* @example
* v = $any.get(vs, 'a'); //assoc
* v = $any.get(vs, 'b.a'); //assoc
* v = $any.get(vs, 0); //array
* v = $any.get(vs, '0.0.0'); //array
*/
any.get = function(vs, name){
var ks = keys(name);
return gtRcs(ks, vs);
};
/**
* @ignore
*/
function stRcs(ks, vs, nm, v, eo){
var k = ks.shift();
if (ks[0] === undefined){
if (vs[k] == null || !eo){
vs[k] = v;
}
} else {
if (vs[k] == null){
vs[k] = {};
stRcs(ks, vs[k], nm, v, eo);
} else if (typeof vs[k] === 'object'){
stRcs(ks, vs[k], nm, v, eo);
} else {
error('not object', vs, nm);
}
}
}
/**
* Set value to assoc.
* @function set
* @memberof $any
* @param {assoc|array} vs Assoc.
* @param {string} name Value's name. Child name of assoc can be specified. - 'a.b.1'.
* @param {*|function} v Value or Function which change value.
* @param {boolean} [emptyOnly=false] Set value if empty.
*
* @tutorial static-any
* @example
* $any.set(vs, 'a', 123); //value
* $any.set(vs, 0, 123); //set to array
* $any.set(vs, 'b.a', 123); //assoc
* $any.set(vs, 'c.0', 123); //array
* $any.set(vs, 'd', function(v){ return v++; }); //using function
* $any.set(vs, 'e', 123, true); //empty only
*/
any.set = function(vs, name, v, emptyOnly){
if (typeof v === 'function'){
v = v(any.get(vs, name));
}
stRcs(keys(name), vs, name, v, emptyOnly);
return v;
};
/**
* Empty values.
* @function drop
* @memberof $any
* @param {assoc|array} vs Assoc.
*
* @tutorial static-any
* @example
* $any.drop(vs);
*/
any.drop = function(vs){
any.each(vs, function(k){
delete vs[k];
});
};
/**
* Data stored for $any.data. It is simple assoc.
* @memberof $any
* @type {assoc}
*
* @see $any.data
*
* @tutorial static-any
* @example
* $any.datas = {a:1, b:2, c:3};
*/
any.datas = {};
/**
* Get and Set global value - $any.datas.
*
* <b>Specification</b><br>
* Internal use: <code>$any.get</code> <code>$any.set</code>
*
* @function data
* @memberof $any
* @param {assoc|array|null} vs Data pool. If null, vs is $any.datas.
* @param {string} name Name.
* @param {*} [v] Value. For set.
* @param {boolean} [emptyOnly=false] Set value if empty. For set.
* @returns {*}
*
* @see $any.datas
* @see $any.get
* @see $any.set
*
* @tutorial static-any
* @example
* //Set
* $any.data(null, null, {a:1, b:2, c:3});
* $any.data(null, 'a', 1);
* $any.data(pool, 'b.b1', 1);
* v = $any.data(pool, 'c', function(v){ return v+1 });
*
* @example
* //Get
* vs = $any.data();
* v = $any.data(null, 'a');
* v = $any.data(pool, 'b.b1');
* v = $any.data(pool, 'c');
*/
any.data = function(vs, name, v, emptyOnly){
if (vs == null){
vs = any.datas;
}
//Get
if (v === undefined){
if (name == null){
return vs;
}
return any.get(vs, name);
}
//Set
if (any.blank(name)){
if (typeof v !== 'object'){
v = {};
}
any.drop(vs);
ext(vs, v, true);
return vs;
}
return any.set(vs, name, v, emptyOnly);
};
/**
* Convert to other structure values from original values by rule.
* @function filter
* @memberof $any
*
* @param {assoc|array} vs Original values.
* @param {assoc} [rule] Convert rule.<br><code>{<br>to: from, //from >> to<br>to: null, //Delete<br>to: {...} or [...], //cover by matrix<br>to: function(v, org, dest){return v;}, //Using function<br>'*': function(vs, r, rule){r.a = 1;} //Initialize<br>}</code>
* @param {assoc} [opt] Option.
* @param {boolean} [opt.reset=false] Determine to reset values. and use only specified values by rule.
* @param {boolean} [opt.replace=true] Determine to replace value. If 'fill' is false, the original value retain.
* @param {boolean} [opt.array=false] Determine return value type. Default type is assoc.
* @param {string} [opt.init='*'] Function name of initialize used by rule.
* @returns {assoc|array} New values converted by rule.
*
* @tutorial static-any
* @example
* rule = {
* a1: 'a', //a >> a1
* b1: 'b', //b >> b1
* c: null, //delete
* d: {1: 'london', 2: 'new york', 3: 'tokyo'}, //cover by matrix
* e: 'x' //none
* };
* vs = $any.filter(vs, rule);
*
* @example
* rule = {
* '*': function(vs, r){
* r.b = 4; //b
* },
* a1: function(v, vs, r){
* return vs.a+10;
* },
* a2: 'a' //a >> a2
* };
* vs = $any.filter(vs, rule, {reset: true});
*
* @example
* //Array
* rule = {
* '*': function(vs, r){
* r[5] = 101; //5
* r[6] = 102; //6
* },
* 7: 0, //0 >> 7
* 8: function(v, vs, r){
* return 103;
* }
* };
vs = $any.filter(vs, rule, {replace: false, array: true});
*/
any.filter = function(vs, rule, opt){
opt = ext({reset: false, replace: true, array: false, init: '*'}, opt);
var r = null, tvs = (opt.reset)?null:vs;
r = any.clone(tvs, opt.array);
if (typeof rule[opt.init] === 'function'){
var init = rule[opt.init];
delete rule[opt.init];
init(vs, r, rule);
}
any.each(rule, function(to, frm){
if (typeof frm !== 'function'){
if (frm == null){
delete r[to];
}else{
if (typeof frm !== 'object'){
r[to] = (vs[frm] !== undefined)?vs[frm]:null;
}else{
tvs = frm[vs[to]];
r[to] = (tvs == null)?null:tvs;
}
if (opt.replace && to != frm){
delete r[frm];
}
}
}else{
r[to] = frm(((vs[to] !== undefined)?vs[to]:null), vs, r);
}
});
return r;
};
/**
* Inject function to wrap function and run. Usecase: ex. initialization.
* @function inject
* @memberof $any
*
* @param {function} wrap Wrap function.<br><code>function(fn, vs...){ }</code>
* @param {function} inject Inject function. <br><code>function(vs...){ }</code>
* @returns {function}
*
* @tutorial static-any
* @tutorial demo-various
* @example
* $any.inject(function(fn, v){
* $('#target').clicked(function(){
* v = !v;
* fn(v);
* });
* }, function(v){
* $('#target-pane').viewing(v);
* })(false);
* @example
* $any.inject(function(fn, v, txt){
* $(this).clicked(function(){
* v = !v;
* fn(v, txt);
* });
* }, function(v, txt){
* $('#target').append(txt);
* $('#target-pane').viewing(v);
* })(false, '.');
*/
any.inject = function(wrap, inject){
return function(){
var v = arrArg(arguments);
v.unshift(inject);
wrap.apply(this, v);
return inject.apply(this, arguments);
};
};
/**
* Create auto-count function.
* @function counter
* @memberof $any
*
* @param {number|array} v Array or init number.
* @param {assoc} [opt] Option.
* @param {number} [opt.min=null] Min value.
* @param {number} [opt.max=null] Max value.
* @param {number} [opt.add=1] Additional value.
* @param {number} [opt.init=null] Initial value.
* @param {boolean} [opt.loop=false] Determine to loop.
* @returns {function}
*
* @tutorial static-any
* @example
* fn = $any.counter(['A', 'B', 'C', 'D', 'E']);
* fn = $any.counter(12);
* fn = $any.counter(20, {add: 3, max: 30});
* fn = $any.counter([1,2,3], {loop: true});
*/
any.counter = function(v, opt){
opt = ext({min: null, max: null, add: 1, init: null, loop: false}, opt);
var n = 0, min = opt.min, max = opt.max;
if (typeof v === 'number'){
n = v;
}else if (v instanceof Array){
if(opt.min == null){
min = 0;
}
if(opt.max == null){
max = v.length - 1;
}
}
if (opt.init != null){
n = opt.init;
}
n-= opt.add;
return function(init){
var t;
n = n + opt.add;
if (init != null){
n = v;
}
t = n - max;
if (max != null && t > 0){
if (opt.loop){
n = (min != null)?min:0;
n+= t - 1;
}else{
n = max;
}
}
t = n - min;
if (min != null && t < 0){
if (opt.loop){
n = max;
n+= t + 1;
}else{
n = min;
}
}
if (v instanceof Array){
return (v[n] !== undefined)?v[n]:null;
}
return n;
};
};
/**
* Calc crc16.
* @function crc
* @memberof $any
*
* @param {string} v String value
* @returns {number} Crc16 value
*
* @tutorial static-any
* @example
* num = $any.crc16(val);
*/
any.crc16 = function(v){
if (v == null){
return 0;
}
var crc = 0, i, j;
for(i=0; i < v.length; i++){
crc ^= v.charCodeAt(i);
for(j = 0; j < 8; j++){
crc = (crc & 1) ? (crc >> 1) ^ 0xa001 : (crc >> 1);
}
}
return crc;
};
/**
* Escape regex.
* @function escapeRegex
* @memberof $any
*
* @param {string} v String value.
* @returns {string}
*
* @tutorial static-any
* @example
* val = $any.escapeRegex(val);
*/
any.escapeRegex = function(v){
return v.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
/**
* Register function which run after document-ready.
*
* <b><i>Note! Only for any-tiny.js.</i></b><br>
*
* @function ready
* @memberof $any
* @param {function} fn Function.
*
* @tutorial static-any
* @example
* $any.ready(function(){ ... });
*/
any.ready = function(fn){
try{
window.addEventListener('load', fn);
}catch(e){
window.attachEvent('onload', fn);
}
};
/**
* any($any) static methods. Method for class operation.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | All methods | Yes | Yes | Yes |
*
* @namespace $any@class
*
* @tutorial static-any-class
*
* @example
* var ACls = $any.makeClass(
* function(n){
* this.n = n;
* }, {
* output: function(){ alert(this.n); }
* }
* );
* var a = new ACls(1);
*
* $any.mixin(AClass, {xyz: function(){ ... }});
*
* $any.defineClass({
* 'StoneClass': function(make){ return make(function(){ ... }, { ... }); },
* 'Metal.IronClass': function(make){ return make(function(){ ... }, { ... }); }
* });
*
* Class = $any.getClass('Metal.IronClass');
*
* tree = $any.newClass('TreeClass');
*/
/**
* @ignore
*/
function clBind(C){
C.prototype.bind = function(fn){
try{
return fn.bind(this);
} catch (e){
}
var c = this;
return function(){
return fn.apply(c, arguments);
};
};
}
/**
* Create class and inherits class.
*
* <b>Specification</b><br>
*
* | | |
* |:---|:---|
* | <b>Build class</b> | Define constructor by function / Methods which added by 'prototype' |
* | <b>Extends class</b> | Both build-class and super-class's constructor / Override super-class methods by 'prototype' |
*
* @function makeClass
* @memberof $any@class
*
* @param {function} construct Class constructor and base structure.
* @param {function|functions} methods Class methods or Function space and class methods. Add methods by prototype.
* @param {function} [parent=null] If specified, extends super-class.
* @param {boolean} [bind=true] If true, Add <i>bind</i> method.
* @returns {object} Class. This is not instance.
*
* @tutorial static-any-class
* @example
* //Build class
* var ACls = $any.makeClass(
* function(n){
* this.n = n;
* }, {
* output: function(){ alert(this.n); }
* }
* );
* var a = new ACls(1);
*
* //Extends class
* var BCls = $any.makeClass(
* function(n){
* this.b = 5;
* }, {
* output: function(){ alert(this.n + this.b); }
* }, ACls
* );
* var b = new BCls(2);
*/
any.makeClass = function(construct, methods, parent, bind){
info('makeClass');
var C;
construct = construct || function(){};
if (parent){
C = function(){
parent.apply(this, arguments);
construct.apply(this, arguments);
};
try {
C.prototype = Object.create(parent.prototype);
}catch(e){
var P = function(){};
P.prototype = parent.prototype;
C.prototype = new P();
}
}else{
C = construct;
}
if (typeof methods === 'function'){
methods = methods();
}
for(var k in methods){
if (methods.hasOwnProperty(k)){
C.prototype[k] = methods[k];
}
}
if (bind !== false){
clBind(C);
}
return C;
};
/**
* Mixin of class by methods. Override methods by 'prototype'.
*
* @function mixin
* @memberof $any@class
*
* @param {Class} Class Class object.
* @param {functions} methods The added method.
* @returns {Class}
*
* @tutorial static-any-class
* @example
* $any.mixin(AClass, {xyz: function(){ ... }});
*/
any.mixin = function(Class, methods){
info('mixin');
for(var k in methods){
if (methods.hasOwnProperty(k)){
Class.prototype[k] = methods[k];
}
}
return Class;
};
/**
* @ignore
*/
var clDf = {};
/**
* Define class builder by function.
*
* @function defineClass
* @memberof $any@class
*
* @param {string|assoc<string, function>} name Class name. Namespace can be specified.
* @param {function} build Build function. <code>function(make){ ... }</code>
* @param {boolean} [once=false] Don't show error in duplication class-name.
*
* @see $any@class.makeClass
*
* @tutorial static-any-class
*
* @example
* $any.defineClass('StoneClass', function(){return $any.makeClass(function(){ ... }; });
* $any.defineClass('Material.natural.StoneClass', function(){ return $any.makeClass(function(){ ... }, { ... }); });
* $any.defineClass('StoneClass', function(make){ return make(function(){ ... }, { ... }); });
* $any.defineClass('Metal.IronClass', function(){return $any.makeClass(function(){ ... }; }, true);
* $any.defineClass({
* 'StoneClass': function(make){ return make(function(){ ... }, { ... }); },
* 'Metal.IronClass': function(make){ return make(function(){ ... }, { ... }); }
* });
*/
any.defineClass = function(name, build, once){
info('defineClass');
if (typeof name === 'string'){
var t = {};
t[name] = build;
name = t;
}
any.each(name, function(name, build){
if (!name || name.search(/^[a-z]+[\w\.]+[a-z0-9]+$/i) == -1){
console.error('class name error:' + name);
return;
}
if (clDf[name]){
if (!once){
console.error('already exist class:' + name);
}
return;
}
clDf[name] = build;
});
};
/**
* @ignore
*/
var clCls = {};
/**
* Get a class from defined classes.
* @function getClass
* @memberof $any@class
*
* @param {string} name Class name. Namespace can be specified.
* @param {boolean} [store=true] Store class object. In default(true), the second time later, not make.
* @return {Class} Class. This is not instance.
*
* @see $any@class.defineClass
* @see $any@class.makeClass
*
* @tutorial static-any-class
*
* @example
* Class = $any.getClass('StoneClass');
* Class = $any.getClass('Metal.IronClass');
* Class = $any.getClass('Material.natural.StoneClass', false);
*/
any.getClass = function(name, store){
info('getClass');
if (!clDf[name]){
console.error('class none:' + name);
return null;
}
if (clCls[name]){
return clCls[name];
}
var C = clDf[name](any.makeClass);
if (store !== false){
clCls[name] = C;
}
return C;
};
/**
* Create new instance with constructor arguments.
* @function newClass
* @memberof $any@class
*
* @param {string} name Class name. Namespace can be specified.
* @param {array} [vs] Constructor arguments.
* @return {object} Class instance.
*
* @see $any@class.defineClass
* @see $any@class.getClass
*
* @tutorial static-any-class
*
* @example
* tree = $any.newClass('TreeClass');
* stone = $any.newClass('Material.natural.StoneClass');
* silver = $any.newClass('Metal.SilverClass', [1, 2, 3]);
*/
any.newClass = function(name, vs){
info('newClass');
var C = any.getClass(name);
vs = vs || [];
vs.unshift(C);
/* jshint ignore:start */
return new (C.bind.apply(C, vs));
/* jshint ignore:end */
};
/**
* Console out defined classes.
* @function definedClasses
* @memberof $any@class
*
* @param {boolean} [store=false] Output stored class.
*
* @see $any@class.defineClass
*
* @tutorial static-any-class
*
* @example
* $any.definedClasses();
* $any.definedClasses(true);
*/
any.definedClasses = function(store){
info('definedClasses');
console.log('[Defined classes]');
any.each((store)?clCls:clDf, function(nm, cls){
console.log(nm, cls);
});
};
/**
* Provide log and debug helper methods.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | events | Yes | - | - |
* | Others | Yes | Yes | Yes |
*
* @namespace $any.log
*
* @tutorial static-any
* @tutorial static-log
*/
any.log = {target: {scope: null, methods: null, elem: null}};
/**
* Set log behaviors. Set $any.define.info, $any.define.error.
* @function debug
* @memberof $any.log
*
* @param {integer} [info=null] $any.info mode. $any.define.info.
* @param {integer} [error=null] $any.error mode. $any.define.error.
* @param {boolean} [throwError=null] Throw error. $any.define.throwError.
* @param {boolean} [targetExist=null] Check existence of selector's target. $any.define.targetExist.
*
* @see $any.info
* @see $any.error
* @see $any.define.info
* @see $any.define.error
* @see $any.define.throwError
*
* @tutorial static-log
*
* @example
* $any.log.debug(0, 1); //On error
* $any.log.debug(0, 1, true); //On error and throw error
* $any.log.debug(0, 0); //Off error
* $any.log.debug(0, 2); //On error trace
* $any.log.debug(1); //On info
* $any.log.debug(1); //On info trace
* $any.log.debug(null, null, true); //Throw error
*/
any.log.debug = function(info, error, throwError, targetExist){
if (info != null){
any.define.info = info;
}
if (error != null){
any.define.error = error;
}
if (throwError != null){
any.define.throwError = throwError;
}
if (targetExist != null){
any.define.targetExist = targetExist;
}
};
/**
* Set limit target by method and element and scope.
* @function limit
* @memberof $any.log
*
* @param {string|array} method Method name.
* @param {Selector} [el] Element target. Enable log if the element has event element.
* @param {boolean} [scope] Scope target. Enable log only target scope.
*
* @see $any.info
* @see $any.error
* @see $any.define.info
* @see $any.define.error
*
* @tutorial static-log
*
* @example
* $any.log.limit('showing');
* $any.log.limit(['showing', 'hiding']);
* $any.log.limit(null, $('#target'));
* $any.log.limit(null, $('#parent'));
* $any.log.limit(null, null, 'ajax');
* $any.log.limit(null, null, 'view');
*/
any.log.limit = function(method, el, scope){
any.log.target.methods = (typeof method === 'string')?[method]:method;
if (el !== undefined){
any.log.target.elem = el;
}
if (scope !== undefined){
any.log.target.scope = scope;
}
};
var logOn = 1;
/**
* @ignore
*/
function logAny(nm, vs, error){
if (logOn <= 0 && !error){
return null;
}
if (any.log.target.scope && any.log.target.scope != nm){
return null;
}
vs = vs || [];
nm = (!error)?(nm || 'any.'):'';
var t;
if (any.log.target.elem){
t = vs[1];
if (isEl(t)){
if(!hasEl(any.log.target.elem, t)){
return null;
}
}
}
if (any.log.target.methods && any.log.target.methods.indexOf(vs[0]) == -1){
return null;
}
vs[0] = nm + ((vs[0] == null)?'*':vs[0]);
for (var i=vs.length;i>=0;i--){
if (vs[i] == undefined){
vs[i] = null;
}
}
return vs;
}
/**
* @ignore
*/
any.log.info = function(nm, vs){
if (any.define.info <= 0){
return;
}
vs = logAny(nm, vs, false);
if (vs){
any.info.apply(null, vs);
if (any.log.breakpoint){
any.log.breakpoint(nm, vs);
}
}
};
/**
* @ignore
*/
any.log.error = function(nm, vs){
if (any.define.error <= 0){
return;
}
vs = logAny(nm, vs, true);
if (vs){
any.error.apply(null, vs);
if (any.log.breakpoint){
any.log.breakpoint(vs);
}
}
};
/**
* Set break-point function.
* @memberof $any.log
* @type {function}
* @default null
*
* @see $any.log.info
* @see $any.log.error
*
* @tutorial static-log
*
* @example
* $any.log.breakpoint = function(){ ... };
*/
any.log.breakpoint = null;
any.log.suspend = function(){
nolog();
};
any.log.resume = function(){
relog();
};
/**
* @ignore
*/
function info(){
any.log.info(null, arguments);
}
/**
* @ignore
*/
function error(){
any.log.error(null, arguments);
}
/**
* @ignore
*/
function nolog(){
logOn--;
}
/**
* @ignore
*/
function relog(){
logOn++;
}
/**
* Assign values to template.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | assign | Yes | Yes | Yes |
* | assigns | Yes | Yes | Yes |
* | make | Yes | - | - |
* | makes | Yes | - | - |
* | cover | Yes | - | - |
*
* @namespace $any.tpl
*
* @tutorial static-tpl
*
* @example
* v = {target: 'MnO2', Type: 'dry-cell'};
* src = 'The principal use for {target} is for {type} batteries.';
* html = $any.tpl.assign(src, v, {ignoreCase: true});
* //The principal use for MnO2 is for dry-cell batteries.
*
* vs = [{a: 'A1', b: 'B1'}, {a: 'A2', b: 'B2'}];
* src = '<li>{a}, {b}</li>';
* html = $any.tpl.assigns(src, vs);
*/
any.tpl = {define: {}};
/**
* Wrap side strings.
* @memberof $any.tpl
* @type {array}
* @default ['{', '}']
*
* @example
* $any.tpl.define.wraps = ['{', '}'];
* $any.tpl.define.wraps = ['{{', '}}'];
*/
any.tpl.define.wraps = ['{', '}'];
/**
* Determine to sort key of assoc by length.
* @memberof $any.tpl
* @type {boolean}
* @default true
* @example
* $any.tpl.define.sort = true;
*/
any.tpl.define.sort = true;
/**
* Assign values to template.
* @function assign
* @memberof $any.tpl
*
* @param {string} src Template source.
* @param {assoc|string|number} vs Assign values or sinple value.
* @param {assoc} opt Option
* @param {boolean} [opt.wrap=true] Determine to wrap.
* @param {boolean} [opt.ignoreCase=false] Determine to ignore case sensitive.
* @returns {string}
*
* @tutorial static-tpl
* @example
* v = {target: 'MnO2', Type: 'dry-cell'};
* src = 'The principal use for {target} is for {type} batteries.';
*
* html = $any.tpl.assign(src, v, {ignoreCase: true});
* //The principal use for MnO2 is for dry-cell batteries.
*
* html = $any.tpl.assign('{*}-pilot / {*}-trader', 'auto'); //auto-pilot / auto-trader
*/
any.tpl.assign = function(src, vs, opt){
info('tpl.assign');
opt = ext({wrap: true, ignoreCase: false}, opt);
var k, wp, rx, rgx = '', vz = {};
if (typeof vs === 'object'){
var v, ks = any.keys(vs);
if (any.tpl.define.sort){
ks.sort(function(a, b){
return b.length - a.length;
});
}
for (var i in ks){
if (ks.hasOwnProperty(i)){
k = ks[i];
v = vs[k];
if (opt.ignoreCase){
k = k.toLowerCase();
}
if (opt.wrap){
wp = any.tpl.define.wraps;
k = wp[0] + k + wp[1];
}
vz[k] = v;
k = any.escapeRegex(k);
rgx += k + '|';
}
}
rgx = rgx.slice(0, -1);
}else{
k = '*';
if (opt.wrap){
wp = any.tpl.define.wraps;
k = wp[0] + k + wp[1];
}
rgx = any.escapeRegex(k);
vz[k] = vs;
}
rgx = '(' + rgx + ')';
var o = 'g';
if (opt.ignoreCase){
o += 'i';
}
rx = new RegExp(rgx, o);
return src.replace(rx, function(key){
if (opt.ignoreCase){
key = key.toLowerCase();
}
return vz[key];
});
};
/**
* Assign multiple values.
* @function assigns
* @memberof $any.tpl
*
* @param {string} src Template source.
* @param {array} rows Multiple assign values.
* @param {assoc} [opt] $any.tpl.assign option.
* @returns {string}
*
* @see $any.tpl.assign
*
* @tutorial static-tpl
* @example
* vs = [{a: 'A1', b: 'B1'}, {a: 'A2', b: 'B2'}];
* src = '<li>{a}, {b}</li>';
* html = $any.tpl.assigns(src, vs);
* v = $any.tpl.assigns('<div>{*}</div>', ['Iron', 'Bronze']); //<div>Iron</div><div>Bronze</div>
*/
any.tpl.assigns = function(src, rows, opt){
info('tpl.assigns');
var r = '';
for(var i = 0; i < rows.length; i++){
r += any.tpl.assign(src, rows[i], opt);
}
return r;
};
/**
* Date data converter. Date source to Date value assoc, date string.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | All methods | Yes | Yes | Yes |
*
* <b>Date format values</b><br>
*
* | Value | Description | Example |
* |:---|:---|:---|
* | y | Number of year | 2016 |
* | yy | 2digit year | "16" |
* | M | Number of month | 2 |
* | MM | 2digit month | "02" |
* | MMM | String month | "Feb" |
* | d | Number of date | 1 |
* | dd | 2digit date | "01" |
* | e | Number of day-of-week | 6 |
* | EEE | String day-of-week | "Sat" |
* | H | Number of 24hours | 5 |
* | HH | 2digit 24hours | "05" |
* | h | Number of 12hours | 5 |
* | hh | 2digit 12hours | "05" |
* | a | AM or PM | "AM" |
* | m | Number of min | 6 |
* | mm | 2digit min | "06" |
* | s | Number of sec | 8 |
* | ss | 2digit sec | "08" |
* | unixtm | Unixtime sec | 1272730884 |
* | unixms | Unixtime ms | 1272730884000 |
*
* @namespace $any.date
*
* @see $any.tpl
*
* @tutorial static-date
*
* @example
* dt = $any.date.get(); //Now
* dt = $any.date.get('2056-1-1 0:00'); //Date format string
* v = $any.date.format('yyyy-MM-dd HH:mm');
* v = $any.date.format('EEE, MMM d, yyyy', 'February 10, 2010 0:00');
*/
any.date = any.profile.create();
/**
* Months
* @memberof $any.date
* @type {array}
* @default ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
* @example
* $any.date.define.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
*/
any.date.define.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
/**
* Days
* @memberof $any.date
* @type {array}
* @default ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
* @example
* $any.date.define.days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
*/
any.date.define.days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
/**
* @ignore
*/
function dtP(dt){
if (!dt){
return new Date();
}else if (typeof dt === 'object'){
return dt;
}
if (String(dt).match(/^[\s\-]*[\d\s]+$/)){
dt = dt * 1000;
}else{
dt = dt.replace(/[\-\.]/g, '/');
if (!dt.match(/\d\s*\:\s*\d/)){
dt+= ' 0:00';
}
}
return new Date(dt);
}
/**
* @ignore
*/
function dtT(v){
return ('0' + v).slice(-2);
}
/**
* Get date value assoc.
* @function get
* @memberof $any.date
*
* @param {integer|Date|string} [date] Date source.Supporting various format.
* @param {boolean} [isError=true] Determine to occur error, failing to parse format.
* @returns {object}
*
* @tutorial static-date
* @example
* //Return object
* {
* y:2010, yyyy:"2010", yy:"10",
* M:5, MM:"05", MMM:"May",
* d:1, dd:"01", EEE:"Sat", e:6
* H:16, HH:"16", h:4, hh:"04", a:"PM"
* m:21, mm:"21"
* s:42, ss:"42"
* unixtm:1272730884, unixms:1272730884000
* }
* @example
* dt = $any.date.get(); //Now
* dt = $any.date.get('2056-1-1 0:00'); //Date format string
* dt = $any.date.get(1024100000); //Unix timestamp
* dt = $any.date.get(new Date('1893/01/01')); //Date object
*/
any.date.get = function(date, isError){
info('date.get');
var dt = dtP(date), v = {}, t;
if (!dt || isNaN(dt.getTime())){
if (isError !== false){
error('illegal format', date);
}
return null;
}
v.y = dt.getFullYear();
v.M = dt.getMonth() + 1;
v.d = dt.getDate();
v.H = dt.getHours();
v.m = dt.getMinutes();
v.s = dt.getSeconds();
v.e = dt.getDay();
v.yyyy = ('0' + v.y).slice(-4);
v.yy = dtT(v.y);
v.MM = dtT(v.M);
v.dd = dtT(v.d);
v.MMM = any.date.define.months[v.M - 1];
v.EEE = any.date.define.days[v.e];
v.a = (v.H < 12)?'AM':'PM';
v.HH = dtT(v.H);
v.h = v.H%12;
v.hh = dtT(v.h);
v.mm = dtT(v.m);
v.ss = dtT(v.s);
t = dt.getTime();
v.unixms = t; //milliseconds
v.unixtm = Math.floor(t/1000);
return v;
};
/**
* Return formated date time.
* @function format
* @memberof $any.date
*
* @param {integer|Date|string} [date] Date source.Supporting various format.
* @param {string} [format='EEE, MMM d, yyyy HH:mm'] Date format.
* @param {assoc} [opt] Option
* @param {string} [opt.error=true] Determine to occur error. - $any.date.get error
* @param {string} [opt.wrap=false] Determine to wrap each value.
* @returns {string}
*
* @tutorial static-date
* @example
* v = $any.date.format('yyyy-MM-dd HH:mm');
* v = $any.date.format('EEE, MMM d, yyyy', 'February 10, 2010 0:00');
* v = $any.date.format('EEE, MMM d, yyyy', '2063-2-30 0:00');
* v = $any.date.format('EEE, MMM, M/d, yyyy HH:mm', '1956.7.10 0:00');
* v = $any.date.format('EEE, MMM d, yyyy', 1131156102);
*/
any.date.format = function(format, date, opt){
info('date.format');
format = format || 'EEE, MMM d, yyyy HH:mm';
opt = ext({error: true, wrap: false}, opt);
var dt = any.date.get(date, opt.error);
if (!dt){
return '';
}
return any.tpl.assign(format, dt, {wrap: opt.wrap});
};
/**
* Any ui($any.ui) static methods. Layout helper methods.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | styleRule | Yes | Yes | - |
* | styleCSS | Yes | Yes | - |
* | showHides | Yes | - | - |
* | delayLoad | Yes | - | - |
* | shower | Yes | - | - |
* | swapper | Yes | - | - |
* | filler | Yes | - | - |
* | calcRelative | Yes | - | - |
*
* @namespace $any.ui
*
* @see jQuery.fn@ui
* @see jQuery.fn@ui-cmp
*
* @tutorial static-ui
* @tutorial fn-ui
* @tutorial ui-css
* @tutorial demo-ui
* @tutorial demo-various
*
* @example
* //See tutorials.
*/
any.ui = {};
/**
* Get CSSRule object by CSS name.
* @function styleRule
* @memberof $any.ui
*
* @param {string} name CSS style name.
* @returns {object} CSSRule object.
*
* @tutorial static-ui
*
* @example
* rule = $any.ui.styleRule('.demo');
*/
any.ui.styleRule = function(name){
info('ui.styleRule');
var nm = name.replace(/([^\:])\:([^\:])/, '$1::$2'), sts = document.styleSheets, i, j, r, st, l;
for (i=0;i<sts.length;i++){
try {
st = sts[i];
r = st.cssRules || st.rules;
l = r.length;
for (j=0;j<l;j++){
if (r[j].selectorText === nm){
return r[j];
}
}
}catch(e){
}
}
if(st.insertRule){
st.insertRule(name + '{}', l);
}else{
st.addRule(name, ' ', l);
}
return r[l];
};
/**
* @ignore
*/
function cml(v){
return v.replace(/\-(.)/g, function(v, t){
return t.toUpperCase();
});
}
/**
* Set CSS value dynamically.
* @function styleCSS
* @memberof $any.ui
*
* @param {string|object} rule CSSRule object or CSS style-name.
* @param {string|assoc} css CSS property name or KeyValue which CSS property and value.
* @param {string|integer} v CSS value.
* @returns {object} CSSRule object.
*
* @tutorial static-ui
*
* @example
* $any.ui.styleCSS('.demo', 'color' , 'red');
* $any.ui.styleCSS(rule, 'font-size' , '1px');
*/
any.ui.styleCSS = function(rule, css, v){
info('ui.styleCSS');
var r = (typeof rule === 'object')?rule:any.ui.styleRule(rule);
if (r){
if (typeof css === 'object'){
any.each(css, function(k, v){
r.style[cml(k)] = v;
});
}else{
r.style[cml(css)] = v;
}
}
return r;
};
var NanoUI = null;
/**
* Create NanoUI class for browser ui. So tiny UI-framework.
*
* <b><i>Note! Only for any-tiny.js.</i></b><br>
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | All methods | - | Yes | - |
*
* @function NanoUI
* @memberof $any.ui
*
* @param {function} construct Class constructor and base structure.
* @param {function|functions} methods Class methods or Function space and class methods. Add methods by prototype.
* @returns {NanoUI}
*
* @see NanoUI
* @see MicroUI
* @see $any.ui.MicroUI
* @see $any@class.makeClass
*
* @tutorial static-nanoui
* @tutorial demo-ui
*
* @example
* var NanoUI = $any.ui.NanoUI();
* var Panel = $any.ui.NanoUI(function(){ ... }, { method1: ..., method2: ...});
*/
any.ui.NanoUI = function(construct, methods){
info('NanoUI');
if (!NanoUI){
/**
* <b><i>Note! Only for any-tiny.js.</i></b><br>
* NanoUI is so tiny UI-framework.
*
* <b>Usecase</b><br>
* Use directly or Use by 'extends class'.
*
* | Method | Default ver | Tiny ver | Micro ver |
* |:---|:---:|:---:|:---:|
* | All methods | - | Yes | - |
*
* @class NanoUI
*
* @param {string} [prefix=''] Prefix.
* @param {assoc<string, string>} [target=null] Target type. <b>Type</b> <code>'id'(default), 'form', 'class'</code>.
* @param {functions} [filter=null] Value-filter functions.
* @param {functions} [mask=null] Value-mask functions.
*
* @see $any.ui.NanoUI
* @see $any@class.makeClass
*
* @tutorial static-nanoui
* @tutorial demo-ui
*
* @example
* var NanoUI = $any.ui.NanoUI();
* var nanoui = new NanoUI();
* var panel = new ($any.ui.NanoUI(function(){ ... }, { method1: ..., method2: ...}));
*/
NanoUI = any.makeClass(function(prefix, targets, filters, masks){
/**
* Element name prefix.
* @memberof NanoUI
* @protected
* @instance
* @name _prefix
* @type {string}
* @default ''
*
* @see NanoUI#prefix
* @tutorial static-nanoui
*
* @example
* var nano = new ($any.ui.NanoUI(function(){ this._prefix = 'prefix'; }, {...});
*/
this._prefix = '';
/**
* Connection to prefix and name.
* @memberof NanoUI
* @protected
* @instance
* @name _join
* @type {string}
* @default '-'
*
* @see NanoUI#prefix
* @tutorial static-nanoui
*/
this._join = '-';
this.prefix(prefix);
/**
* Element id for building. If null, id is <i>prefix</i>.
* @memberof NanoUI
* @protected
* @instance
* @name _bldid
* @type {string}
* @default null
*
* @see NanoUI#_build
* @tutorial static-nanoui
*
* @example
* this._bldid = 'targetid';
*/
this._bldid = null;
/**
* Assign parameters for building.
* @memberof NanoUI
* @protected
* @instance
* @name _blds
* @type {assoc}
* @default null
*
* @see NanoUI#build
* @see NanoUI#_build
* @tutorial static-nanoui
*/
this._blds = null;
/**
* Target type. <b>Type</b> <code>'id'(default), 'form', 'class'</code>.
* @memberof NanoUI
* @protected
* @instance
* @name _targets
* @type {assoc<string, string>}
* @default null
*
* @see NanoUI#targets
* @tutorial static-nanoui
*/
this._targets = targets || null;
/**
* Value-filters for <i>val</i> / <i>html</i>.
* @memberof NanoUI
* @protected
* @instance
* @name _filters
* @type {functions}
* @default null
*
* @see NanoUI#filters
* @see NanoUI#val
* @see NanoUI#html
* @tutorial static-nanoui
*/
this._filters = filters || null;
/**
* Value-masks.
* @memberof NanoUI
* @protected
* @instance
* @name _masks
* @type {functions}
* @default null
*
* @see NanoUI#masks
* @tutorial static-nanoui
*/
this._masks = masks || null;
/**
* Data variable. If use <i>data</i> method, require to initialize <i>_data</i>.
* @memberof NanoUI
* @protected
* @instance
* @name _data
* @type {assoc}
* @default null
*
* @see NanoUI#data
* @tutorial static-nanoui
*
* @example
* var nano = new ($any.ui.NanoUI(function(){ this._data = {}; }, {...});
*/
this._data = null;
}, {
/**
* Set prefix.
* @function
* @name prefix
* @memberof NanoUI
* @instance
* @param {string} p Prefix name.
*
* @see NanoUI#_prefix
* @tutorial static-nanoui
*
* @example
* nui.prefix('prefix');
*/
prefix: function(p){
this._prefix = p;
},
/**
* Return name prepended prefix.
* @function
* @name name
* @memberof NanoUI
* @instance
* @param {string} nm Name.
* @returns {string}
*
* @tutorial static-nanoui
*
* @example
* nui.prefix('prefix');
* name = nui.name('name1');
* //prefix-name1
*/
name: function(nm){
if (!this._prefix){
return nm;
}
return this._prefix + this._join + nm;
},
/**
* Set target types. <b>Type</b> <code>'id'(default), 'form', 'class'</code>
* @function
* @name targets
* @memberof NanoUI
* @instance
* @param {assoc<string, string>} targets Target types.
*
* @see NanoUI#_targets
* @tutorial static-nanoui
*
* @example
* nui.target({name1: 'class', name2: 'form'});
*/
targets: function(targets){
this._targets = targets;
},
/**
* Set value-filter functions.
* @function
* @name filters
* @memberof NanoUI
* @instance
* @param {functions} filters Filter functions. <code>function(v){ ... return v; }</code>
*
* @see NanoUI#val
* @see NanoUI#vals
* @see NanoUI#html
* @tutorial static-nanoui
*
* @example
* nui.filter({name1: function(v){ ... }});
*/
filters: function(filters){
this._filters = filters;
},
/**
* Apply filter and return value.
* @function
* @name filterApply
* @memberof NanoUI
* @instance
*
* @param {string} nm Filter name.
* @param {*} v Value.
* @returns {*}
*
* @see NanoUI#_filters
* @see NanoUI#filters
* @see NanoUI#val
* @see NanoUI#vals
* @tutorial static-nanoui
*
* @example
* v = nui.filterApply('filter1', v);
*/
filterApply: function(nm, v){
if (this._filters && this._filters[nm]){
v = this._filters[nm].call(this, v);
}else{
console.error('filter none', nm);
}
return v;
},
/**
* Set Value-mask functions.
* @function
* @name masks
* @memberof NanoUI
* @instance
* @param {functions} masks Mask functions. <code>function(nm, v, opt){ ... return el; }</code>
*
* @see NanoUI#_masks
* @see NanoUI#filters
* @see NanoUI#val
* @see NanoUI#vals
* @tutorial static-nanoui
*
* @example
* nui.masks({name1: function(nm, v, opt){ ... }});
*/
masks: function(masks){
this._masks = masks;
},
/**
* Set config of target element. <code>target / filter / mask</code>
* @function
* @name config
* @memberof NanoUI
* @instance
* @param {string} nm Target name.
* @param {assoc} [stg=null] Settings. <code> {target: ..., filter: ..., mask: ...}</code>
* @param {string} [stg.target=null] Target type.
* @param {function} [stg.filter=null] Filter function.
* @param {function} [stg.mask=null] Mask function.
*
* @see NanoUI#targets
* @see NanoUI#filters
* @see NanoUI#masks
* @see NanoUI#val
* @see NanoUI#vals
* @tutorial static-nanoui
*
* @example
* nui.config('name1', {target: ..., filter: ..., mask: ...});
* nui.config('name1', null);
*/
config: function(nm, stg){
stg = stg || {};
if (!this._targets){ this._targets = {}; }
this._targets[nm] = stg.target || null;
if (!this._filters){ this._filters = {}; }
this._filters[nm] = stg.filter || null;
if (!this._masks){ this._masks = {}; }
this._masks[nm] = stg.mask || null;
},
/**
* Return HTML source for building. It make possible to create ui component.
* @protected
* @function _build
* @memberof NanoUI
* @instance
*
* @param {function} [bldset] Initialize call function. <i>NanoUI::__bldset</u>
* @returns {string}
*
* @see NanoUI#_bldid
* @see NanoUI#_blds
* @tutorial static-nanoui
*
* @example
* _build: function(){
* return '<div id="prefix"><div id="{$p}-val"></div>HTML source...</div>';
* }
* _build: function(bldset){
* request.get(url, function(err, res){ bldset(res); });
* }
*/
_build: null,
/**
* Set fn and params for building.
* @function
* @name build
* @memberof NanoUI
* @instance
* @param {function} [fn] Function which return HTML source for building.
* @param {assoc} [vs] Assign parameters for building.
*
* @see NanoUI#_build
* @see NanoUI#_blds
* @tutorial static-nanoui
*
* @example
* this.build(function(){ return 'HTML source'; }, {v1: 'Iron'})
*/
build: function(fn, vs){
if (fn){
this._build = fn;
}
if (vs !== undefined){
this._blds = vs;
}
},
/**
* Initialize. This method is applied motion suspend and resume.
* @function
* @name init
* @memberof NanoUI
* @instance
*
* @see NanoUI#_init
* @tutorial static-nanoui
*
* @example
* nui.init();
*/
init: function(){
if (this._build){
var s = this._build(this.bind(this.__bldset));
if (s){
if (typeof s === 'string'){
this.__bldset(s);
}
}
}else{
this.__bldinit();
}
},
/**
* Initialize, implements method.
* @function
* @name _init
* @protected
* @memberof NanoUI
* @instance
*
* @see NanoUI#init
* @tutorial static-nanoui
*
* @example
* _init: function(){
* ...
* }
*/
_init: null,
/**
* @ignore
*/
__bldset: function(s){
var c = document.getElementById((this._bldid)?this._bldid:this._prefix);
if (c){
var vs = this._blds || {};
vs.$p = this._prefix;
c.innerHTML = any.tpl.assign(s, vs);
}
this.__bldinit();
},
/**
* @ignore
*/
__bldinit: function(){
if (this._init){
this._init();
}
},
/**
* Set value to element. and get value.
* @function
* @name val
* @memberof NanoUI
* @instance
* @param {string|Element|NodeList} nm Target name. If <i>prefix</i> is specified, prepend prefix automatically.
* @param {number|string} [v] Value. If v is undefined, get value.
* @param {assoc} [opt=null] Options.
* @returns {NanoUI|number|string}
*
* @see NanoUI#take
* @see NanoUI#filters
* @see NanoUI#masks
* @tutorial static-nanoui
*
* @example
* nui.val('name1', 1);
* nui.val('name1', 1, opt);
* v = nui.val('name1');
*/
val: function(nm, v){
if (v !== undefined) {
if(this._filters && this._filters[nm]) {
v = this._filters[nm].call(this, v);
}
if(this._masks && this._masks[nm]) {
return this._masks[nm].call(this, nm, v);
}
}
this.__apply(nm, this.__val, v);
return this;
},
/**
* @ignore
*/
__val: function(c, v){
c.value = v;
},
/**
* Set values to element.
* @function
* @name vals
* @memberof NanoUI
* @instance
* @param {assoc<string, number|string>} [vs] Name and value assoc.
* @param {assoc} [opt=null] Options.
*
* @see NanoUI#val
* @see NanoUI#filters
* @see NanoUI#masks
* @tutorial static-nanoui
*
* @example
* nui.vals({name1: 1, name2: 2});
*/
vals: function(vs, opt){
for (var k in vs){
if (vs.hasOwnProperty(vs[k])){
this.val(k, vs[k], opt);
}
}
},
/**
* Set value to element by innerHTML.
* @function
* @name html
* @memberof NanoUI
* @instance
* @param {string|Element|NodeList} nm Target name. If <i>prefix</i> is specified, prepend prefix automatically.
* @param {number|string} [v] Value.
* @returns {NanoUI}
*
* @see NanoUI#take
* @see NanoUI#html
* @tutorial static-nanoui
*
* @example
* nui.html('name1', 'Stone');
*/
html: function(nm, v){
if(this._filters && this._filters[nm]) {
v = this._filters[nm].call(this, v);
}
this.__apply(nm, this.__html, v);
return this;
},
/**
* @ignore
*/
__html: function(c, v){
c.innerHTML = v;
},
/**
* Set view-state by Css display.
* @function
* @name view
* @memberof NanoUI
* @instance
* @param {string|Element|NodeList} nm Target name. If <i>prefix</i> is specified, prepend prefix automatically.
* @param {boolean} [v] Show / hide.
* @param {string} [prop] Css display style value.
* @returns {NanoUI}
*
* @see NanoUI#take
* @tutorial static-nanoui
*
* @example
* nui.view('name1', 123, opt);
*/
view: function(nm, v, prop){
this.__apply(nm, this.__view, v, prop);
return this;
},
/**
* @ignore
*/
__view: function(c, v, w){
if (w === undefined){
w = (c.tagName.toLowerCase().search(/^(div|p|form|table|h\d)$/) !== -1)?'block':'inline';
}
c.style.display = (v)?w:'none';
},
/**
* Bind click by onclick.
* @function
* @name click
* @memberof NanoUI
* @instance
* @param {string|Element|NodeList} nm Target name. If <i>prefix</i> is specified, prepend prefix automatically.
* @param {function} fn Callback function.
* @param {boolean} [unbind=false] If true, not use <i>bind</i> method.
* @returns {NanoUI}
*
* @see NanoUI#take
* @tutorial static-nanoui
*
* @example
* nui.click('name1', function(){ ... });
* nui.click('name1', function(){ ... }, true);
*/
click: function(nm, fn, unbind){
this.__apply(nm, this.__click, this.__bind(fn, unbind));
return this;
},
/**
* @ignore
*/
__click: function(c, fn){
c.onclick = fn;
},
/**
* Bind changing by onchange.
* @function
* @name change
* @memberof NanoUI
* @instance
* @param {string|Element|NodeList} nm Target name. If <i>prefix</i> is specified, prepend prefix automatically.
* @param {function} fn Callback function.
* @param {boolean} [unbind=false] If true, not use <i>bind</i> method.
* @returns {NanoUI}
*
* @see NanoUI#take
* @tutorial static-nanoui
*
* @example
* nui.change('name1', function(){ ... });
* nui.change('name1', function(){ ... }, true);
*/
change: function(nm, fn, unbind){
this.__apply(nm, this.__change, this.__bind(fn, unbind));
return this;
},
/**
* @ignore
*/
__change: function(c, fn){
c.onchange = fn;
},
/**
* Bind event by <i>on event</i>.
* @function
* @name on
* @memberof NanoUI
* @instance
* @param {string|Element|NodeList} nm Target name. If <i>prefix</i> is specified, prepend prefix automatically.
* @param {string} event Event.
* @param {function} fn Callback function.
* @param {boolean} [unbind=false] If true, not use <i>bind</i> method.
* @returns {NanoUI}
*
* @see NanoUI#take
* @tutorial static-nanoui
*
* @example
* nui.on('name1', 'mouseover', function(){ ... });
* nui.on('name1', 'mouseover', function(){ ... }, true);
*/
on: function(nm, event, fn, unbind){
this.__apply(nm, this.__on, event, this.__bind(fn, unbind));
return this;
},
/**
* @ignore
*/
__on: function(c, ev, fn){
c['on' + ev] = fn;
},
/**
* @ignore
*/
__bind: function(fn, b){
return (b)?fn:this.bind(fn);
},
/**
* Take element by name with prefix. Provide auto-selector by <i>prefix</i> and <i>target</i>. If <i>form</i> or <i>class</i>, return NodeList.
*
* <b>Specification</b><br>
* Internal use: <code>_prefix</code> <code>_targets</code>
*
* @function
* @name take
* @memberof NanoUI
* @instance
* @param {string} nm Element name.
* @param {string|function} type Target type. <b>Type</b> <code>'id'(default), 'form', 'class'</code>
* @returns {Element|NodeList}
*
* @see NanoUI#prefix
* @see NanoUI#targets
* @tutorial static-nanoui
*
* @example
* nui.take('name1').innerHTML('sample');
* nui.take('name2', 'class')[0].innerHTML('sample');
* nui.take('name3', 'form')[0].innerHTML('sample');
*/
take: function(nm, type){
var t = this.name(nm);
type = type || ((this._targets)?this._targets[nm]:null);
if (type){
switch (type){
case 'form':
return document.getElementsByName(t);
break;
case 'class':
return document.getElementsByClassName(t);
break;
//case 'id':
default:
break;
}
}
return document.getElementById(t);
},
/**
* @ignore
*/
__take: function(nm, type){
if (typeof nm === 'object'){
return nm;
}
return this.take(nm , type);
},
/**
* Return element by selector expression.
*
* @function
* @name selector
* @memberof NanoUI
* @instance
* @param {string} qs Selector expression.
* @returns {NodeList}
*
* @tutorial static-nanoui
*
* @example
* el = nui.query('#name1');
*/
selector: function(qs){
return document.querySelectorAll(qs);
},
/**
* Set to data and get from data. This method use <i>_data</i>. Require to initialize <i>_data</i> before using method.
*
* @function
* @name data
* @memberof NanoUI
* @instance
* @param {string} nm Element name.
* @returns {*}
*
* @see NanoUI#_data
* @tutorial static-nanoui
*
* @example
* v = nui.data('v1');
* nui.data('v1', 123);
*/
data: function(key, v){
if (!this._data){
console.error('_data is null.');
return;
}
return any.data(this._data, key, v);
},
/**
* @ignore
*/
__apply: function(nm, link, v, w){
var c = this.__take(nm);
if (c.nodeType === 1){
link(c, v, w);
}else if (c){ //NodeList
for (var i=0;i<c.length;i++){
link(c[i], v, w);
}
}else{
console.error('element none: ' + nm);
}
}
}, null, true);
}
if (construct || methods){
return any.makeClass(construct, methods, NanoUI, false);
}
return NanoUI;
};
})($any);
|
module.exports={title:"PayPal",slug:"paypal",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>PayPal</title><path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.565-5.946.36-1.847.174-3.388-.777-4.471z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://www.paypal.com/",hex:"00457C",guidelines:void 0,license:void 0}; |
import Fixture from '../../Fixture';
const React = window.React;
class NumberInputDecimal extends React.Component {
state = {value: '.98'};
changeValue = () => {
this.setState({
value: '0.98',
});
};
render() {
const {value} = this.state;
return (
<Fixture>
<div>{this.props.children}</div>
<div className="control-box">
<input
type="number"
value={value}
onChange={e => {
this.setState({value: e.target.value});
}}
/>
<button onClick={this.changeValue}>change.98 to 0.98</button>
</div>
</Fixture>
);
}
}
export default NumberInputDecimal;
|
/*
* /MathJax/localization/cy/TeX.js
*
* Copyright (c) 2009-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Localization.addTranslation("cy","TeX",{version:"2.7.2",isLoaded:true,strings:{}});MathJax.Ajax.loadComplete("[MathJax]/localization/cy/TeX.js");
|
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A LinkedMap data structure that is accessed using key/value
* pairs like an ordinary Map, but which guarantees a consistent iteration
* order over its entries. The iteration order is either insertion order (the
* default) or ordered from most recent to least recent use. By setting a fixed
* size, the LRU version of the LinkedMap makes an effective object cache. This
* data structure is similar to Java's LinkedHashMap.
*
*/
goog.provide('goog.structs.LinkedMap');
goog.require('goog.structs.Map');
/**
* Class for a LinkedMap datastructure, which combines O(1) map access for
* key/value pairs with a linked list for a consistent iteration order. Sample
* usage:
*
* <pre>
* var m = new LinkedMap();
* m.set('param1', 'A');
* m.set('param2', 'B');
* m.set('param3', 'C');
* alert(m.getKeys()); // param1, param2, param3
*
* var c = new LinkedMap(5, true);
* for (var i = 0; i < 10; i++) {
* c.set('entry' + i, false);
* }
* alert(c.getKeys()); // entry9, entry8, entry7, entry6, entry5
*
* c.set('entry5', true);
* c.set('entry1', false);
* alert(c.getKeys()); // entry1, entry5, entry9, entry8, entry7
* </pre>
*
* @param {number=} opt_maxCount The maximum number of objects to store in the
* LinkedMap. If unspecified or 0, there is no maximum.
* @param {boolean=} opt_cache When set, the LinkedMap stores items in order
* from most recently used to least recently used, instead of insertion
* order.
* @constructor
*/
goog.structs.LinkedMap = function(opt_maxCount, opt_cache) {
/**
* The maximum number of entries to allow, or null if there is no limit.
* @type {?number}
* @private
*/
this.maxCount_ = opt_maxCount || null;
/**
* @type {boolean}
* @private
*/
this.cache_ = !!opt_cache;
this.map_ = new goog.structs.Map();
this.head_ = new goog.structs.LinkedMap.Node_('', undefined);
this.head_.next = this.head_.prev = this.head_;
};
/**
* Finds a node and updates it to be the most recently used.
* @param {string} key The key of the node.
* @return {goog.structs.LinkedMap.Node_} The node or null if not found.
* @private
*/
goog.structs.LinkedMap.prototype.findAndMoveToTop_ = function(key) {
var node = /** @type {goog.structs.LinkedMap.Node_} */ (this.map_.get(key));
if (node) {
if (this.cache_) {
node.remove();
this.insert_(node);
}
}
return node;
};
/**
* Retrieves the value for a given key. If this is a caching LinkedMap, the
* entry will become the most recently used.
* @param {string} key The key to retrieve the value for.
* @param {*=} opt_val A default value that will be returned if the key is
* not found, defaults to undefined.
* @return {*} The retrieved value.
*/
goog.structs.LinkedMap.prototype.get = function(key, opt_val) {
var node = this.findAndMoveToTop_(key);
return node ? node.value : opt_val;
};
/**
* Retrieves the value for a given key without updating the entry to be the
* most recently used.
* @param {string} key The key to retrieve the value for.
* @param {*=} opt_val A default value that will be returned if the key is
* not found.
* @return {*} The retrieved value.
*/
goog.structs.LinkedMap.prototype.peekValue = function(key, opt_val) {
var node = this.map_.get(key);
return node ? node.value : opt_val;
};
/**
* Sets a value for a given key. If this is a caching LinkedMap, this entry
* will become the most recently used.
* @param {string} key The key to retrieve the value for.
* @param {*} value A default value that will be returned if the key is
* not found.
*/
goog.structs.LinkedMap.prototype.set = function(key, value) {
var node = this.findAndMoveToTop_(key);
if (node) {
node.value = value;
} else {
node = new goog.structs.LinkedMap.Node_(key, value);
this.map_.set(key, node);
this.insert_(node);
}
};
/**
* Returns the value of the first node without making any modifications.
* @return {*} The value of the first node or undefined if the map is empty.
*/
goog.structs.LinkedMap.prototype.peek = function() {
return this.head_.next.value;
};
/**
* Returns the value of the last node without making any modifications.
* @return {*} The value of the last node or undefined if the map is empty.
*/
goog.structs.LinkedMap.prototype.peekLast = function() {
return this.head_.prev.value;
};
/**
* Removes the first node from the list and returns its value.
* @return {*} The value of the popped node, or undefined if the map was empty.
*/
goog.structs.LinkedMap.prototype.shift = function() {
return this.popNode_(this.head_.next);
};
/**
* Removes the last node from the list and returns its value.
* @return {*} The value of the popped node, or undefined if the map was empty.
*/
goog.structs.LinkedMap.prototype.pop = function() {
return this.popNode_(this.head_.prev);
};
/**
* Removes a value from the LinkedMap based on its key.
* @param {string} key The key to remove.
* @return {boolean} True if the entry was removed, false if the key was not
* found.
*/
goog.structs.LinkedMap.prototype.remove = function(key) {
var node = /** @type {goog.structs.LinkedMap.Node_} */ (this.map_.get(key));
if (node) {
this.removeNode(node);
return true;
}
return false;
};
/**
* Removes a node from the {@code LinkedMap}. It can be overridden to do
* further cleanup such as disposing of the node value.
* @param {!goog.structs.LinkedMap.Node_} node The node to remove.
* @protected
*/
goog.structs.LinkedMap.prototype.removeNode = function(node) {
node.remove();
this.map_.remove(node.key);
};
/**
* @return {number} The number of items currently in the LinkedMap.
*/
goog.structs.LinkedMap.prototype.getCount = function() {
return this.map_.getCount();
};
/**
* @return {boolean} True if the cache is empty, false if it contains any items.
*/
goog.structs.LinkedMap.prototype.isEmpty = function() {
return this.map_.isEmpty();
};
/**
* Sets the maximum number of entries allowed in this object, truncating any
* excess objects if necessary.
* @param {number} maxCount The new maximum number of entries to allow.
*/
goog.structs.LinkedMap.prototype.setMaxCount = function(maxCount) {
this.maxCount_ = maxCount || null;
if (this.maxCount_ != null) {
this.truncate_(this.maxCount_);
}
};
/**
* @return {Array.<string>} The list of the keys in the appropriate order for
* this LinkedMap.
*/
goog.structs.LinkedMap.prototype.getKeys = function() {
return this.map(function(val, key) {
return key;
});
};
/**
* @return {!Array} The list of the values in the appropriate order for
* this LinkedMap.
*/
goog.structs.LinkedMap.prototype.getValues = function() {
return this.map(function(val, key) {
return val;
});
};
/**
* Tests whether a provided value is currently in the LinkedMap. This does not
* affect item ordering in cache-style LinkedMaps.
* @param {Object} value The value to check for.
* @return {boolean} Whether the value is in the LinkedMap.
*/
goog.structs.LinkedMap.prototype.contains = function(value) {
return this.some(function(el) {
return el == value;
});
};
/**
* Tests whether a provided key is currently in the LinkedMap. This does not
* affect item ordering in cache-style LinkedMaps.
* @param {string} key The key to check for.
* @return {boolean} Whether the key is in the LinkedMap.
*/
goog.structs.LinkedMap.prototype.containsKey = function(key) {
return this.map_.containsKey(key);
};
/**
* Removes all entries in this object.
*/
goog.structs.LinkedMap.prototype.clear = function() {
this.truncate_(0);
};
/**
* Calls a function on each item in the LinkedMap.
*
* @see goog.structs.forEach
* @param {Function} f The function to call for each item. The function takes
* three arguments: the value, the key, and the LinkedMap.
* @param {Object=} opt_obj The object context to use as "this" for the
* function.
*/
goog.structs.LinkedMap.prototype.forEach = function(f, opt_obj) {
for (var n = this.head_.next; n != this.head_; n = n.next) {
f.call(opt_obj, n.value, n.key, this);
}
};
/**
* Calls a function on each item in the LinkedMap and returns the results of
* those calls in an array.
*
* @see goog.structs.map
* @param {!Function} f The function to call for each item. The function takes
* three arguments: the value, the key, and the LinkedMap.
* @param {Object=} opt_obj The object context to use as "this" for the
* function.
* @return {!Array} The results of the function calls for each item in the
* LinkedMap.
*/
goog.structs.LinkedMap.prototype.map = function(f, opt_obj) {
var rv = [];
for (var n = this.head_.next; n != this.head_; n = n.next) {
rv.push(f.call(opt_obj, n.value, n.key, this));
}
return rv;
};
/**
* Calls a function on each item in the LinkedMap and returns true if any of
* those function calls returns a true-like value.
*
* @see goog.structs.some
* @param {Function} f The function to call for each item. The function takes
* three arguments: the value, the key, and the LinkedMap, and returns a
* boolean.
* @param {Object=} opt_obj The object context to use as "this" for the
* function.
* @return {boolean} Whether f evaluates to true for at least one item in the
* LinkedMap.
*/
goog.structs.LinkedMap.prototype.some = function(f, opt_obj) {
for (var n = this.head_.next; n != this.head_; n = n.next) {
if (f.call(opt_obj, n.value, n.key, this)) {
return true;
}
}
return false;
};
/**
* Calls a function on each item in the LinkedMap and returns true only if every
* function call returns a true-like value.
*
* @see goog.structs.some
* @param {Function} f The function to call for each item. The function takes
* three arguments: the value, the key, and the Cache, and returns a
* boolean.
* @param {Object=} opt_obj The object context to use as "this" for the
* function.
* @return {boolean} Whether f evaluates to true for every item in the Cache.
*/
goog.structs.LinkedMap.prototype.every = function(f, opt_obj) {
for (var n = this.head_.next; n != this.head_; n = n.next) {
if (!f.call(opt_obj, n.value, n.key, this)) {
return false;
}
}
return true;
};
/**
* Appends a node to the list. LinkedMap in cache mode adds new nodes to
* the head of the list, otherwise they are appended to the tail. If there is a
* maximum size, the list will be truncated if necessary.
*
* @param {goog.structs.LinkedMap.Node_} node The item to insert.
* @private
*/
goog.structs.LinkedMap.prototype.insert_ = function(node) {
if (this.cache_) {
node.next = this.head_.next;
node.prev = this.head_;
this.head_.next = node;
node.next.prev = node;
} else {
node.prev = this.head_.prev;
node.next = this.head_;
this.head_.prev = node;
node.prev.next = node;
}
if (this.maxCount_ != null) {
this.truncate_(this.maxCount_);
}
};
/**
* Removes elements from the LinkedMap if the given count has been exceeded.
* In cache mode removes nodes from the tail of the list. Otherwise removes
* nodes from the head.
* @param {number} count Number of elements to keep.
* @private
*/
goog.structs.LinkedMap.prototype.truncate_ = function(count) {
for (var i = this.map_.getCount(); i > count; i--) {
this.removeNode(this.cache_ ? this.head_.prev : this.head_.next);
}
};
/**
* Removes the node from the LinkedMap if it is not the head, and returns
* the node's value.
* @param {!goog.structs.LinkedMap.Node_} node The item to remove.
* @return {*} The value of the popped node.
* @private
*/
goog.structs.LinkedMap.prototype.popNode_ = function(node) {
if (this.head_ != node) {
this.removeNode(node);
}
return node.value;
};
/**
* Internal class for a doubly-linked list node containing a key/value pair.
* @param {string} key The key.
* @param {*} value The value.
* @constructor
* @private
*/
goog.structs.LinkedMap.Node_ = function(key, value) {
this.key = key;
this.value = value;
};
/**
* The next node in the list.
* @type {!goog.structs.LinkedMap.Node_}
*/
goog.structs.LinkedMap.Node_.prototype.next;
/**
* The previous node in the list.
* @type {!goog.structs.LinkedMap.Node_}
*/
goog.structs.LinkedMap.Node_.prototype.prev;
/**
* Causes this node to remove itself from the list.
*/
goog.structs.LinkedMap.Node_.prototype.remove = function() {
this.prev.next = this.next;
this.next.prev = this.prev;
delete this.prev;
delete this.next;
};
|
/**
* Copyright (c) Nicolas Gallagher.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import ReactNativePropRegistry from './ReactNativePropRegistry';
import flattenStyle from './flattenStyle';
var absoluteFillObject = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0
};
var absoluteFill = ReactNativePropRegistry.register(absoluteFillObject);
var StyleSheet = {
absoluteFill: absoluteFill,
absoluteFillObject: absoluteFillObject,
compose: function compose(style1, style2) {
if (process.env.NODE_ENV !== 'production') {
/* eslint-disable prefer-rest-params */
var len = arguments.length;
if (len > 2) {
var readableStyles = Array.prototype.slice.call(arguments).map(function (a) {
return flattenStyle(a);
});
throw new Error("StyleSheet.compose() only accepts 2 arguments, received " + len + ": " + JSON.stringify(readableStyles));
}
/* eslint-enable prefer-rest-params */
}
if (style1 && style2) {
return [style1, style2];
} else {
return style1 || style2;
}
},
create: function create(styles) {
var result = {};
Object.keys(styles).forEach(function (key) {
if (process.env.NODE_ENV !== 'production') {
var validate = require('./validate');
var interopValidate = validate.default ? validate.default : validate;
interopValidate(key, styles);
}
var id = styles[key] && ReactNativePropRegistry.register(styles[key]);
result[key] = id;
});
return result;
},
flatten: flattenStyle,
// `hairlineWidth` is not implemented using screen density as browsers may
// round sub-pixel values down to `0`, causing the line not to be rendered.
hairlineWidth: 1
};
export default StyleSheet; |
/*globals $*/
/*jslint vars: true, eqeq: true, continue: true*/
/**
* Recalculate.
*
* Licensed under the MIT License
*
*/
// Dependencies:
// 1) jquery
// 2) jquery-svg.js
// 3) svgedit.js
// 4) browser.js
// 5) math.js
// 6) history.js
// 7) units.js
// 8) svgtransformlist.js
// 9) svgutils.js
// 10) coords.js
var svgedit = svgedit || {};
(function() {
if (!svgedit.recalculate) {
svgedit.recalculate = {};
}
var NS = svgedit.NS;
var context_;
// Function: svgedit.recalculate.init
svgedit.recalculate.init = function(editorContext) {
context_ = editorContext;
};
// Function: svgedit.recalculate.updateClipPath
// Updates a <clipPath>s values based on the given translation of an element
//
// Parameters:
// attr - The clip-path attribute value with the clipPath's ID
// tx - The translation's x value
// ty - The translation's y value
svgedit.recalculate.updateClipPath = function(attr, tx, ty) {
var path = getRefElem(attr).firstChild;
var cp_xform = svgedit.transformlist.getTransformList(path);
var newxlate = context_.getSVGRoot().createSVGTransform();
newxlate.setTranslate(tx, ty);
cp_xform.appendItem(newxlate);
// Update clipPath's dimensions
svgedit.recalculate.recalculateDimensions(path);
};
// Function: svgedit.recalculate.recalculateDimensions
// Decides the course of action based on the element's transform list
//
// Parameters:
// selected - The DOM element to recalculate
//
// Returns:
// Undo command object with the resulting change
svgedit.recalculate.recalculateDimensions = function(selected) {
if (selected == null) {return null;}
// Firefox Issue - 1081
if (selected.nodeName == "svg" && navigator.userAgent.indexOf("Firefox/20") >= 0) {
return null;
}
var svgroot = context_.getSVGRoot();
var tlist = svgedit.transformlist.getTransformList(selected);
var k;
// remove any unnecessary transforms
if (tlist && tlist.numberOfItems > 0) {
k = tlist.numberOfItems;
while (k--) {
var xform = tlist.getItem(k);
if (xform.type === 0) {
tlist.removeItem(k);
}
// remove identity matrices
else if (xform.type === 1) {
if (svgedit.math.isIdentity(xform.matrix)) {
tlist.removeItem(k);
}
}
// remove zero-degree rotations
else if (xform.type === 4) {
if (xform.angle === 0) {
tlist.removeItem(k);
}
}
}
// End here if all it has is a rotation
if (tlist.numberOfItems === 1 &&
svgedit.utilities.getRotationAngle(selected)) {return null;}
}
// if this element had no transforms, we are done
if (!tlist || tlist.numberOfItems == 0) {
// Chrome has a bug that requires clearing the attribute first.
selected.setAttribute('transform', '');
selected.removeAttribute('transform');
return null;
}
// TODO: Make this work for more than 2
if (tlist) {
k = tlist.numberOfItems;
var mxs = [];
while (k--) {
var xform = tlist.getItem(k);
if (xform.type === 1) {
mxs.push([xform.matrix, k]);
} else if (mxs.length) {
mxs = [];
}
}
if (mxs.length === 2) {
var m_new = svgroot.createSVGTransformFromMatrix(svgedit.math.matrixMultiply(mxs[1][0], mxs[0][0]));
tlist.removeItem(mxs[0][1]);
tlist.removeItem(mxs[1][1]);
tlist.insertItemBefore(m_new, mxs[1][1]);
}
// combine matrix + translate
k = tlist.numberOfItems;
if (k >= 2 && tlist.getItem(k-2).type === 1 && tlist.getItem(k-1).type === 2) {
var mt = svgroot.createSVGTransform();
var m = svgedit.math.matrixMultiply(
tlist.getItem(k-2).matrix,
tlist.getItem(k-1).matrix);
mt.setMatrix(m);
tlist.removeItem(k-2);
tlist.removeItem(k-2);
tlist.appendItem(mt);
}
}
// If it still has a single [M] or [R][M], return null too (prevents BatchCommand from being returned).
switch ( selected.tagName ) {
// Ignore these elements, as they can absorb the [M]
case 'line':
case 'polyline':
case 'polygon':
case 'path':
break;
default:
if ((tlist.numberOfItems === 1 && tlist.getItem(0).type === 1) ||
(tlist.numberOfItems === 2 && tlist.getItem(0).type === 1 && tlist.getItem(0).type === 4)) {
return null;
}
}
// Grouped SVG element
var gsvg = $(selected).data('gsvg');
// we know we have some transforms, so set up return variable
var batchCmd = new svgedit.history.BatchCommand('Transform');
// store initial values that will be affected by reducing the transform list
var changes = {}, initial = null, attrs = [];
switch (selected.tagName) {
case 'line':
attrs = ['x1', 'y1', 'x2', 'y2'];
break;
case 'circle':
attrs = ['cx', 'cy', 'r'];
break;
case 'ellipse':
attrs = ['cx', 'cy', 'rx', 'ry'];
break;
case 'foreignObject':
case 'rect':
case 'image':
attrs = ['width', 'height', 'x', 'y'];
break;
case 'use':
case 'text':
case 'tspan':
attrs = ['x', 'y'];
break;
case 'polygon':
case 'polyline':
initial = {};
initial.points = selected.getAttribute('points');
var list = selected.points;
var len = list.numberOfItems;
changes.points = new Array(len);
var i;
for (i = 0; i < len; ++i) {
var pt = list.getItem(i);
changes.points[i] = {x:pt.x, y:pt.y};
}
break;
case 'path':
initial = {};
initial.d = selected.getAttribute('d');
changes.d = selected.getAttribute('d');
break;
} // switch on element type to get initial values
if (attrs.length) {
changes = $(selected).attr(attrs);
$.each(changes, function(attr, val) {
changes[attr] = svgedit.units.convertToNum(attr, val);
});
} else if (gsvg) {
// GSVG exception
changes = {
x: $(gsvg).attr('x') || 0,
y: $(gsvg).attr('y') || 0
};
}
// if we haven't created an initial array in polygon/polyline/path, then
// make a copy of initial values and include the transform
if (initial == null) {
initial = $.extend(true, {}, changes);
$.each(initial, function(attr, val) {
initial[attr] = svgedit.units.convertToNum(attr, val);
});
}
// save the start transform value too
initial.transform = context_.getStartTransform() || '';
// if it's a regular group, we have special processing to flatten transforms
if ((selected.tagName == 'g' && !gsvg) || selected.tagName == 'a') {
var box = svgedit.utilities.getBBox(selected),
oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
newcenter = svgedit.math.transformPoint(box.x+box.width/2,
box.y+box.height/2,
svgedit.math.transformListToTransform(tlist).matrix),
m = svgroot.createSVGMatrix();
// temporarily strip off the rotate and save the old center
var gangle = svgedit.utilities.getRotationAngle(selected);
if (gangle) {
var a = gangle * Math.PI / 180;
if ( Math.abs(a) > (1.0e-10) ) {
var s = Math.sin(a)/(1 - Math.cos(a));
} else {
// FIXME: This blows up if the angle is exactly 0!
var s = 2/a;
}
var i;
for (i = 0; i < tlist.numberOfItems; ++i) {
var xform = tlist.getItem(i);
if (xform.type == 4) {
// extract old center through mystical arts
var rm = xform.matrix;
oldcenter.y = (s*rm.e + rm.f)/2;
oldcenter.x = (rm.e - s*rm.f)/2;
tlist.removeItem(i);
break;
}
}
}
var tx = 0, ty = 0,
operation = 0,
N = tlist.numberOfItems;
if (N) {
var first_m = tlist.getItem(0).matrix;
}
// first, if it was a scale then the second-last transform will be it
if (N >= 3 && tlist.getItem(N-2).type == 3 &&
tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
{
operation = 3; // scale
// if the children are unrotated, pass the scale down directly
// otherwise pass the equivalent matrix() down directly
var tm = tlist.getItem(N-3).matrix,
sm = tlist.getItem(N-2).matrix,
tmn = tlist.getItem(N-1).matrix;
var children = selected.childNodes;
var c = children.length;
while (c--) {
var child = children.item(c);
tx = 0;
ty = 0;
if (child.nodeType == 1) {
var childTlist = svgedit.transformlist.getTransformList(child);
// some children might not have a transform (<metadata>, <defs>, etc)
if (!childTlist) {continue;}
var m = svgedit.math.transformListToTransform(childTlist).matrix;
// Convert a matrix to a scale if applicable
// if (svgedit.math.hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) {
// if (m.b==0 && m.c==0 && m.e==0 && m.f==0) {
// childTlist.removeItem(0);
// var translateOrigin = svgroot.createSVGTransform(),
// scale = svgroot.createSVGTransform(),
// translateBack = svgroot.createSVGTransform();
// translateOrigin.setTranslate(0, 0);
// scale.setScale(m.a, m.d);
// translateBack.setTranslate(0, 0);
// childTlist.appendItem(translateBack);
// childTlist.appendItem(scale);
// childTlist.appendItem(translateOrigin);
// }
// }
var angle = svgedit.utilities.getRotationAngle(child);
var oldStartTransform = context_.getStartTransform();
var childxforms = [];
context_.setStartTransform(child.getAttribute('transform'));
if (angle || svgedit.math.hasMatrixTransform(childTlist)) {
var e2t = svgroot.createSVGTransform();
e2t.setMatrix(svgedit.math.matrixMultiply(tm, sm, tmn, m));
childTlist.clear();
childTlist.appendItem(e2t);
childxforms.push(e2t);
}
// if not rotated or skewed, push the [T][S][-T] down to the child
else {
// update the transform list with translate,scale,translate
// slide the [T][S][-T] from the front to the back
// [T][S][-T][M] = [M][T2][S2][-T2]
// (only bringing [-T] to the right of [M])
// [T][S][-T][M] = [T][S][M][-T2]
// [-T2] = [M_inv][-T][M]
var t2n = svgedit.math.matrixMultiply(m.inverse(), tmn, m);
// [T2] is always negative translation of [-T2]
var t2 = svgroot.createSVGMatrix();
t2.e = -t2n.e;
t2.f = -t2n.f;
// [T][S][-T][M] = [M][T2][S2][-T2]
// [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv]
var s2 = svgedit.math.matrixMultiply(t2.inverse(), m.inverse(), tm, sm, tmn, m, t2n.inverse());
var translateOrigin = svgroot.createSVGTransform(),
scale = svgroot.createSVGTransform(),
translateBack = svgroot.createSVGTransform();
translateOrigin.setTranslate(t2n.e, t2n.f);
scale.setScale(s2.a, s2.d);
translateBack.setTranslate(t2.e, t2.f);
childTlist.appendItem(translateBack);
childTlist.appendItem(scale);
childTlist.appendItem(translateOrigin);
childxforms.push(translateBack);
childxforms.push(scale);
childxforms.push(translateOrigin);
// logMatrix(translateBack.matrix);
// logMatrix(scale.matrix);
} // not rotated
batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(child) );
// TODO: If any <use> have this group as a parent and are
// referencing this child, then we need to impose a reverse
// scale on it so that when it won't get double-translated
// var uses = selected.getElementsByTagNameNS(NS.SVG, 'use');
// var href = '#' + child.id;
// var u = uses.length;
// while (u--) {
// var useElem = uses.item(u);
// if (href == svgedit.utilities.getHref(useElem)) {
// var usexlate = svgroot.createSVGTransform();
// usexlate.setTranslate(-tx,-ty);
// svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate,0);
// batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(useElem) );
// }
// }
context_.setStartTransform(oldStartTransform);
} // element
} // for each child
// Remove these transforms from group
tlist.removeItem(N-1);
tlist.removeItem(N-2);
tlist.removeItem(N-3);
} else if (N >= 3 && tlist.getItem(N-1).type == 1) {
operation = 3; // scale
m = svgedit.math.transformListToTransform(tlist).matrix;
var e2t = svgroot.createSVGTransform();
e2t.setMatrix(m);
tlist.clear();
tlist.appendItem(e2t);
}
// next, check if the first transform was a translate
// if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ]
// therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ]
else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
tlist.getItem(0).type == 2)
{
operation = 2; // translate
var T_M = svgedit.math.transformListToTransform(tlist).matrix;
tlist.removeItem(0);
var M_inv = svgedit.math.transformListToTransform(tlist).matrix.inverse();
var M2 = svgedit.math.matrixMultiply( M_inv, T_M );
tx = M2.e;
ty = M2.f;
if (tx != 0 || ty != 0) {
// we pass the translates down to the individual children
var children = selected.childNodes;
var c = children.length;
var clipPaths_done = [];
while (c--) {
var child = children.item(c);
if (child.nodeType == 1) {
// Check if child has clip-path
if (child.getAttribute('clip-path')) {
// tx, ty
var attr = child.getAttribute('clip-path');
if (clipPaths_done.indexOf(attr) === -1) {
svgedit.recalculate.updateClipPath(attr, tx, ty);
clipPaths_done.push(attr);
}
}
var oldStartTransform = context_.getStartTransform();
context_.setStartTransform(child.getAttribute('transform'));
var childTlist = svgedit.transformlist.getTransformList(child);
// some children might not have a transform (<metadata>, <defs>, etc)
if (childTlist) {
var newxlate = svgroot.createSVGTransform();
newxlate.setTranslate(tx, ty);
if (childTlist.numberOfItems) {
childTlist.insertItemBefore(newxlate, 0);
} else {
childTlist.appendItem(newxlate);
}
batchCmd.addSubCommand(svgedit.recalculate.recalculateDimensions(child));
// If any <use> have this group as a parent and are
// referencing this child, then impose a reverse translate on it
// so that when it won't get double-translated
var uses = selected.getElementsByTagNameNS(NS.SVG, 'use');
var href = '#' + child.id;
var u = uses.length;
while (u--) {
var useElem = uses.item(u);
if (href == svgedit.utilities.getHref(useElem)) {
var usexlate = svgroot.createSVGTransform();
usexlate.setTranslate(-tx,-ty);
svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate, 0);
batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(useElem) );
}
}
context_.setStartTransform(oldStartTransform);
}
}
}
clipPaths_done = [];
context_.setStartTransform(oldStartTransform);
}
}
// else, a matrix imposition from a parent group
// keep pushing it down to the children
else if (N == 1 && tlist.getItem(0).type == 1 && !gangle) {
operation = 1;
var m = tlist.getItem(0).matrix,
children = selected.childNodes,
c = children.length;
while (c--) {
var child = children.item(c);
if (child.nodeType == 1) {
var oldStartTransform = context_.getStartTransform();
context_.setStartTransform(child.getAttribute('transform'));
var childTlist = svgedit.transformlist.getTransformList(child);
if (!childTlist) {continue;}
var em = svgedit.math.matrixMultiply(m, svgedit.math.transformListToTransform(childTlist).matrix);
var e2m = svgroot.createSVGTransform();
e2m.setMatrix(em);
childTlist.clear();
childTlist.appendItem(e2m, 0);
batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(child) );
context_.setStartTransform(oldStartTransform);
// Convert stroke
// TODO: Find out if this should actually happen somewhere else
var sw = child.getAttribute('stroke-width');
if (child.getAttribute('stroke') !== 'none' && !isNaN(sw)) {
var avg = (Math.abs(em.a) + Math.abs(em.d)) / 2;
child.setAttribute('stroke-width', sw * avg);
}
}
}
tlist.clear();
}
// else it was just a rotate
else {
if (gangle) {
var newRot = svgroot.createSVGTransform();
newRot.setRotate(gangle, newcenter.x, newcenter.y);
if (tlist.numberOfItems) {
tlist.insertItemBefore(newRot, 0);
} else {
tlist.appendItem(newRot);
}
}
if (tlist.numberOfItems == 0) {
selected.removeAttribute('transform');
}
return null;
}
// if it was a translate, put back the rotate at the new center
if (operation == 2) {
if (gangle) {
newcenter = {
x: oldcenter.x + first_m.e,
y: oldcenter.y + first_m.f
};
var newRot = svgroot.createSVGTransform();
newRot.setRotate(gangle, newcenter.x, newcenter.y);
if (tlist.numberOfItems) {
tlist.insertItemBefore(newRot, 0);
} else {
tlist.appendItem(newRot);
}
}
}
// if it was a resize
else if (operation == 3) {
var m = svgedit.math.transformListToTransform(tlist).matrix;
var roldt = svgroot.createSVGTransform();
roldt.setRotate(gangle, oldcenter.x, oldcenter.y);
var rold = roldt.matrix;
var rnew = svgroot.createSVGTransform();
rnew.setRotate(gangle, newcenter.x, newcenter.y);
var rnew_inv = rnew.matrix.inverse(),
m_inv = m.inverse(),
extrat = svgedit.math.matrixMultiply(m_inv, rnew_inv, rold, m);
tx = extrat.e;
ty = extrat.f;
if (tx != 0 || ty != 0) {
// now push this transform down to the children
// we pass the translates down to the individual children
var children = selected.childNodes;
var c = children.length;
while (c--) {
var child = children.item(c);
if (child.nodeType == 1) {
var oldStartTransform = context_.getStartTransform();
context_.setStartTransform(child.getAttribute('transform'));
var childTlist = svgedit.transformlist.getTransformList(child);
var newxlate = svgroot.createSVGTransform();
newxlate.setTranslate(tx, ty);
if (childTlist.numberOfItems) {
childTlist.insertItemBefore(newxlate, 0);
} else {
childTlist.appendItem(newxlate);
}
batchCmd.addSubCommand( svgedit.recalculate.recalculateDimensions(child) );
context_.setStartTransform(oldStartTransform);
}
}
}
if (gangle) {
if (tlist.numberOfItems) {
tlist.insertItemBefore(rnew, 0);
} else {
tlist.appendItem(rnew);
}
}
}
}
// else, it's a non-group
else {
// FIXME: box might be null for some elements (<metadata> etc), need to handle this
var box = svgedit.utilities.getBBox(selected);
// Paths (and possbly other shapes) will have no BBox while still in <defs>,
// but we still may need to recalculate them (see issue 595).
// TODO: Figure out how to get BBox from these elements in case they
// have a rotation transform
if (!box && selected.tagName != 'path') return null;
var m = svgroot.createSVGMatrix(),
// temporarily strip off the rotate and save the old center
angle = svgedit.utilities.getRotationAngle(selected);
if (angle) {
var oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
newcenter = svgedit.math.transformPoint(box.x+box.width/2, box.y+box.height/2,
svgedit.math.transformListToTransform(tlist).matrix);
var a = angle * Math.PI / 180;
if ( Math.abs(a) > (1.0e-10) ) {
var s = Math.sin(a)/(1 - Math.cos(a));
} else {
// FIXME: This blows up if the angle is exactly 0!
var s = 2/a;
}
for (var i = 0; i < tlist.numberOfItems; ++i) {
var xform = tlist.getItem(i);
if (xform.type == 4) {
// extract old center through mystical arts
var rm = xform.matrix;
oldcenter.y = (s*rm.e + rm.f)/2;
oldcenter.x = (rm.e - s*rm.f)/2;
tlist.removeItem(i);
break;
}
}
}
// 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition
var operation = 0;
var N = tlist.numberOfItems;
// Check if it has a gradient with userSpaceOnUse, in which case
// adjust it by recalculating the matrix transform.
// TODO: Make this work in Webkit using svgedit.transformlist.SVGTransformList
if (!svgedit.browser.isWebkit()) {
var fill = selected.getAttribute('fill');
if (fill && fill.indexOf('url(') === 0) {
var paint = getRefElem(fill);
var type = 'pattern';
if (paint.tagName !== type) type = 'gradient';
var attrVal = paint.getAttribute(type + 'Units');
if (attrVal === 'userSpaceOnUse') {
//Update the userSpaceOnUse element
m = svgedit.math.transformListToTransform(tlist).matrix;
var gtlist = svgedit.transformlist.getTransformList(paint);
var gmatrix = svgedit.math.transformListToTransform(gtlist).matrix;
m = svgedit.math.matrixMultiply(m, gmatrix);
var m_str = 'matrix(' + [m.a, m.b, m.c, m.d, m.e, m.f].join(',') + ')';
paint.setAttribute(type + 'Transform', m_str);
}
}
}
// first, if it was a scale of a non-skewed element, then the second-last
// transform will be the [S]
// if we had [M][T][S][T] we want to extract the matrix equivalent of
// [T][S][T] and push it down to the element
if (N >= 3 && tlist.getItem(N-2).type == 3 &&
tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
// Removed this so a <use> with a given [T][S][T] would convert to a matrix.
// Is that bad?
// && selected.nodeName != 'use'
{
operation = 3; // scale
m = svgedit.math.transformListToTransform(tlist, N-3, N-1).matrix;
tlist.removeItem(N-1);
tlist.removeItem(N-2);
tlist.removeItem(N-3);
} // if we had [T][S][-T][M], then this was a skewed element being resized
// Thus, we simply combine it all into one matrix
else if (N == 4 && tlist.getItem(N-1).type == 1) {
operation = 3; // scale
m = svgedit.math.transformListToTransform(tlist).matrix;
var e2t = svgroot.createSVGTransform();
e2t.setMatrix(m);
tlist.clear();
tlist.appendItem(e2t);
// reset the matrix so that the element is not re-mapped
m = svgroot.createSVGMatrix();
} // if we had [R][T][S][-T][M], then this was a rotated matrix-element
// if we had [T1][M] we want to transform this into [M][T2]
// therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2]
// down to the element
else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
tlist.getItem(0).type == 2)
{
operation = 2; // translate
var oldxlate = tlist.getItem(0).matrix,
meq = svgedit.math.transformListToTransform(tlist,1).matrix,
meq_inv = meq.inverse();
m = svgedit.math.matrixMultiply( meq_inv, oldxlate, meq );
tlist.removeItem(0);
}
// else if this child now has a matrix imposition (from a parent group)
// we might be able to simplify
else if (N == 1 && tlist.getItem(0).type == 1 && !angle) {
// Remap all point-based elements
m = svgedit.math.transformListToTransform(tlist).matrix;
switch (selected.tagName) {
case 'line':
changes = $(selected).attr(['x1', 'y1', 'x2', 'y2']);
case 'polyline':
case 'polygon':
changes.points = selected.getAttribute('points');
if (changes.points) {
var list = selected.points;
var len = list.numberOfItems;
changes.points = new Array(len);
for (var i = 0; i < len; ++i) {
var pt = list.getItem(i);
changes.points[i] = {x:pt.x, y:pt.y};
}
}
case 'path':
changes.d = selected.getAttribute('d');
operation = 1;
tlist.clear();
break;
default:
break;
}
}
// if it was a rotation, put the rotate back and return without a command
// (this function has zero work to do for a rotate())
else {
operation = 4; // rotation
if (angle) {
var newRot = svgroot.createSVGTransform();
newRot.setRotate(angle, newcenter.x, newcenter.y);
if (tlist.numberOfItems) {
tlist.insertItemBefore(newRot, 0);
} else {
tlist.appendItem(newRot);
}
}
if (tlist.numberOfItems == 0) {
selected.removeAttribute('transform');
}
return null;
}
// if it was a translate or resize, we need to remap the element and absorb the xform
if (operation == 1 || operation == 2 || operation == 3) {
svgedit.coords.remapElement(selected, changes, m);
} // if we are remapping
// if it was a translate, put back the rotate at the new center
if (operation == 2) {
if (angle) {
if (!svgedit.math.hasMatrixTransform(tlist)) {
newcenter = {
x: oldcenter.x + m.e,
y: oldcenter.y + m.f
};
}
var newRot = svgroot.createSVGTransform();
newRot.setRotate(angle, newcenter.x, newcenter.y);
if (tlist.numberOfItems) {
tlist.insertItemBefore(newRot, 0);
} else {
tlist.appendItem(newRot);
}
}
// We have special processing for tspans: Tspans are not transformable
// but they can have x,y coordinates (sigh). Thus, if this was a translate,
// on a text element, also translate any tspan children.
if (selected.tagName == 'text') {
var children = selected.childNodes;
var c = children.length;
while (c--) {
var child = children.item(c);
if (child.tagName == 'tspan') {
var tspanChanges = {
x: $(child).attr('x') || 0,
y: $(child).attr('y') || 0
};
svgedit.coords.remapElement(child, tspanChanges, m);
}
}
}
}
// [Rold][M][T][S][-T] became [Rold][M]
// we want it to be [Rnew][M][Tr] where Tr is the
// translation required to re-center it
// Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M]
else if (operation == 3 && angle) {
var m = svgedit.math.transformListToTransform(tlist).matrix;
var roldt = svgroot.createSVGTransform();
roldt.setRotate(angle, oldcenter.x, oldcenter.y);
var rold = roldt.matrix;
var rnew = svgroot.createSVGTransform();
rnew.setRotate(angle, newcenter.x, newcenter.y);
var rnew_inv = rnew.matrix.inverse();
var m_inv = m.inverse();
var extrat = svgedit.math.matrixMultiply(m_inv, rnew_inv, rold, m);
svgedit.coords.remapElement(selected, changes, extrat);
if (angle) {
if (tlist.numberOfItems) {
tlist.insertItemBefore(rnew, 0);
} else {
tlist.appendItem(rnew);
}
}
}
} // a non-group
// if the transform list has been emptied, remove it
if (tlist.numberOfItems == 0) {
selected.removeAttribute('transform');
}
batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(selected, initial));
return batchCmd;
};
})();
|
ej.addCulture("et",{name:"et",englishName:"Estonian",nativeName:"eesti",language:"et",numberFormat:{",":" ",".":",",NaN:"avaldamatu",negativeInfinity:"miinuslõpmatus",positiveInfinity:"plusslõpmatus",percent:{pattern:["-n%","n%"],",":" ",".":","},currency:{pattern:["-n $","n $"],",":" ",symbol:"€"}},calendars:{standard:{"/":".",firstDay:1,days:{names:["pühapäev","esmaspäev","teisipäev","kolmapäev","neljapäev","reede","laupäev"],namesAbbr:["P","E","T","K","N","R","L"],namesShort:["P","E","T","K","N","R","L"]},months:{names:["jaanuar","veebruar","märts","aprill","mai","juuni","juuli","august","september","oktoober","november","detsember",""],namesAbbr:["jaan","veebr","märts","apr","mai","juuni","juuli","aug","sept","okt","nov","dets",""]},AM:["EL","el","EL"],PM:["PL","pl","PL"],patterns:{d:"d.MM.yyyy",D:"d. MMMM yyyy",t:"H:mm",T:"H:mm:ss",f:"d. MMMM yyyy H:mm",F:"d. MMMM yyyy H:mm:ss",M:"dd. MMMM"}}}}); |
define(function(require) {
var test = require('../../test')
var assert = test.assert
// var BASE_RE = /^(.+?\/)(\?\?)?(seajs\/)+/
assert('http://test.com/seajs/sea.js'.match(BASE_RE)[1] === 'http://test.com/', 'BASE_RE')
assert('http://test.com/seajs/2.1.0/sea.js'.match(BASE_RE)[1] === 'http://test.com/', 'BASE_RE')
assert('http://test.com/seajs/seajs/2.1.0/sea.js'.match(BASE_RE)[1] === 'http://test.com/', 'BASE_RE')
assert('http://test.com/??seajs/seajs/2.1.0/sea.js,jquery/jquery/1.9.2/jquery.js'.match(BASE_RE)[1] === 'http://test.com/', 'BASE_RE')
assert('http://test.com/seajs/??seajs/2.1.0/sea.js,seajs-combo/1.0.0/seajs-combo.js'.match(BASE_RE)[1] === 'http://test.com/', 'BASE_RE')
assert('http://test.com/libs/??seajs/seajs/2.1.0/sea.js,jquery/jquery/1.9.2/jquery.js'.match(BASE_RE)[1] === 'http://test.com/libs/', 'BASE_RE')
test.next()
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ModuleDependency = require("./ModuleDependency");
var Template = require("../Template");
function LabeledModuleDependency(request, range) {
ModuleDependency.call(this, request);
this.Class = LabeledModuleDependency;
this.range = range;
}
module.exports = LabeledModuleDependency;
LabeledModuleDependency.prototype = Object.create(ModuleDependency.prototype);
LabeledModuleDependency.prototype.constructor = LabeledModuleDependency;
LabeledModuleDependency.prototype.type = "labeled require";
LabeledModuleDependency.Template = function LabeledModuleDependencyTemplate() {};
LabeledModuleDependency.Template.prototype.apply = function(dep, source, outputOptions, requestShortener) {
var comment = "",
content;
if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ ";
if(dep.module && dep.module.meta && dep.module.meta.exports) {
content = "var __WEBPACK_LABELED_MODULE__" + Template.toIdentifier(dep.module.id) + " = __webpack_require__(" + comment + JSON.stringify(dep.module.id) + ")";
dep.module.meta.exports.forEach(function(e) {
content += ", " + e + " = __WEBPACK_LABELED_MODULE__" + Template.toIdentifier(dep.module.id) + "." + e;
});
content += ";";
} else if(dep.module) {
content = require("./WebpackMissingModule").moduleMetaInfo(dep.request);
} else {
content = require("./WebpackMissingModule").module(dep.request);
}
source.replace(dep.range[0], dep.range[1] - 1, content);
};
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.async = global.async || {})));
}(this, function (exports) { 'use strict';
/**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/
function apply(func, thisArg, args) {
var length = args.length;
switch (length) {
case 0: return func.call(thisArg);
case 1: return func.call(thisArg, args[0]);
case 2: return func.call(thisArg, args[0], args[1]);
case 3: return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/6.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
var funcTag = '[object Function]';
var genTag = '[object GeneratorFunction]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8 which returns 'object' for typed array and weak map constructors,
// and PhantomJS 1.9 which returns 'function' for `NodeList` instances.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used for built-in method references. */
var objectProto$1 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString$1 = objectProto$1.toString;
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && objectToString$1.call(value) == symbolTag);
}
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/
function toNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
if (isObject(value)) {
var other = isFunction(value.valueOf) ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = value.replace(reTrim, '');
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
var INFINITY = 1 / 0;
var MAX_INTEGER = 1.7976931348623157e+308;
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber(value);
if (value === INFINITY || value === -INFINITY) {
var sign = (value < 0 ? -1 : 1);
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This function is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/
function toInteger(value) {
var result = toFinite(value),
remainder = result % 1;
return result === result ? (remainder ? result - remainder : result) : 0;
}
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function rest(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : toInteger(start), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, array);
case 1: return func.call(this, args[0], array);
case 2: return func.call(this, args[0], args[1], array);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = array;
return apply(func, this, otherArgs);
};
}
function initialParams (fn) {
return rest(function (args /*..., callback*/) {
var callback = args.pop();
fn.call(this, args, callback);
});
}
function applyEach$1(eachfn) {
return rest(function (fns, args) {
var go = initialParams(function (args, callback) {
var that = this;
return eachfn(fns, function (fn, cb) {
fn.apply(that, args.concat([cb]));
}, callback);
});
if (args.length) {
return go.apply(this, args);
} else {
return go;
}
});
}
/**
* A no-operation function that returns `undefined` regardless of the
* arguments it receives.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* var object = { 'user': 'fred' };
*
* _.noop(object) === undefined;
* // => true
*/
function noop() {
// No operation performed.
}
function once(fn) {
return function () {
if (fn === null) return;
var callFn = fn;
fn = null;
callFn.apply(this, arguments);
};
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a
* [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) that affects
* Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length,
* else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value)) && !isFunction(value);
}
var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
function getIterator (coll) {
return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol]();
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeGetPrototype = Object.getPrototypeOf;
/**
* Gets the `[[Prototype]]` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {null|Object} Returns the `[[Prototype]]`.
*/
function getPrototype(value) {
return nativeGetPrototype(Object(value));
}
/** Used for built-in method references. */
var objectProto$2 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto$2.hasOwnProperty;
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHas(object, key) {
// Avoid a bug in IE 10-11 where objects with a [[Prototype]] of `null`,
// that are composed entirely of index properties, return `false` for
// `hasOwnProperty` checks of them.
return hasOwnProperty.call(object, key) ||
(typeof object == 'object' && key in object && getPrototype(object) === null);
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = Object.keys;
/**
* The base implementation of `_.keys` which doesn't skip the constructor
* property of prototypes or treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
return nativeKeys(Object(object));
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/
function baseTimes(n, iteratee) {
var index = -1,
result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/** Used for built-in method references. */
var objectProto$3 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$1 = objectProto$3.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString$2 = objectProto$3.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto$3.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 incorrectly makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty$1.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString$2.call(value) == argsTag);
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @type {Function}
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for built-in method references. */
var objectProto$4 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString$3 = objectProto$4.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && objectToString$3.call(value) == stringTag);
}
/**
* Creates an array of index keys for `object` values of arrays,
* `arguments` objects, and strings, otherwise `null` is returned.
*
* @private
* @param {Object} object The object to query.
* @returns {Array|null} Returns index keys, else `null`.
*/
function indexKeys(object) {
var length = object ? object.length : undefined;
if (isLength(length) &&
(isArray(object) || isString(object) || isArguments(object))) {
return baseTimes(length, String);
}
return null;
}
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER$1 = 9007199254740991;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
length = length == null ? MAX_SAFE_INTEGER$1 : length;
return !!length &&
(typeof value == 'number' || reIsUint.test(value)) &&
(value > -1 && value % 1 == 0 && value < length);
}
/** Used for built-in method references. */
var objectProto$5 = Object.prototype;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/
function isPrototype(value) {
var Ctor = value && value.constructor,
proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5;
return value === proto;
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
function keys(object) {
var isProto = isPrototype(object);
if (!(isProto || isArrayLike(object))) {
return baseKeys(object);
}
var indexes = indexKeys(object),
skipIndexes = !!indexes,
result = indexes || [],
length = result.length;
for (var key in object) {
if (baseHas(object, key) &&
!(skipIndexes && (key == 'length' || isIndex(key, length))) &&
!(isProto && key == 'constructor')) {
result.push(key);
}
}
return result;
}
function iterator(coll) {
var i = -1;
var len;
if (isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? { value: coll[i], key: i } : null;
};
}
var iterate = getIterator(coll);
if (iterate) {
return function next() {
var item = iterate.next();
if (item.done) return null;
i++;
return { value: item.value, key: i };
};
}
var okeys = keys(coll);
len = okeys.length;
return function next() {
i++;
var key = okeys[i];
return i < len ? { value: coll[key], key: key } : null;
};
}
function onlyOnce(fn) {
return function () {
if (fn === null) throw new Error("Callback was already called.");
var callFn = fn;
fn = null;
callFn.apply(this, arguments);
};
}
function _eachOfLimit(limit) {
return function (obj, iteratee, callback) {
callback = once(callback || noop);
obj = obj || [];
var nextElem = iterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish() {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var elem = nextElem();
if (elem === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iteratee(elem.value, elem.key, onlyOnce(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
} else {
replenish();
}
}));
}
})();
};
}
function doParallelLimit(fn) {
return function (obj, limit, iteratee, callback) {
return fn(_eachOfLimit(limit), obj, iteratee, callback);
};
}
function _asyncMap(eachfn, arr, iteratee, callback) {
callback = once(callback || noop);
arr = arr || [];
var results = isArrayLike(arr) || getIterator(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iteratee(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
/**
* The same as `map` but runs a maximum of `limit` async operations at a time.
*
* @name mapLimit
* @static
* @memberOf async
* @see async.map
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A function to apply to each item in `coll`.
* The iteratee is passed a `callback(err, transformed)` which must be called
* once it has completed with an error (which can be `null`) and a transformed
* item. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. Results is an array of the
* transformed items from the `coll`. Invoked with (err, results).
*/
var mapLimit = doParallelLimit(_asyncMap);
function doLimit(fn, limit) {
return function (iterable, iteratee, callback) {
return fn(iterable, limit, iteratee, callback);
};
}
/**
* Produces a new collection of values by mapping each value in `coll` through
* the `iteratee` function. The `iteratee` is called with an item from `coll`
* and a callback for when it has finished processing. Each of these callback
* takes 2 arguments: an `error`, and the transformed item from `coll`. If
* `iteratee` passes an error to its callback, the main `callback` (for the
* `map` function) is immediately called with the error.
*
* Note, that since this function applies the `iteratee` to each item in
* parallel, there is no guarantee that the `iteratee` functions will complete
* in order. However, the results array will be in the same order as the
* original `coll`.
*
* @name map
* @static
* @memberOf async
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item in `coll`.
* The iteratee is passed a `callback(err, transformed)` which must be called
* once it has completed with an error (which can be `null`) and a
* transformed item. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. Results is an array of the
* transformed items from the `coll`. Invoked with (err, results).
* @example
*
* async.map(['file1','file2','file3'], fs.stat, function(err, results) {
* // results is now an array of stats for each file
* });
*/
var map = doLimit(mapLimit, Infinity);
/**
* Applies the provided arguments to each function in the array, calling
* `callback` after all functions have completed. If you only provide the first
* argument, then it will return a function which lets you pass in the
* arguments as if it were a single function call.
*
* @name applyEach
* @static
* @memberOf async
* @category Control Flow
* @param {Array|Object} fns - A collection of asynchronous functions to all
* call with the same arguments
* @param {...*} [args] - any number of separate arguments to pass to the
* function.
* @param {Function} [callback] - the final argument should be the callback,
* called when all functions have completed processing.
* @returns {Function} - If only the first argument is provided, it will return
* a function which lets you pass in the arguments as if it were a single
* function call.
* @example
*
* async.applyEach([enableSearch, updateSchema], 'bucket', callback);
*
* // partial application example:
* async.each(
* buckets,
* async.applyEach([enableSearch, updateSchema]),
* callback
* );
*/
var applyEach = applyEach$1(map);
/**
* The same as `map` but runs only a single async operation at a time.
*
* @name mapSeries
* @static
* @memberOf async
* @see async.map
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item in `coll`.
* The iteratee is passed a `callback(err, transformed)` which must be called
* once it has completed with an error (which can be `null`) and a
* transformed item. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. Results is an array of the
* transformed items from the `coll`. Invoked with (err, results).
*/
var mapSeries = doLimit(mapLimit, 1);
/**
* The same as `applyEach` but runs only a single async operation at a time.
*
* @name applyEachSeries
* @static
* @memberOf async
* @see async.applyEach
* @category Control Flow
* @param {Array|Object} fns - A collection of asynchronous functions to all
* call with the same arguments
* @param {...*} [args] - any number of separate arguments to pass to the
* function.
* @param {Function} [callback] - the final argument should be the callback,
* called when all functions have completed processing.
* @returns {Function} - If only the first argument is provided, it will return
* a function which lets you pass in the arguments as if it were a single
* function call.
*/
var applyEachSeries = applyEach$1(mapSeries);
/**
* Creates a continuation function with some arguments already applied.
*
* Useful as a shorthand when combined with other control flow functions. Any
* arguments passed to the returned function are added to the arguments
* originally passed to apply.
*
* @name apply
* @static
* @memberOf async
* @category Util
* @param {Function} function - The function you want to eventually apply all
* arguments to. Invokes with (arguments...).
* @param {...*} arguments... - Any number of arguments to automatically apply
* when the continuation is called.
* @example
*
* // using apply
* async.parallel([
* async.apply(fs.writeFile, 'testfile1', 'test1'),
* async.apply(fs.writeFile, 'testfile2', 'test2')
* ]);
*
*
* // the same process without using apply
* async.parallel([
* function(callback) {
* fs.writeFile('testfile1', 'test1', callback);
* },
* function(callback) {
* fs.writeFile('testfile2', 'test2', callback);
* }
* ]);
*
* // It's possible to pass any number of additional arguments when calling the
* // continuation:
*
* node> var fn = async.apply(sys.puts, 'one');
* node> fn('two', 'three');
* one
* two
* three
*/
var apply$1 = rest(function (fn, args) {
return rest(function (callArgs) {
return fn.apply(null, args.concat(callArgs));
});
});
/**
* Take a sync function and make it async, passing its return value to a
* callback. This is useful for plugging sync functions into a waterfall,
* series, or other async functions. Any arguments passed to the generated
* function will be passed to the wrapped function (except for the final
* callback argument). Errors thrown will be passed to the callback.
*
* If the function passed to `asyncify` returns a Promise, that promises's
* resolved/rejected state will be used to call the callback, rather than simply
* the synchronous return value.
*
* This also means you can asyncify ES2016 `async` functions.
*
* @name asyncify
* @static
* @memberOf async
* @alias wrapSync
* @category Util
* @param {Function} func - The synchronous function to convert to an
* asynchronous function.
* @returns {Function} An asynchronous wrapper of the `func`. To be invoked with
* (callback).
* @example
*
* // passing a regular synchronous function
* async.waterfall([
* async.apply(fs.readFile, filename, "utf8"),
* async.asyncify(JSON.parse),
* function (data, next) {
* // data is the result of parsing the text.
* // If there was a parsing error, it would have been caught.
* }
* ], callback);
*
* // passing a function returning a promise
* async.waterfall([
* async.apply(fs.readFile, filename, "utf8"),
* async.asyncify(function (contents) {
* return db.model.create(contents);
* }),
* function (model, next) {
* // `model` is the instantiated model object.
* // If there was an error, this function would be skipped.
* }
* ], callback);
*
* // es6 example
* var q = async.queue(async.asyncify(async function(file) {
* var intermediateStep = await processFile(file);
* return await somePromise(intermediateStep)
* }));
*
* q.push(files);
*/
function asyncify(func) {
return initialParams(function (args, callback) {
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (isObject(result) && typeof result.then === 'function') {
result.then(function (value) {
callback(null, value);
})['catch'](function (err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1,
iterable = Object(object),
props = keysFunc(object),
length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'user': 'fred' };
* var other = { 'user': 'fred' };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/
function eq(value, other) {
return value === other || (value !== value && other !== other);
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to search.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq(array[length][0], key)) {
return length;
}
}
return -1;
}
/** Used for built-in method references. */
var arrayProto = Array.prototype;
/** Built-in value references. */
var splice = arrayProto.splice;
/**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function listCacheDelete(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
return true;
}
/**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function listCacheGet(key) {
var data = this.__data__,
index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}
/**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function listCacheHas(key) {
return assocIndexOf(this.__data__, key) > -1;
}
/**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/
function listCacheSet(key, value) {
var data = this.__data__,
index = assocIndexOf(data, key);
if (index < 0) {
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
}
/**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function stackDelete(key) {
return this.__data__['delete'](key);
}
/**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function stackGet(key) {
return this.__data__.get(key);
}
/**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function stackHas(key) {
return this.__data__.has(key);
}
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
function isHostObject(value) {
// Many host objects are `Object` objects that can coerce to strings
// despite having improperly defined `toString` methods.
var result = false;
if (value != null && typeof value.toString != 'function') {
try {
result = !!(value + '');
} catch (e) {}
}
return result;
}
/** Used to resolve the decompiled source of functions. */
var funcToString$1 = Function.prototype.toString;
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to process.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString$1.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
/** Used to detect host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for built-in method references. */
var objectProto$6 = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var funcToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty$2 = objectProto$6.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty$2).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (!isObject(value)) {
return false;
}
var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object[key];
return isNative(value) ? value : undefined;
}
/* Built-in method references that are verified to be native. */
var nativeCreate = getNative(Object, 'create');
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
}
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
return this.has(key) && delete this.__data__[key];
}
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used for built-in method references. */
var objectProto$7 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$3 = objectProto$7.hasOwnProperty;
/**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function hashGet(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty$3.call(data, key) ? data[key] : undefined;
}
/** Used for built-in method references. */
var objectProto$8 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$4 = objectProto$8.hasOwnProperty;
/**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function hashHas(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty$4.call(data, key);
}
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
/**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/
function hashSet(key, value) {
var data = this.__data__;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
return this;
}
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/**
* Checks if `value` is a global object.
*
* @private
* @param {*} value The value to check.
* @returns {null|Object} Returns `value` if it's a global object, else `null`.
*/
function checkGlobal(value) {
return (value && value.Object === Object) ? value : null;
}
/** Used to determine if values are of the language type `Object`. */
var objectTypes = {
'function': true,
'object': true
};
/** Detect free variable `exports`. */
var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType)
? exports
: undefined;
/** Detect free variable `module`. */
var freeModule = (objectTypes[typeof module] && module && !module.nodeType)
? module
: undefined;
/** Detect free variable `global` from Node.js. */
var freeGlobal = checkGlobal(freeExports && freeModule && typeof global == 'object' && global);
/** Detect free variable `self`. */
var freeSelf = checkGlobal(objectTypes[typeof self] && self);
/** Detect free variable `window`. */
var freeWindow = checkGlobal(objectTypes[typeof window] && window);
/** Detect `this` as the global object. */
var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
/**
* Used as a reference to the global object.
*
* The `this` value is used if it's the global object to avoid Greasemonkey's
* restricted `window` object, otherwise the `window` object is used.
*/
var root = freeGlobal ||
((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) ||
freeSelf || thisGlobal || Function('return this')();
/* Built-in method references that are verified to be native. */
var Map = getNative(root, 'Map');
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* Checks if `value` is suitable for use as unique object key.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is suitable, else `false`.
*/
function isKeyable(value) {
var type = typeof value;
return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
? (value !== '__proto__')
: (value === null);
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/
function getMapData(map, key) {
var data = map.__data__;
return isKeyable(key)
? data[typeof key == 'string' ? 'string' : 'hash']
: data.map;
}
/**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function mapCacheDelete(key) {
return getMapData(this, key)['delete'](key);
}
/**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/
function mapCacheGet(key) {
return getMapData(this, key).get(key);
}
/**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function mapCacheHas(key) {
return getMapData(this, key).has(key);
}
/**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/
function mapCacheSet(key, value) {
getMapData(this, key).set(key, value);
return this;
}
/**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function MapCache(entries) {
var index = -1,
length = entries ? entries.length : 0;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/
function stackSet(key, value) {
var cache = this.__data__;
if (cache instanceof ListCache && cache.__data__.length == LARGE_ARRAY_SIZE) {
cache = this.__data__ = new MapCache(cache.__data__);
}
cache.set(key, value);
return this;
}
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
this.__data__ = new ListCache(entries);
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
/**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED$2);
return this;
}
/**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/
function setCacheHas(value) {
return this.__data__.has(value);
}
/**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/
function SetCache(values) {
var index = -1,
length = values ? values.length : 0;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
var UNORDERED_COMPARE_FLAG$1 = 1;
var PARTIAL_COMPARE_FLAG$2 = 2;
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG$2,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(array);
if (stacked) {
return stacked == other;
}
var index = -1,
result = true,
seen = (bitmask & UNORDERED_COMPARE_FLAG$1) ? new SetCache : undefined;
stack.set(array, other);
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index];
if (customizer) {
var compared = isPartial
? customizer(othValue, arrValue, index, other, array, stack)
: customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== undefined) {
if (compared) {
continue;
}
result = false;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!seen.has(othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
return seen.add(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, customizer, bitmask, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
return result;
}
/** Built-in value references. */
var Symbol$1 = root.Symbol;
/** Built-in value references. */
var Uint8Array = root.Uint8Array;
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/
function mapToArray(map) {
var index = -1,
result = Array(map.size);
map.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/
function setToArray(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
var UNORDERED_COMPARE_FLAG$2 = 1;
var PARTIAL_COMPARE_FLAG$3 = 2;
var boolTag = '[object Boolean]';
var dateTag = '[object Date]';
var errorTag = '[object Error]';
var mapTag = '[object Map]';
var numberTag = '[object Number]';
var regexpTag = '[object RegExp]';
var setTag = '[object Set]';
var stringTag$1 = '[object String]';
var symbolTag$1 = '[object Symbol]';
var arrayBufferTag = '[object ArrayBuffer]';
var dataViewTag = '[object DataView]';
var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined;
var symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
switch (tag) {
case dataViewTag:
if ((object.byteLength != other.byteLength) ||
(object.byteOffset != other.byteOffset)) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag:
if ((object.byteLength != other.byteLength) ||
!equalFunc(new Uint8Array(object), new Uint8Array(other))) {
return false;
}
return true;
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and
// booleans to `1` or `0` treating invalid dates coerced to `NaN` as
// not equal.
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object) ? other != +other : object == +other;
case regexpTag:
case stringTag$1:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/6.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & PARTIAL_COMPARE_FLAG$3;
convert || (convert = setToArray);
if (object.size != other.size && !isPartial) {
return false;
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= UNORDERED_COMPARE_FLAG$2;
stack.set(object, other);
// Recursively compare objects (susceptible to call stack limits).
return equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
case symbolTag$1:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/** Used to compose bitmasks for comparison styles. */
var PARTIAL_COMPARE_FLAG$4 = 2;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} customizer The function to customize comparisons.
* @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
var isPartial = bitmask & PARTIAL_COMPARE_FLAG$4,
objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : baseHas(other, key))) {
return false;
}
}
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
var result = true;
stack.set(object, other);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key];
if (customizer) {
var compared = isPartial
? customizer(othValue, objValue, key, other, object, stack)
: customizer(objValue, othValue, key, object, other, stack);
}
// Recursively compare objects (susceptible to call stack limits).
if (!(compared === undefined
? (objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack))
: compared
)) {
result = false;
break;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (result && !skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
result = false;
}
}
stack['delete'](object);
return result;
}
/* Built-in method references that are verified to be native. */
var DataView = getNative(root, 'DataView');
/* Built-in method references that are verified to be native. */
var Promise = getNative(root, 'Promise');
/* Built-in method references that are verified to be native. */
var Set = getNative(root, 'Set');
/* Built-in method references that are verified to be native. */
var WeakMap = getNative(root, 'WeakMap');
var mapTag$1 = '[object Map]';
var objectTag$1 = '[object Object]';
var promiseTag = '[object Promise]';
var setTag$1 = '[object Set]';
var weakMapTag = '[object WeakMap]';
var dataViewTag$1 = '[object DataView]';
/** Used for built-in method references. */
var objectProto$10 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString$4 = objectProto$10.toString;
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView);
var mapCtorString = toSource(Map);
var promiseCtorString = toSource(Promise);
var setCtorString = toSource(Set);
var weakMapCtorString = toSource(WeakMap);
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function getTag(value) {
return objectToString$4.call(value);
}
// Fallback for data views, maps, sets, and weak maps in IE 11,
// for data views in Edge, and promises in Node.js.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$1) ||
(Map && getTag(new Map) != mapTag$1) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag$1) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = objectToString$4.call(value),
Ctor = result == objectTag$1 ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : undefined;
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag$1;
case mapCtorString: return mapTag$1;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag$1;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
var getTag$1 = getTag;
var argsTag$2 = '[object Arguments]';
var arrayTag$1 = '[object Array]';
var boolTag$1 = '[object Boolean]';
var dateTag$1 = '[object Date]';
var errorTag$1 = '[object Error]';
var funcTag$1 = '[object Function]';
var mapTag$2 = '[object Map]';
var numberTag$1 = '[object Number]';
var objectTag$2 = '[object Object]';
var regexpTag$1 = '[object RegExp]';
var setTag$2 = '[object Set]';
var stringTag$2 = '[object String]';
var weakMapTag$1 = '[object WeakMap]';
var arrayBufferTag$1 = '[object ArrayBuffer]';
var dataViewTag$2 = '[object DataView]';
var float32Tag = '[object Float32Array]';
var float64Tag = '[object Float64Array]';
var int8Tag = '[object Int8Array]';
var int16Tag = '[object Int16Array]';
var int32Tag = '[object Int32Array]';
var uint8Tag = '[object Uint8Array]';
var uint8ClampedTag = '[object Uint8ClampedArray]';
var uint16Tag = '[object Uint16Array]';
var uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$1] =
typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] =
typedArrayTags[dataViewTag$2] = typedArrayTags[dateTag$1] =
typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] =
typedArrayTags[mapTag$2] = typedArrayTags[numberTag$1] =
typedArrayTags[objectTag$2] = typedArrayTags[regexpTag$1] =
typedArrayTags[setTag$2] = typedArrayTags[stringTag$2] =
typedArrayTags[weakMapTag$1] = false;
/** Used for built-in method references. */
var objectProto$11 = Object.prototype;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString$5 = objectProto$11.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified,
* else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[objectToString$5.call(value)];
}
/** Used to compose bitmasks for comparison styles. */
var PARTIAL_COMPARE_FLAG$1 = 2;
/** `Object#toString` result references. */
var argsTag$1 = '[object Arguments]';
var arrayTag = '[object Array]';
var objectTag = '[object Object]';
/** Used for built-in method references. */
var objectProto$9 = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty$5 = objectProto$9.hasOwnProperty;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparisons.
* @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
* for more details.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = getTag$1(object);
objTag = objTag == argsTag$1 ? objectTag : objTag;
}
if (!othIsArr) {
othTag = getTag$1(other);
othTag = othTag == argsTag$1 ? objectTag : othTag;
}
var objIsObj = objTag == objectTag && !isHostObject(object),
othIsObj = othTag == objectTag && !isHostObject(other),
isSameTag = objTag == othTag;
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, equalFunc, customizer, bitmask, stack)
: equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
}
if (!(bitmask & PARTIAL_COMPARE_FLAG$1)) {
var objIsWrapped = objIsObj && hasOwnProperty$5.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty$5.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object,
othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack);
return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @param {boolean} [bitmask] The bitmask of comparison flags.
* The bitmask may be composed of the following flags:
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, bitmask, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
}
var UNORDERED_COMPARE_FLAG = 1;
var PARTIAL_COMPARE_FLAG = 2;
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var stack = new Stack;
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === undefined
? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/
function arrayMap(array, iteratee) {
var index = -1,
length = array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
* of key-value pairs for `object` corresponding to the property names of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the key-value pairs.
*/
function baseToPairs(object, props) {
return arrayMap(props, function(key) {
return [key, object[key]];
});
}
/**
* Converts `set` to its value-value pairs.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the value-value pairs.
*/
function setToPairs(set) {
var index = -1,
result = Array(set.size);
set.forEach(function(value) {
result[++index] = [value, value];
});
return result;
}
var mapTag$3 = '[object Map]';
var setTag$3 = '[object Set]';
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/
function createToPairs(keysFunc) {
return function(object) {
var tag = getTag$1(object);
if (tag == mapTag$3) {
return mapToArray(object);
}
if (tag == setTag$3) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/
var toPairs = createToPairs(keys);
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = toPairs(object),
length = result.length;
while (length--) {
result[length][2] = isStrictComparable(result[length][1]);
}
return result;
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue &&
(srcValue !== undefined || (key in Object(object)));
};
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT$1 = 'Expected a function';
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
* method interface of `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/
function memoize(func, resolver) {
if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT$1);
}
var memoized = function() {
var args = arguments,
key = resolver ? resolver.apply(this, args) : args[0],
cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result);
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Assign cache to `_.memoize`.
memoize.Cache = MapCache;
/** Used as references for various `Number` constants. */
var INFINITY$1 = 1 / 0;
/** Used to convert symbols to primitives and strings. */
var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined;
var symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if (typeof value == 'string') {
return value;
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {string} Returns the string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoize(function(string) {
var result = [];
toString(string).replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value) {
return isArray(value) ? value : stringToPath(value);
}
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
if (isArray(value)) {
return false;
}
var type = typeof value;
if (type == 'number' || type == 'symbol' || type == 'boolean' ||
value == null || isSymbol(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
(object != null && value in Object(object));
}
/** Used as references for various `Number` constants. */
var INFINITY$2 = 1 / 0;
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/
function toKey(value) {
if (typeof value == 'string' || isSymbol(value)) {
return value;
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY$2) ? '-0' : result;
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path) {
path = isKey(path, object) ? [path] : castPath(path);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is used in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/
function baseHasIn(object, key) {
return key in Object(object);
}
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/
function hasPath(object, path, hasFunc) {
path = isKey(path, object) ? [path] : castPath(path);
var result,
index = -1,
length = path.length;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result) {
return result;
}
var length = object ? object.length : 0;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isString(object) || isArguments(object));
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/
function hasIn(object, path) {
return object != null && hasPath(object, path, baseHasIn);
}
var UNORDERED_COMPARE_FLAG$3 = 1;
var PARTIAL_COMPARE_FLAG$5 = 2;
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/
function baseMatchesProperty(path, srcValue) {
if (isKey(path) && isStrictComparable(srcValue)) {
return matchesStrictComparable(toKey(path), srcValue);
}
return function(object) {
var objValue = get(object, path);
return (objValue === undefined && objValue === srcValue)
? hasIn(object, path)
: baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG$3 | PARTIAL_COMPARE_FLAG$5);
};
}
/**
* This method returns the first argument given to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyDeep(path) {
return function(object) {
return baseGet(object, path);
};
}
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/
function baseIteratee(value) {
// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
if (typeof value == 'function') {
return value;
}
if (value == null) {
return identity;
}
if (typeof value == 'object') {
return isArray(value)
? baseMatchesProperty(value[0], value[1])
: baseMatches(value);
}
return property(value);
}
/**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forOwn(object, iteratee) {
return object && baseForOwn(object, baseIteratee(iteratee, 3));
}
/**
* Gets the index at which the first occurrence of `NaN` is found in `array`.
*
* @private
* @param {Array} array The array to search.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched `NaN`, else `-1`.
*/
function indexOfNaN(array, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 0 : -1);
while ((fromRight ? index-- : ++index < length)) {
var other = array[index];
if (other !== other) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOf(array, value, fromIndex) {
if (value !== value) {
return indexOfNaN(array, fromIndex);
}
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* Determines the best order for running the functions in `tasks`, based on
* their requirements. Each function can optionally depend on other functions
* being completed first, and each function is run as soon as its requirements
* are satisfied.
*
* If any of the functions pass an error to their callback, the `auto` sequence
* will stop. Further tasks will not execute (so any other functions depending
* on it will not run), and the main `callback` is immediately called with the
* error.
*
* Functions also receive an object containing the results of functions which
* have completed so far as the first argument, if they have dependencies. If a
* task function has no dependencies, it will only be passed a callback.
*
* @name auto
* @static
* @memberOf async
* @category Control Flow
* @param {Object} tasks - An object. Each of its properties is either a
* function or an array of requirements, with the function itself the last item
* in the array. The object's key of a property serves as the name of the task
* defined by that property, i.e. can be used when specifying requirements for
* other tasks. The function receives one or two arguments:
* * a `results` object, containing the results of the previously executed
* functions, only passed if the task has any dependencies,
* * a `callback(err, result)` function, which must be called when finished,
* passing an `error` (which can be `null`) and the result of the function's
* execution.
* @param {number} [concurrency=Infinity] - An optional `integer` for
* determining the maximum number of tasks that can be run in parallel. By
* default, as many as possible.
* @param {Function} [callback] - An optional callback which is called when all
* the tasks have been completed. It receives the `err` argument if any `tasks`
* pass an error to their callback. Results are always returned; however, if an
* error occurs, no further `tasks` will be performed, and the results object
* will only contain partial results. Invoked with (err, results).
* @example
*
* async.auto({
* // this function will just be passed a callback
* readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),
* showData: ['readData', function(results, cb) {
* // results.readData is the file's contents
* // ...
* }]
* }, callback);
*
* async.auto({
* get_data: function(callback) {
* console.log('in get_data');
* // async code to get some data
* callback(null, 'data', 'converted to array');
* },
* make_folder: function(callback) {
* console.log('in make_folder');
* // async code to create a directory to store a file in
* // this is run at the same time as getting the data
* callback(null, 'folder');
* },
* write_file: ['get_data', 'make_folder', function(results, callback) {
* console.log('in write_file', JSON.stringify(results));
* // once there is some data and the directory exists,
* // write the data to a file in the directory
* callback(null, 'filename');
* }],
* email_link: ['write_file', function(results, callback) {
* console.log('in email_link', JSON.stringify(results));
* // once the file is written let's email a link to it...
* // results.write_file contains the filename returned by write_file.
* callback(null, {'file':results.write_file, 'email':'user@example.com'});
* }]
* }, function(err, results) {
* console.log('err = ', err);
* console.log('results = ', results);
* });
*/
function auto (tasks, concurrency, callback) {
if (typeof concurrency === 'function') {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = once(callback || noop);
var keys$$ = keys(tasks);
var numTasks = keys$$.length;
if (!numTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = numTasks;
}
var results = {};
var runningTasks = 0;
var hasError = false;
var listeners = {};
var readyTasks = [];
// for cycle detection:
var readyToCheck = []; // tasks that have been identified as reachable
// without the possibility of returning to an ancestor task
var uncheckedDependencies = {};
forOwn(tasks, function (task, key) {
if (!isArray(task)) {
// no dependencies
enqueueTask(key, [task]);
readyToCheck.push(key);
return;
}
var dependencies = task.slice(0, task.length - 1);
var remainingDependencies = dependencies.length;
if (remainingDependencies === 0) {
enqueueTask(key, task);
readyToCheck.push(key);
return;
}
uncheckedDependencies[key] = remainingDependencies;
arrayEach(dependencies, function (dependencyName) {
if (!tasks[dependencyName]) {
throw new Error('async.auto task `' + key + '` has a non-existent dependency in ' + dependencies.join(', '));
}
addListener(dependencyName, function () {
remainingDependencies--;
if (remainingDependencies === 0) {
enqueueTask(key, task);
}
});
});
});
checkForDeadlocks();
processQueue();
function enqueueTask(key, task) {
readyTasks.push(function () {
runTask(key, task);
});
}
function processQueue() {
if (readyTasks.length === 0 && runningTasks === 0) {
return callback(null, results);
}
while (readyTasks.length && runningTasks < concurrency) {
var run = readyTasks.shift();
run();
}
}
function addListener(taskName, fn) {
var taskListeners = listeners[taskName];
if (!taskListeners) {
taskListeners = listeners[taskName] = [];
}
taskListeners.push(fn);
}
function taskComplete(taskName) {
var taskListeners = listeners[taskName] || [];
arrayEach(taskListeners, function (fn) {
fn();
});
processQueue();
}
function runTask(key, task) {
if (hasError) return;
var taskCallback = onlyOnce(rest(function (err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
forOwn(results, function (val, rkey) {
safeResults[rkey] = val;
});
safeResults[key] = args;
hasError = true;
listeners = [];
callback(err, safeResults);
} else {
results[key] = args;
taskComplete(key);
}
}));
runningTasks++;
var taskFn = task[task.length - 1];
if (task.length > 1) {
taskFn(results, taskCallback);
} else {
taskFn(taskCallback);
}
}
function checkForDeadlocks() {
// Kahn's algorithm
// https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm
// http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html
var currentTask;
var counter = 0;
while (readyToCheck.length) {
currentTask = readyToCheck.pop();
counter++;
arrayEach(getDependents(currentTask), function (dependent) {
if (! --uncheckedDependencies[dependent]) {
readyToCheck.push(dependent);
}
});
}
if (counter !== numTasks) {
throw new Error('async.auto cannot execute tasks due to a recursive dependency');
}
}
function getDependents(taskName) {
var result = [];
forOwn(tasks, function (task, key) {
if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) {
result.push(key);
}
});
return result;
}
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function copyArray(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/
function castSlice(array, start, end) {
var length = array.length;
end = end === undefined ? length : end;
return (!start && end >= length) ? array : baseSlice(array, start, end);
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/
function charsEndIndex(strSymbols, chrSymbols) {
var index = strSymbols.length;
while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/
function charsStartIndex(strSymbols, chrSymbols) {
var index = -1,
length = strSymbols.length;
while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
return index;
}
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff';
var rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23';
var rsComboSymbolsRange = '\\u20d0-\\u20f0';
var rsVarRange = '\\ufe0e\\ufe0f';
var rsAstral = '[' + rsAstralRange + ']';
var rsCombo = '[' + rsComboMarksRange + rsComboSymbolsRange + ']';
var rsFitz = '\\ud83c[\\udffb-\\udfff]';
var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')';
var rsNonAstral = '[^' + rsAstralRange + ']';
var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}';
var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]';
var rsZWJ = '\\u200d';
var reOptMod = rsModifier + '?';
var rsOptVar = '[' + rsVarRange + ']?';
var rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*';
var rsSeq = rsOptVar + reOptMod + rsOptJoin;
var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reComplexSymbol = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return string.match(reComplexSymbol);
}
/** Used to match leading and trailing whitespace. */
var reTrim$1 = /^\s+|\s+$/g;
/**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/
function trim(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrim$1, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
chrSymbols = stringToArray(chars),
start = charsStartIndex(strSymbols, chrSymbols),
end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}
var argsRegex = /^(function[^\(]*)?\(?\s*([^\)=]*)/m;
function parseParams(func) {
return trim(func.toString().match(argsRegex)[2]).split(/\s*\,\s*/);
}
/**
* A dependency-injected version of the {@link async.auto} function. Dependent
* tasks are specified as parameters to the function, after the usual callback
* parameter, with the parameter names matching the names of the tasks it
* depends on. This can provide even more readable task graphs which can be
* easier to maintain.
*
* If a final callback is specified, the task results are similarly injected,
* specified as named parameters after the initial error parameter.
*
* The autoInject function is purely syntactic sugar and its semantics are
* otherwise equivalent to {@link async.auto}.
*
* @name autoInject
* @static
* @memberOf async
* @see async.auto
* @category Control Flow
* @param {Object} tasks - An object, each of whose properties is a function of
* the form 'func([dependencies...], callback). The object's key of a property
* serves as the name of the task defined by that property, i.e. can be used
* when specifying requirements for other tasks.
* * The `callback` parameter is a `callback(err, result)` which must be called
* when finished, passing an `error` (which can be `null`) and the result of
* the function's execution. The remaining parameters name other tasks on
* which the task is dependent, and the results from those tasks are the
* arguments of those parameters.
* @param {Function} [callback] - An optional callback which is called when all
* the tasks have been completed. It receives the `err` argument if any `tasks`
* pass an error to their callback. The remaining parameters are task names
* whose results you are interested in. This callback will only be called when
* all tasks have finished or an error has occurred, and so do not specify
* dependencies in the same way as `tasks` do. If an error occurs, no further
* `tasks` will be performed, and `results` will only be valid for those tasks
* which managed to complete. Invoked with (err, [results...]).
* @example
*
* // The example from `auto` can be rewritten as follows:
* async.autoInject({
* get_data: function(callback) {
* // async code to get some data
* callback(null, 'data', 'converted to array');
* },
* make_folder: function(callback) {
* // async code to create a directory to store a file in
* // this is run at the same time as getting the data
* callback(null, 'folder');
* },
* write_file: function(get_data, make_folder, callback) {
* // once there is some data and the directory exists,
* // write the data to a file in the directory
* callback(null, 'filename');
* },
* email_link: function(write_file, callback) {
* // once the file is written let's email a link to it...
* // write_file contains the filename returned by write_file.
* callback(null, {'file':write_file, 'email':'user@example.com'});
* }
* }, function(err, email_link) {
* console.log('err = ', err);
* console.log('email_link = ', email_link);
* });
*
* // If you are using a JS minifier that mangles parameter names, `autoInject`
* // will not work with plain functions, since the parameter names will be
* // collapsed to a single letter identifier. To work around this, you can
* // explicitly specify the names of the parameters your task function needs
* // in an array, similar to Angular.js dependency injection. The final
* // results callback can be provided as an array in the same way.
*
* // This still has an advantage over plain `auto`, since the results a task
* // depends on are still spread into arguments.
* async.autoInject({
* //...
* write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
* callback(null, 'filename');
* }],
* email_link: ['write_file', function(write_file, callback) {
* callback(null, {'file':write_file, 'email':'user@example.com'});
* }]
* //...
* }, ['email_link', function(err, email_link) {
* console.log('err = ', err);
* console.log('email_link = ', email_link);
* }]);
*/
function autoInject(tasks, callback) {
var newTasks = {};
forOwn(tasks, function (taskFn, key) {
var params;
if (isArray(taskFn)) {
params = copyArray(taskFn);
taskFn = params.pop();
newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
} else if (taskFn.length === 0) {
throw new Error("autoInject task functions require explicit parameters.");
} else if (taskFn.length === 1) {
// no dependencies, use the function as-is
newTasks[key] = taskFn;
} else {
params = parseParams(taskFn);
params.pop();
newTasks[key] = params.concat(newTask);
}
function newTask(results, taskCb) {
var newArgs = arrayMap(params, function (name) {
return results[name];
});
newArgs.push(taskCb);
taskFn.apply(null, newArgs);
}
});
auto(newTasks, callback);
}
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _defer;
if (_setImmediate) {
_defer = _setImmediate;
} else if (typeof process === 'object' && typeof process.nextTick === 'function') {
_defer = process.nextTick;
} else {
_defer = function (fn) {
setTimeout(fn, 0);
};
}
var setImmediate$1 = rest(function (fn, args) {
_defer(function () {
fn.apply(null, args);
});
});
function queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
} else if (concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== 'function') {
throw new Error('task callback must be a function');
}
q.started = true;
if (!isArray(data)) {
data = [data];
}
if (data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return setImmediate$1(function () {
q.drain();
});
}
arrayEach(data, function (task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
});
setImmediate$1(q.process);
}
function _next(q, tasks) {
return function () {
workers -= 1;
var removed = false;
var args = arguments;
arrayEach(tasks, function (task) {
arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (workers <= q.concurrency - q.buffer) {
q.unsaturated();
}
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
unsaturated: noop,
buffer: concurrency / 4,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
while (!q.paused && workers < q.concurrency && q.tasks.length) {
var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length);
var data = arrayMap(tasks, baseProperty('data'));
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
if (workers === q.concurrency) {
q.saturated();
}
var cb = onlyOnce(_next(q, tasks));
worker(data, cb);
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function () {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) {
return;
}
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
setImmediate$1(q.process);
}
}
};
return q;
}
/**
* A cargo of tasks for the worker function to complete. Cargo inherits all of
* the same methods and event callbacks as {@link async.queue}.
* @typedef {Object} cargo
* @property {Function} length - A function returning the number of items
* waiting to be processed. Invoke with ().
* @property {number} payload - An `integer` for determining how many tasks
* should be process per round. This property can be changed after a `cargo` is
* created to alter the payload on-the-fly.
* @property {Function} push - Adds `task` to the `queue`. The callback is
* called once the `worker` has finished processing the task. Instead of a
* single task, an array of `tasks` can be submitted. The respective callback is
* used for every task in the list. Invoke with (task, [callback]).
* @property {Function} saturated - A callback that is called when the
* `queue.length()` hits the concurrency and further tasks will be queued.
* @property {Function} empty - A callback that is called when the last item
* from the `queue` is given to a `worker`.
* @property {Function} drain - A callback that is called when the last item
* from the `queue` has returned from the `worker`.
* @property {Function} idle - a function returning false if there are items
* waiting or being processed, or true if not. Invoke with ().
* @property {Function} pause - a function that pauses the processing of tasks
* until `resume()` is called. Invoke with ().
* @property {Function} resume - a function that resumes the processing of
* queued tasks when the queue is paused. Invoke with ().
* @property {Function} kill - a function that removes the `drain` callback and
* empties remaining tasks from the queue forcing it to go idle. Invoke with ().
*/
/**
* Creates a `cargo` object with the specified payload. Tasks added to the
* cargo will be processed altogether (up to the `payload` limit). If the
* `worker` is in progress, the task is queued until it becomes available. Once
* the `worker` has completed some tasks, each callback of those tasks is
* called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)
* for how `cargo` and `queue` work.
*
* While [queue](#queue) passes only one task to one of a group of workers
* at a time, cargo passes an array of tasks to a single worker, repeating
* when the worker is finished.
*
* @name cargo
* @static
* @memberOf async
* @see async.queue
* @category Control Flow
* @param {Function} worker - An asynchronous function for processing an array
* of queued tasks, which must call its `callback(err)` argument when finished,
* with an optional `err` argument. Invoked with (tasks, callback).
* @param {number} [payload=Infinity] - An optional `integer` for determining
* how many tasks should be processed per round; if omitted, the default is
* unlimited.
* @returns {cargo} A cargo object to manage the tasks. Callbacks can
* attached as certain properties to listen for specific events during the
* lifecycle of the cargo and inner queue.
* @example
*
* // create a cargo object with payload 2
* var cargo = async.cargo(function(tasks, callback) {
* for (var i=0; i<tasks.length; i++) {
* console.log('hello ' + tasks[i].name);
* }
* callback();
* }, 2);
*
* // add some items
* cargo.push({name: 'foo'}, function(err) {
* console.log('finished processing foo');
* });
* cargo.push({name: 'bar'}, function(err) {
* console.log('finished processing bar');
* });
* cargo.push({name: 'baz'}, function(err) {
* console.log('finished processing baz');
* });
*/
function cargo(worker, payload) {
return queue(worker, 1, payload);
}
/**
* The same as `eachOf` but runs a maximum of `limit` async operations at a
* time.
*
* @name eachOfLimit
* @static
* @memberOf async
* @see async.eachOf
* @alias forEachOfLimit
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A function to apply to each
* item in `coll`. The `key` is the item's key, or index in the case of an
* array. The iteratee is passed a `callback(err)` which must be called once it
* has completed. If no error has occurred, the callback should be run without
* arguments or with an explicit `null` argument. Invoked with
* (item, key, callback).
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
*/
function eachOfLimit(obj, limit, iteratee, cb) {
_eachOfLimit(limit)(obj, iteratee, cb);
}
/**
* The same as `eachOf` but runs only a single async operation at a time.
*
* @name eachOfSeries
* @static
* @memberOf async
* @see async.eachOf
* @alias forEachOfSeries
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item in `coll`. The
* `key` is the item's key, or index in the case of an array. The iteratee is
* passed a `callback(err)` which must be called once it has completed. If no
* error has occurred, the callback should be run without arguments or with an
* explicit `null` argument. Invoked with (item, key, callback).
* @param {Function} [callback] - A callback which is called when all `iteratee`
* functions have finished, or an error occurs. Invoked with (err).
*/
var eachOfSeries = doLimit(eachOfLimit, 1);
/**
* Reduces `coll` into a single value using an async `iteratee` to return each
* successive step. `memo` is the initial state of the reduction. This function
* only operates in series.
*
* For performance reasons, it may make sense to split a call to this function
* into a parallel map, and then use the normal `Array.prototype.reduce` on the
* results. This function is for situations where each step in the reduction
* needs to be async; if you can get the data before reducing it, then it's
* probably a good idea to do so.
*
* @name reduce
* @static
* @memberOf async
* @alias inject, foldl
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {*} memo - The initial state of the reduction.
* @param {Function} iteratee - A function applied to each item in the
* array to produce the next step in the reduction. The `iteratee` is passed a
* `callback(err, reduction)` which accepts an optional error as its first
* argument, and the state of the reduction as the second. If an error is
* passed to the callback, the reduction is stopped and the main `callback` is
* immediately called with the error. Invoked with (memo, item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the reduced value. Invoked with
* (err, result).
* @example
*
* async.reduce([1,2,3], 0, function(memo, item, callback) {
* // pointless async:
* process.nextTick(function() {
* callback(null, memo + item)
* });
* }, function(err, result) {
* // result is now equal to the last value of memo, which is 6
* });
*/
function reduce(arr, memo, iteratee, cb) {
eachOfSeries(arr, function (x, i, cb) {
iteratee(memo, x, function (err, v) {
memo = v;
cb(err);
});
}, function (err) {
cb(err, memo);
});
}
/**
* Version of the compose function that is more natural to read. Each function
* consumes the return value of the previous function. It is the equivalent of
* {@link async.compose} with the arguments reversed.
*
* Each function is executed with the `this` binding of the composed function.
*
* @name seq
* @static
* @memberOf async
* @see async.compose
* @category Control Flow
* @param {...Function} functions - the asynchronous functions to compose
* @example
*
* // Requires lodash (or underscore), express3 and dresende's orm2.
* // Part of an app, that fetches cats of the logged user.
* // This example uses `seq` function to avoid overnesting and error
* // handling clutter.
* app.get('/cats', function(request, response) {
* var User = request.models.User;
* async.seq(
* _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))
* function(user, fn) {
* user.getCats(fn); // 'getCats' has signature (callback(err, data))
* }
* )(req.session.user_id, function (err, cats) {
* if (err) {
* console.error(err);
* response.json({ status: 'error', message: err.message });
* } else {
* response.json({ status: 'ok', message: 'Cats found', data: cats });
* }
* });
* });
*/
function seq() /* functions... */{
var fns = arguments;
return rest(function (args) {
var that = this;
var cb = args[args.length - 1];
if (typeof cb == 'function') {
args.pop();
} else {
cb = noop;
}
reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([rest(function (err, nextargs) {
cb(err, nextargs);
})]));
}, function (err, results) {
cb.apply(that, [err].concat(results));
});
});
}
var reverse = Array.prototype.reverse;
/**
* Creates a function which is a composition of the passed asynchronous
* functions. Each function consumes the return value of the function that
* follows. Composing functions `f()`, `g()`, and `h()` would produce the result
* of `f(g(h()))`, only this version uses callbacks to obtain the return values.
*
* Each function is executed with the `this` binding of the composed function.
*
* @name compose
* @static
* @memberOf async
* @category Control Flow
* @param {...Function} functions - the asynchronous functions to compose
* @example
*
* function add1(n, callback) {
* setTimeout(function () {
* callback(null, n + 1);
* }, 10);
* }
*
* function mul3(n, callback) {
* setTimeout(function () {
* callback(null, n * 3);
* }, 10);
* }
*
* var add1mul3 = async.compose(mul3, add1);
* add1mul3(4, function (err, result) {
* // result now equals 15
* });
*/
function compose() /* functions... */{
return seq.apply(null, reverse.call(arguments));
}
function concat$1(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
/**
* Like `each`, except that it passes the key (or index) as the second argument
* to the iteratee.
*
* @name eachOf
* @static
* @memberOf async
* @alias forEachOf
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each
* item in `coll`. The `key` is the item's key, or index in the case of an
* array. The iteratee is passed a `callback(err)` which must be called once it
* has completed. If no error has occurred, the callback should be run without
* arguments or with an explicit `null` argument. Invoked with
* (item, key, callback).
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
* @example
*
* var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
* var configs = {};
*
* async.forEachOf(obj, function (value, key, callback) {
* fs.readFile(__dirname + value, "utf8", function (err, data) {
* if (err) return callback(err);
* try {
* configs[key] = JSON.parse(data);
* } catch (e) {
* return callback(e);
* }
* callback();
* });
* }, function (err) {
* if (err) console.error(err.message);
* // configs is now a map of JSON data
* doSomethingWith(configs);
* });
*/
var eachOf = doLimit(eachOfLimit, Infinity);
function doParallel(fn) {
return function (obj, iteratee, callback) {
return fn(eachOf, obj, iteratee, callback);
};
}
/**
* Applies `iteratee` to each item in `coll`, concatenating the results. Returns
* the concatenated list. The `iteratee`s are called in parallel, and the
* results are concatenated as they return. There is no guarantee that the
* results array will be returned in the original order of `coll` passed to the
* `iteratee` function.
*
* @name concat
* @static
* @memberOf async
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item in `coll`.
* The iteratee is passed a `callback(err, results)` which must be called once
* it has completed with an error (which can be `null`) and an array of results.
* Invoked with (item, callback).
* @param {Function} [callback(err)] - A callback which is called after all the
* `iteratee` functions have finished, or an error occurs. Results is an array
* containing the concatenated results of the `iteratee` function. Invoked with
* (err, results).
* @example
*
* async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {
* // files is now a list of filenames that exist in the 3 directories
* });
*/
var concat = doParallel(concat$1);
function doSeries(fn) {
return function (obj, iteratee, callback) {
return fn(eachOfSeries, obj, iteratee, callback);
};
}
/**
* The same as `concat` but runs only a single async operation at a time.
*
* @name concatSeries
* @static
* @memberOf async
* @see async.concat
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item in `coll`.
* The iteratee is passed a `callback(err, results)` which must be called once
* it has completed with an error (which can be `null`) and an array of results.
* Invoked with (item, callback).
* @param {Function} [callback(err)] - A callback which is called after all the
* `iteratee` functions have finished, or an error occurs. Results is an array
* containing the concatenated results of the `iteratee` function. Invoked with
* (err, results).
*/
var concatSeries = doSeries(concat$1);
/**
* Returns a function that when called, calls-back with the values provided.
* Useful as the first function in a `waterfall`, or for plugging values in to
* `auto`.
*
* @name constant
* @static
* @memberOf async
* @category Util
* @param {...*} arguments... - Any number of arguments to automatically invoke
* callback with.
* @returns {Function} Returns a function that when invoked, automatically
* invokes the callback with the previous given arguments.
* @example
*
* async.waterfall([
* async.constant(42),
* function (value, next) {
* // value === 42
* },
* //...
* ], callback);
*
* async.waterfall([
* async.constant(filename, "utf8"),
* fs.readFile,
* function (fileData, next) {
* //...
* }
* //...
* ], callback);
*
* async.auto({
* hostname: async.constant("https://server.net/"),
* port: findFreePort,
* launchServer: ["hostname", "port", function (options, cb) {
* startServer(options, cb);
* }],
* //...
* }, callback);
*/
var constant = rest(function (values) {
var args = [null].concat(values);
return initialParams(function (ignoredArgs, callback) {
return callback.apply(this, args);
});
});
function _createTester(eachfn, check, getResult) {
return function (arr, limit, iteratee, cb) {
function done(err) {
if (cb) {
if (err) {
cb(err);
} else {
cb(null, getResult(false));
}
}
}
function wrappedIteratee(x, _, callback) {
if (!cb) return callback();
iteratee(x, function (err, v) {
if (cb) {
if (err) {
cb(err);
cb = iteratee = false;
} else if (check(v)) {
cb(null, getResult(true, x));
cb = iteratee = false;
}
}
callback();
});
}
if (arguments.length > 3) {
cb = cb || noop;
eachfn(arr, limit, wrappedIteratee, done);
} else {
cb = iteratee;
cb = cb || noop;
iteratee = limit;
eachfn(arr, wrappedIteratee, done);
}
};
}
function _findGetResult(v, x) {
return x;
}
/**
* Returns the first value in `coll` that passes an async truth test. The
* `iteratee` is applied in parallel, meaning the first iteratee to return
* `true` will fire the detect `callback` with that result. That means the
* result might not be the first item in the original `coll` (in terms of order)
* that passes the test.
* If order within the original `coll` is important, then look at
* `detectSeries`.
*
* @name detect
* @static
* @memberOf async
* @alias find
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The iteratee is passed a `callback(err, truthValue)` which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the `iteratee` functions have finished.
* Result will be the first item in the array that passes the truth test
* (iteratee) or the value `undefined` if none passed. Invoked with
* (err, result).
* @example
*
* async.detect(['file1','file2','file3'], function(filePath, callback) {
* fs.access(filePath, function(err) {
* callback(null, !err)
* });
* }, function(err, result) {
* // result now equals the first file in the list that exists
* });
*/
var detect = _createTester(eachOf, identity, _findGetResult);
/**
* The same as `detect` but runs a maximum of `limit` async operations at a
* time.
*
* @name detectLimit
* @static
* @memberOf async
* @see async.detect
* @alias findLimit
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The iteratee is passed a `callback(err, truthValue)` which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the `iteratee` functions have finished.
* Result will be the first item in the array that passes the truth test
* (iteratee) or the value `undefined` if none passed. Invoked with
* (err, result).
*/
var detectLimit = _createTester(eachOfLimit, identity, _findGetResult);
/**
* The same as `detect` but runs only a single async operation at a time.
*
* @name detectSeries
* @static
* @memberOf async
* @see async.detect
* @alias findSeries
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The iteratee is passed a `callback(err, truthValue)` which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the `iteratee` functions have finished.
* Result will be the first item in the array that passes the truth test
* (iteratee) or the value `undefined` if none passed. Invoked with
* (err, result).
*/
var detectSeries = _createTester(eachOfSeries, identity, _findGetResult);
function consoleFunc(name) {
return rest(function (fn, args) {
fn.apply(null, args.concat([rest(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
} else if (console[name]) {
arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
/**
* Logs the result of an `async` function to the `console` using `console.dir`
* to display the properties of the resulting object. Only works in Node.js or
* in browsers that support `console.dir` and `console.error` (such as FF and
* Chrome). If multiple arguments are returned from the async function,
* `console.dir` is called on each argument in order.
*
* @name log
* @static
* @memberOf async
* @category Util
* @param {Function} function - The function you want to eventually apply all
* arguments to.
* @param {...*} arguments... - Any number of arguments to apply to the function.
* @example
*
* // in a module
* var hello = function(name, callback) {
* setTimeout(function() {
* callback(null, {hello: name});
* }, 1000);
* };
*
* // in the node repl
* node> async.dir(hello, 'world');
* {hello: 'world'}
*/
var dir = consoleFunc('dir');
/**
* Like {@link async.whilst}, except the `test` is an asynchronous function that
* is passed a callback in the form of `function (err, truth)`. If error is
* passed to `test` or `fn`, the main callback is immediately called with the
* value of the error.
*
* @name during
* @static
* @memberOf async
* @see async.whilst
* @category Control Flow
* @param {Function} test - asynchronous truth test to perform before each
* execution of `fn`. Invoked with (callback).
* @param {Function} fn - A function which is called each time `test` passes.
* The function is passed a `callback(err)`, which must be called once it has
* completed with an optional `err` argument. Invoked with (callback).
* @param {Function} [callback] - A callback which is called after the test
* function has failed and repeated execution of `fn` has stopped. `callback`
* will be passed an error and any arguments passed to the final `fn`'s
* callback. Invoked with (err, [results]);
* @example
*
* var count = 0;
*
* async.during(
* function (callback) {
* return callback(null, count < 5);
* },
* function (callback) {
* count++;
* setTimeout(callback, 1000);
* },
* function (err) {
* // 5 seconds have passed
* }
* );
*/
function during(test, iteratee, cb) {
cb = cb || noop;
var next = rest(function (err, args) {
if (err) {
cb(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function (err, truth) {
if (err) return cb(err);
if (!truth) return cb(null);
iteratee(next);
};
test(check);
}
/**
* The post-check version of {@link async.during}. To reflect the difference in
* the order of operations, the arguments `test` and `fn` are switched.
*
* Also a version of {@link async.doWhilst} with asynchronous `test` function.
* @name doDuring
* @static
* @memberOf async
* @see async.during
* @category Control Flow
* @param {Function} fn - A function which is called each time `test` passes.
* The function is passed a `callback(err)`, which must be called once it has
* completed with an optional `err` argument. Invoked with (callback).
* @param {Function} test - asynchronous truth test to perform before each
* execution of `fn`. Invoked with (callback).
* @param {Function} [callback] - A callback which is called after the test
* function has failed and repeated execution of `fn` has stopped. `callback`
* will be passed an error and any arguments passed to the final `fn`'s
* callback. Invoked with (err, [results]);
*/
function doDuring(iteratee, test, cb) {
var calls = 0;
during(function (next) {
if (calls++ < 1) return next(null, true);
test.apply(this, arguments);
}, iteratee, cb);
}
/**
* Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when
* stopped, or an error occurs.
*
* @name whilst
* @static
* @memberOf async
* @category Control Flow
* @param {Function} test - synchronous truth test to perform before each
* execution of `fn`. Invoked with ().
* @param {Function} fn - A function which is called each time `test` passes.
* The function is passed a `callback(err)`, which must be called once it has
* completed with an optional `err` argument. Invoked with (callback).
* @param {Function} [callback] - A callback which is called after the test
* function has failed and repeated execution of `fn` has stopped. `callback`
* will be passed an error and any arguments passed to the final `fn`'s
* callback. Invoked with (err, [results]);
* @example
*
* var count = 0;
* async.whilst(
* function() { return count < 5; },
* function(callback) {
* count++;
* setTimeout(function() {
* callback(null, count);
* }, 1000);
* },
* function (err, n) {
* // 5 seconds have passed, n = 5
* }
* );
*/
function whilst(test, iteratee, cb) {
cb = cb || noop;
if (!test()) return cb(null);
var next = rest(function (err, args) {
if (err) return cb(err);
if (test.apply(this, args)) return iteratee(next);
cb.apply(null, [null].concat(args));
});
iteratee(next);
}
/**
* The post-check version of {@link async.whilst}. To reflect the difference in
* the order of operations, the arguments `test` and `fn` are switched.
*
* `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
*
* @name doWhilst
* @static
* @memberOf async
* @see async.whilst
* @category Control Flow
* @param {Function} fn - A function which is called each time `test` passes.
* The function is passed a `callback(err)`, which must be called once it has
* completed with an optional `err` argument. Invoked with (callback).
* @param {Function} test - synchronous truth test to perform after each
* execution of `fn`. Invoked with Invoked with the non-error callback results
* of `fn`.
* @param {Function} [callback] - A callback which is called after the test
* function has failed and repeated execution of `fn` has stopped. `callback`
* will be passed an error and any arguments passed to the final `fn`'s
* callback. Invoked with (err, [results]);
*/
function doWhilst(iteratee, test, cb) {
var calls = 0;
return whilst(function () {
return ++calls <= 1 || test.apply(this, arguments);
}, iteratee, cb);
}
/**
* Like {@link async.doWhilst}, except the `test` is inverted. Note the
* argument ordering differs from `until`.
*
* @name doUntil
* @static
* @memberOf async
* @see async.doWhilst
* @category Control Flow
* @param {Function} fn - A function which is called each time `test` fails.
* The function is passed a `callback(err)`, which must be called once it has
* completed with an optional `err` argument. Invoked with (callback).
* @param {Function} test - synchronous truth test to perform after each
* execution of `fn`. Invoked with the non-error callback results of `fn`.
* @param {Function} [callback] - A callback which is called after the test
* function has passed and repeated execution of `fn` has stopped. `callback`
* will be passed an error and any arguments passed to the final `fn`'s
* callback. Invoked with (err, [results]);
*/
function doUntil(iteratee, test, cb) {
return doWhilst(iteratee, function () {
return !test.apply(this, arguments);
}, cb);
}
function _withoutIndex(iteratee) {
return function (value, index, callback) {
return iteratee(value, callback);
};
}
/**
* The same as `each` but runs a maximum of `limit` async operations at a time.
*
* @name eachLimit
* @static
* @memberOf async
* @see async.each
* @alias forEachLimit
* @category Collection
* @param {Array|Object} coll - A colleciton to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A function to apply to each item in `coll`. The
* iteratee is passed a `callback(err)` which must be called once it has
* completed. If no error has occurred, the `callback` should be run without
* arguments or with an explicit `null` argument. The array index is not passed
* to the iteratee. Invoked with (item, callback). If you need the index, use
* `eachOfLimit`.
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
*/
function eachLimit(arr, limit, iteratee, cb) {
return _eachOfLimit(limit)(arr, _withoutIndex(iteratee), cb);
}
/**
* Applies the function `iteratee` to each item in `coll`, in parallel.
* The `iteratee` is called with an item from the list, and a callback for when
* it has finished. If the `iteratee` passes an error to its `callback`, the
* main `callback` (for the `each` function) is immediately called with the
* error.
*
* Note, that since this function applies `iteratee` to each item in parallel,
* there is no guarantee that the iteratee functions will complete in order.
*
* @name each
* @static
* @memberOf async
* @alias forEach
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item
* in `coll`. The iteratee is passed a `callback(err)` which must be called once
* it has completed. If no error has occurred, the `callback` should be run
* without arguments or with an explicit `null` argument. The array index is not
* passed to the iteratee. Invoked with (item, callback). If you need the index,
* use `eachOf`.
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
* @example
*
* // assuming openFiles is an array of file names and saveFile is a function
* // to save the modified contents of that file:
*
* async.each(openFiles, saveFile, function(err){
* // if any of the saves produced an error, err would equal that error
* });
*
* // assuming openFiles is an array of file names
* async.each(openFiles, function(file, callback) {
*
* // Perform operation on file here.
* console.log('Processing file ' + file);
*
* if( file.length > 32 ) {
* console.log('This file name is too long');
* callback('File name too long');
* } else {
* // Do work to process file here
* console.log('File processed');
* callback();
* }
* }, function(err) {
* // if any of the file processing produced an error, err would equal that error
* if( err ) {
* // One of the iterations produced an error.
* // All processing will now stop.
* console.log('A file failed to process');
* } else {
* console.log('All files have been processed successfully');
* }
* });
*/
var each = doLimit(eachLimit, Infinity);
/**
* The same as `each` but runs only a single async operation at a time.
*
* @name eachSeries
* @static
* @memberOf async
* @see async.each
* @alias forEachSeries
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each
* item in `coll`. The iteratee is passed a `callback(err)` which must be called
* once it has completed. If no error has occurred, the `callback` should be run
* without arguments or with an explicit `null` argument. The array index is
* not passed to the iteratee. Invoked with (item, callback). If you need the
* index, use `eachOfSeries`.
* @param {Function} [callback] - A callback which is called when all
* `iteratee` functions have finished, or an error occurs. Invoked with (err).
*/
var eachSeries = doLimit(eachLimit, 1);
/**
* Wrap an async function and ensure it calls its callback on a later tick of
* the event loop. If the function already calls its callback on a next tick,
* no extra deferral is added. This is useful for preventing stack overflows
* (`RangeError: Maximum call stack size exceeded`) and generally keeping
* [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)
* contained.
*
* @name ensureAsync
* @static
* @memberOf async
* @category Util
* @param {Function} fn - an async function, one that expects a node-style
* callback as its last argument.
* @returns {Function} Returns a wrapped function with the exact same call
* signature as the function passed in.
* @example
*
* function sometimesAsync(arg, callback) {
* if (cache[arg]) {
* return callback(null, cache[arg]); // this would be synchronous!!
* } else {
* doSomeIO(arg, callback); // this IO would be asynchronous
* }
* }
*
* // this has a risk of stack overflows if many results are cached in a row
* async.mapSeries(args, sometimesAsync, done);
*
* // this will defer sometimesAsync's callback if necessary,
* // preventing stack overflows
* async.mapSeries(args, async.ensureAsync(sometimesAsync), done);
*/
function ensureAsync(fn) {
return initialParams(function (args, callback) {
var sync = true;
args.push(function () {
var innerArgs = arguments;
if (sync) {
setImmediate$1(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
fn.apply(this, args);
sync = false;
});
}
function notId(v) {
return !v;
}
/**
* The same as `every` but runs a maximum of `limit` async operations at a time.
*
* @name everyLimit
* @static
* @memberOf async
* @see async.every
* @alias allLimit
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A truth test to apply to each item in the
* collection in parallel. The iteratee is passed a `callback(err, truthValue)`
* which must be called with a boolean argument once it has completed. Invoked
* with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result will be either `true` or `false`
* depending on the values of the async tests. Invoked with (err, result).
*/
var everyLimit = _createTester(eachOfLimit, notId, notId);
/**
* Returns `true` if every element in `coll` satisfies an async test. If any
* iteratee call returns `false`, the main `callback` is immediately called.
*
* @name every
* @static
* @memberOf async
* @alias all
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in the
* collection in parallel. The iteratee is passed a `callback(err, truthValue)`
* which must be called with a boolean argument once it has completed. Invoked
* with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result will be either `true` or `false`
* depending on the values of the async tests. Invoked with (err, result).
* @example
*
* async.every(['file1','file2','file3'], function(filePath, callback) {
* fs.access(filePath, function(err) {
* callback(null, !err)
* });
* }, function(err, result) {
* // if result is true then every file exists
* });
*/
var every = doLimit(everyLimit, Infinity);
/**
* The same as `every` but runs only a single async operation at a time.
*
* @name everySeries
* @static
* @memberOf async
* @see async.every
* @alias allSeries
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in the
* collection in parallel. The iteratee is passed a `callback(err, truthValue)`
* which must be called with a boolean argument once it has completed. Invoked
* with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result will be either `true` or `false`
* depending on the values of the async tests. Invoked with (err, result).
*/
var everySeries = doLimit(everyLimit, 1);
function _filter(eachfn, arr, iteratee, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iteratee(x, function (err, v) {
if (err) {
callback(err);
} else {
if (v) {
results.push({ index: index, value: x });
}
callback();
}
});
}, function (err) {
if (err) {
callback(err);
} else {
callback(null, arrayMap(results.sort(function (a, b) {
return a.index - b.index;
}), baseProperty('value')));
}
});
}
/**
* The same as `filter` but runs a maximum of `limit` async operations at a
* time.
*
* @name filterLimit
* @static
* @memberOf async
* @see async.filter
* @alias selectLimit
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
*/
var filterLimit = doParallelLimit(_filter);
/**
* Returns a new array of all the values in `coll` which pass an async truth
* test. This operation is performed in parallel, but the results array will be
* in the same order as the original.
*
* @name filter
* @static
* @memberOf async
* @alias select
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @example
*
* async.filter(['file1','file2','file3'], function(filePath, callback) {
* fs.access(filePath, function(err) {
* callback(null, !err)
* });
* }, function(err, results) {
* // results now equals an array of the existing files
* });
*/
var filter = doLimit(filterLimit, Infinity);
/**
* The same as `filter` but runs only a single async operation at a time.
*
* @name filterSeries
* @static
* @memberOf async
* @see async.filter
* @alias selectSeries
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results)
*/
var filterSeries = doLimit(filterLimit, 1);
/**
* Calls the asynchronous function `fn` with a callback parameter that allows it
* to call itself again, in series, indefinitely.
* If an error is passed to the
* callback then `errback` is called with the error, and execution stops,
* otherwise it will never be called.
*
* @name forever
* @static
* @memberOf async
* @category Control Flow
* @param {Function} fn - a function to call repeatedly. Invoked with (next).
* @param {Function} [errback] - when `fn` passes an error to it's callback,
* this function will be called, and execution stops. Invoked with (err).
* @example
*
* async.forever(
* function(next) {
* // next is suitable for passing to things that need a callback(err [, whatever]);
* // it will result in this function being called again.
* },
* function(err) {
* // if next is called with a value in its first parameter, it will appear
* // in here as 'err', and execution will stop.
* }
* );
*/
function forever(fn, cb) {
var done = onlyOnce(cb || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) return done(err);
task(next);
}
next();
}
/**
* Creates an iterator function which calls the next function in the `tasks`
* array, returning a continuation to call the next one after that. It's also
* possible to “peek” at the next iterator with `iterator.next()`.
*
* This function is used internally by the `async` module, but can be useful
* when you want to manually control the flow of functions in series.
*
* @name iterator
* @static
* @memberOf async
* @category Control Flow
* @param {Array} tasks - An array of functions to run.
* @returns The next function to run in the series.
* @example
*
* var iterator = async.iterator([
* function() { sys.p('one'); },
* function() { sys.p('two'); },
* function() { sys.p('three'); }
* ]);
*
* node> var iterator2 = iterator();
* 'one'
* node> var iterator3 = iterator2();
* 'two'
* node> iterator3();
* 'three'
* node> var nextfn = iterator2.next();
* node> nextfn();
* 'three'
*/
function iterator$1 (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return index < tasks.length - 1 ? makeCallback(index + 1) : null;
};
return fn;
}
return makeCallback(0);
}
/**
* Logs the result of an `async` function to the `console`. Only works in
* Node.js or in browsers that support `console.log` and `console.error` (such
* as FF and Chrome). If multiple arguments are returned from the async
* function, `console.log` is called on each argument in order.
*
* @name log
* @static
* @memberOf async
* @category Util
* @param {Function} function - The function you want to eventually apply all
* arguments to.
* @param {...*} arguments... - Any number of arguments to apply to the function.
* @example
*
* // in a module
* var hello = function(name, callback) {
* setTimeout(function() {
* callback(null, 'hello ' + name);
* }, 1000);
* };
*
* // in the node repl
* node> async.log(hello, 'world');
* 'hello world'
*/
var log = consoleFunc('log');
function has(obj, key) {
return key in obj;
}
/**
* Caches the results of an `async` function. When creating a hash to store
* function results against, the callback is omitted from the hash and an
* optional hash function can be used.
*
* If no hash function is specified, the first argument is used as a hash key,
* which may work reasonably if it is a string or a data type that converts to a
* distinct string. Note that objects and arrays will not behave reasonably.
* Neither will cases where the other arguments are significant. In such cases,
* specify your own hash function.
*
* The cache of results is exposed as the `memo` property of the function
* returned by `memoize`.
*
* @name memoize
* @static
* @memberOf async
* @category Util
* @param {Function} fn - The function to proxy and cache results from.
* @param {Function} hasher - An optional function for generating a custom hash
* for storing results. It has all the arguments applied to it apart from the
* callback, and must be synchronous.
* @example
*
* var slow_fn = function(name, callback) {
* // do something
* callback(null, result);
* };
* var fn = async.memoize(slow_fn);
*
* // fn can now be used as if it were slow_fn
* fn('some name', function() {
* // callback
* });
*/
function memoize$1(fn, hasher) {
var memo = Object.create(null);
var queues = Object.create(null);
hasher = hasher || identity;
var memoized = initialParams(function memoized(args, callback) {
var key = hasher.apply(null, args);
if (has(memo, key)) {
setImmediate$1(function () {
callback.apply(null, memo[key]);
});
} else if (has(queues, key)) {
queues[key].push(callback);
} else {
queues[key] = [callback];
fn.apply(null, args.concat([rest(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
}
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(rest(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
/**
* The same as `parallel` but runs a maximum of `limit` async operations at a
* time.
*
* @name parallel
* @static
* @memberOf async
* @see async.parallel
* @category Control Flow
* @param {Array|Collection} tasks - A collection containing functions to run.
* Each function is passed a `callback(err, result)` which it must call on
* completion with an error `err` (which can be `null`) and an optional `result`
* value.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed successfully. This function gets a results array
* (or object) containing all the result arguments passed to the task callbacks.
* Invoked with (err, results).
*/
function parallelLimit(tasks, limit, cb) {
return _parallel(_eachOfLimit(limit), tasks, cb);
}
/**
* Run the `tasks` collection of functions in parallel, without waiting until
* the previous function has completed. If any of the functions pass an error to
* its callback, the main `callback` is immediately called with the value of the
* error. Once the `tasks` have completed, the results are passed to the final
* `callback` as an array.
*
* **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about
* parallel execution of code. If your tasks do not use any timers or perform
* any I/O, they will actually be executed in series. Any synchronous setup
* sections for each task will happen one after the other. JavaScript remains
* single-threaded.
*
* It is also possible to use an object instead of an array. Each property will
* be run as a function and the results will be passed to the final `callback`
* as an object instead of an array. This can be a more readable way of handling
* results from {@link async.parallel}.
*
* @name parallel
* @static
* @memberOf async
* @category Control Flow
* @param {Array|Object} tasks - A collection containing functions to run.
* Each function is passed a `callback(err, result)` which it must call on
* completion with an error `err` (which can be `null`) and an optional `result`
* value.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed successfully. This function gets a results array
* (or object) containing all the result arguments passed to the task callbacks.
* Invoked with (err, results).
* @example
* async.parallel([
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ],
* // optional callback
* function(err, results) {
* // the results array will equal ['one','two'] even though
* // the second function had a shorter timeout.
* });
*
* // an example using an object instead of an array
* async.parallel({
* one: function(callback) {
* setTimeout(function() {
* callback(null, 1);
* }, 200);
* },
* two: function(callback) {
* setTimeout(function() {
* callback(null, 2);
* }, 100);
* }
* }, function(err, results) {
* // results is now equals to: {one: 1, two: 2}
* });
*/
var parallel = doLimit(parallelLimit, Infinity);
/**
* A queue of tasks for the worker function to complete.
* @typedef {Object} queue
* @property {Function} length - a function returning the number of items
* waiting to be processed. Invoke with ().
* @property {Function} started - a function returning whether or not any
* items have been pushed and processed by the queue. Invoke with ().
* @property {Function} running - a function returning the number of items
* currently being processed. Invoke with ().
* @property {Function} workersList - a function returning the array of items
* currently being processed. Invoke with ().
* @property {Function} idle - a function returning false if there are items
* waiting or being processed, or true if not. Invoke with ().
* @property {number} concurrency - an integer for determining how many `worker`
* functions should be run in parallel. This property can be changed after a
* `queue` is created to alter the concurrency on-the-fly.
* @property {Function} push - add a new task to the `queue`. Calls `callback`
* once the `worker` has finished processing the task. Instead of a single task,
* a `tasks` array can be submitted. The respective callback is used for every
* task in the list. Invoke with (task, [callback]),
* @property {Function} unshift - add a new task to the front of the `queue`.
* Invoke with (task, [callback]).
* @property {Function} saturated - a callback that is called when the number of
* running workers hits the `concurrency` limit, and further tasks will be
* queued.
* @property {Function} unsaturated - a callback that is called when the number
* of running workers is less than the `concurrency` & `buffer` limits, and
* further tasks will not be queued.
* @property {number} buffer - A minimum threshold buffer in order to say that
* the `queue` is `unsaturated`.
* @property {Function} empty - a callback that is called when the last item
* from the `queue` is given to a `worker`.
* @property {Function} drain - a callback that is called when the last item
* from the `queue` has returned from the `worker`.
* @property {boolean} paused - a boolean for determining whether the queue is
* in a paused state.
* @property {Function} pause - a function that pauses the processing of tasks
* until `resume()` is called. Invoke with ().
* @property {Function} resume - a function that resumes the processing of
* queued tasks when the queue is paused. Invoke with ().
* @property {Function} kill - a function that removes the `drain` callback and
* empties remaining tasks from the queue forcing it to go idle. Invoke with ().
*/
/**
* Creates a `queue` object with the specified `concurrency`. Tasks added to the
* `queue` are processed in parallel (up to the `concurrency` limit). If all
* `worker`s are in progress, the task is queued until one becomes available.
* Once a `worker` completes a `task`, that `task`'s callback is called.
*
* @name queue
* @static
* @memberOf async
* @category Control Flow
* @param {Function} worker - An asynchronous function for processing a queued
* task, which must call its `callback(err)` argument when finished, with an
* optional `error` as an argument. If you want to handle errors from an
* individual task, pass a callback to `q.push()`. Invoked with
* (task, callback).
* @param {number} [concurrency=1] - An `integer` for determining how many
* `worker` functions should be run in parallel. If omitted, the concurrency
* defaults to `1`. If the concurrency is `0`, an error is thrown.
* @returns {queue} A queue object to manage the tasks. Callbacks can
* attached as certain properties to listen for specific events during the
* lifecycle of the queue.
* @example
*
* // create a queue object with concurrency 2
* var q = async.queue(function(task, callback) {
* console.log('hello ' + task.name);
* callback();
* }, 2);
*
* // assign a callback
* q.drain = function() {
* console.log('all items have been processed');
* };
*
* // add some items to the queue
* q.push({name: 'foo'}, function(err) {
* console.log('finished processing foo');
* });
* q.push({name: 'bar'}, function (err) {
* console.log('finished processing bar');
* });
*
* // add some items to the queue (batch-wise)
* q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
* console.log('finished processing item');
* });
*
* // add some items to the front of the queue
* q.unshift({name: 'bar'}, function (err) {
* console.log('finished processing bar');
* });
*/
function queue$1 (worker, concurrency) {
return queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
}
/**
* The same as {@link async.queue} only tasks are assigned a priority and
* completed in ascending priority order.
*
* @name priorityQueue
* @static
* @memberOf async
* @see async.queue
* @category Control Flow
* @param {Function} worker - An asynchronous function for processing a queued
* task, which must call its `callback(err)` argument when finished, with an
* optional `error` as an argument. If you want to handle errors from an
* individual task, pass a callback to `q.push()`. Invoked with
* (task, callback).
* @param {number} concurrency - An `integer` for determining how many `worker`
* functions should be run in parallel. If omitted, the concurrency defaults to
* `1`. If the concurrency is `0`, an error is thrown.
* @returns {queue} A priorityQueue object to manage the tasks. There are two
* differences between `queue` and `priorityQueue` objects:
* * `push(task, priority, [callback])` - `priority` should be a number. If an
* array of `tasks` is given, all tasks will be assigned the same priority.
* * The `unshift` method was removed.
*/
function priorityQueue (worker, concurrency) {
function _compareTasks(a, b) {
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + (end - beg + 1 >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== 'function') {
throw new Error('task callback must be a function');
}
q.started = true;
if (!isArray(data)) {
data = [data];
}
if (data.length === 0) {
// call drain immediately if there are no tasks
return setImmediate$1(function () {
q.drain();
});
}
arrayEach(data, function (task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
setImmediate$1(q.process);
});
}
// Start with a normal queue
var q = queue$1(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length,
index = fromRight ? length : -1,
iterable = Object(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _([1, 2]).forEach(function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/
function forEach(collection, iteratee) {
var func = isArray(collection) ? arrayEach : baseEach;
return func(collection, baseIteratee(iteratee, 3));
}
/**
* Runs the `tasks` array of functions in parallel, without waiting until the
* previous function has completed. Once any the `tasks` completed or pass an
* error to its callback, the main `callback` is immediately called. It's
* equivalent to `Promise.race()`.
*
* @name race
* @static
* @memberOf async
* @category Control Flow
* @param {Array} tasks - An array containing functions to run. Each function
* is passed a `callback(err, result)` which it must call on completion with an
* error `err` (which can be `null`) and an optional `result` value.
* @param {Function} callback - A callback to run once any of the functions have
* completed. This function gets an error or result from the first function that
* completed. Invoked with (err, result).
* @example
*
* async.race([
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ],
* // main callback
* function(err, result) {
* // the result will be equal to 'two' as it finishes earlier
* });
*/
function race(tasks, cb) {
cb = once(cb || noop);
if (!isArray(tasks)) return cb(new TypeError('First argument to race must be an array of functions'));
if (!tasks.length) return cb();
forEach(tasks, function (task) {
task(cb);
});
}
var slice = Array.prototype.slice;
/**
* Same as `reduce`, only operates on `coll` in reverse order.
*
* @name reduceRight
* @static
* @memberOf async
* @see async.reduce
* @alias foldr
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {*} memo - The initial state of the reduction.
* @param {Function} iteratee - A function applied to each item in the
* array to produce the next step in the reduction. The `iteratee` is passed a
* `callback(err, reduction)` which accepts an optional error as its first
* argument, and the state of the reduction as the second. If an error is
* passed to the callback, the reduction is stopped and the main `callback` is
* immediately called with the error. Invoked with (memo, item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the reduced value. Invoked with
* (err, result).
*/
function reduceRight(arr, memo, iteratee, cb) {
var reversed = slice.call(arr).reverse();
reduce(reversed, memo, iteratee, cb);
}
/**
* Wraps the function in another function that always returns data even when it
* errors.
*
* The object returned has either the property `error` or `value`.
*
* @name reflect
* @static
* @memberOf async
* @category Util
* @param {Function} function - The function you want to wrap
* @returns {Function} - A function that always passes null to it's callback as
* the error. The second argument to the callback will be an `object` with
* either an `error` or a `value` property.
* @example
*
* async.parallel([
* async.reflect(function(callback) {
* // do some stuff ...
* callback(null, 'one');
* }),
* async.reflect(function(callback) {
* // do some more stuff but error ...
* callback('bad stuff happened');
* }),
* async.reflect(function(callback) {
* // do some more stuff ...
* callback(null, 'two');
* })
* ],
* // optional callback
* function(err, results) {
* // values
* // results[0].value = 'one'
* // results[1].error = 'bad stuff happened'
* // results[2].value = 'two'
* });
*/
function reflect(fn) {
return initialParams(function reflectOn(args, reflectCallback) {
args.push(rest(function callback(err, cbArgs) {
if (err) {
reflectCallback(null, {
error: err
});
} else {
var value = null;
if (cbArgs.length === 1) {
value = cbArgs[0];
} else if (cbArgs.length > 1) {
value = cbArgs;
}
reflectCallback(null, {
value: value
});
}
}));
return fn.apply(this, args);
});
}
function reject$1(eachfn, arr, iteratee, callback) {
_filter(eachfn, arr, function (value, cb) {
iteratee(value, function (err, v) {
if (err) {
cb(err);
} else {
cb(null, !v);
}
});
}, callback);
}
/**
* The same as `reject` but runs a maximum of `limit` async operations at a
* time.
*
* @name rejectLimit
* @static
* @memberOf async
* @see async.reject
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
*/
var rejectLimit = doParallelLimit(reject$1);
/**
* The opposite of `filter`. Removes values that pass an `async` truth test.
*
* @name reject
* @static
* @memberOf async
* @see async.filter
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @example
*
* async.reject(['file1','file2','file3'], function(filePath, callback) {
* fs.access(filePath, function(err) {
* callback(null, !err)
* });
* }, function(err, results) {
* // results now equals an array of missing files
* createFiles(results);
* });
*/
var reject = doLimit(rejectLimit, Infinity);
/**
* A helper function that wraps an array of functions with reflect.
*
* @name reflectAll
* @static
* @memberOf async
* @see async.reflect
* @category Util
* @param {Array} tasks - The array of functions to wrap in `async.reflect`.
* @returns {Array} Returns an array of functions, each function wrapped in
* `async.reflect`
* @example
*
* let tasks = [
* function(callback) {
* setTimeout(function() {
* callback(null, 'one');
* }, 200);
* },
* function(callback) {
* // do some more stuff but error ...
* callback(new Error('bad stuff happened'));
* },
* function(callback) {
* setTimeout(function() {
* callback(null, 'two');
* }, 100);
* }
* ];
*
* async.parallel(async.reflectAll(tasks),
* // optional callback
* function(err, results) {
* // values
* // results[0].value = 'one'
* // results[1].error = Error('bad stuff happened')
* // results[2].value = 'two'
* });
*/
function reflectAll(tasks) {
return tasks.map(reflect);
}
/**
* The same as `reject` but runs only a single async operation at a time.
*
* @name rejectSeries
* @static
* @memberOf async
* @see async.reject
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in `coll`.
* The `iteratee` is passed a `callback(err, truthValue)`, which must be called
* with a boolean argument once it has completed. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
*/
var rejectSeries = doLimit(rejectLimit, 1);
/**
* Run the functions in the `tasks` collection in series, each one running once
* the previous function has completed. If any functions in the series pass an
* error to its callback, no more functions are run, and `callback` is
* immediately called with the value of the error. Otherwise, `callback`
* receives an array of results when `tasks` have completed.
*
* It is also possible to use an object instead of an array. Each property will
* be run as a function, and the results will be passed to the final `callback`
* as an object instead of an array. This can be a more readable way of handling
* results from {@link async.series}.
*
* **Note** that while many implementations preserve the order of object
* properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
* explicitly states that
*
* > The mechanics and order of enumerating the properties is not specified.
*
* So if you rely on the order in which your series of functions are executed,
* and want this to work on all platforms, consider using an array.
*
* @name series
* @static
* @memberOf async
* @category Control Flow
* @param {Array|Object} tasks - A collection containing functions to run, each
* function is passed a `callback(err, result)` it must call on completion with
* an error `err` (which can be `null`) and an optional `result` value.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed. This function gets a results array (or object)
* containing all the result arguments passed to the `task` callbacks. Invoked
* with (err, result).
* @example
* async.series([
* function(callback) {
* // do some stuff ...
* callback(null, 'one');
* },
* function(callback) {
* // do some more stuff ...
* callback(null, 'two');
* }
* ],
* // optional callback
* function(err, results) {
* // results is now equal to ['one', 'two']
* });
*
* async.series({
* one: function(callback) {
* setTimeout(function() {
* callback(null, 1);
* }, 200);
* },
* two: function(callback){
* setTimeout(function() {
* callback(null, 2);
* }, 100);
* }
* }, function(err, results) {
* // results is now equal to: {one: 1, two: 2}
* });
*/
function series(tasks, cb) {
return _parallel(eachOfSeries, tasks, cb);
}
/**
* Attempts to get a successful response from `task` no more than `times` times
* before returning an error. If the task is successful, the `callback` will be
* passed the result of the successful task. If all attempts fail, the callback
* will be passed the error and result (if any) of the final attempt.
*
* @name retry
* @static
* @memberOf async
* @category Control Flow
* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an
* object with `times` and `interval` or a number.
* * `times` - The number of attempts to make before giving up. The default
* is `5`.
* * `interval` - The time to wait between retries, in milliseconds. The
* default is `0`.
* * If `opts` is a number, the number specifies the number of times to retry,
* with the default interval of `0`.
* @param {Function} task - A function which receives two arguments: (1) a
* `callback(err, result)` which must be called when finished, passing `err`
* (which can be `null`) and the `result` of the function's execution, and (2)
* a `results` object, containing the results of the previously executed
* functions (if nested inside another control flow). Invoked with
* (callback, results).
* @param {Function} [callback] - An optional callback which is called when the
* task has succeeded, or after the final failed attempt. It receives the `err`
* and `result` arguments of the last attempt at completing the `task`. Invoked
* with (err, results).
* @example
*
* // The `retry` function can be used as a stand-alone control flow by passing
* // a callback, as shown below:
*
* // try calling apiMethod 3 times
* async.retry(3, apiMethod, function(err, result) {
* // do something with the result
* });
*
* // try calling apiMethod 3 times, waiting 200 ms between each retry
* async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
* // do something with the result
* });
*
* // try calling apiMethod the default 5 times no delay between each retry
* async.retry(apiMethod, function(err, result) {
* // do something with the result
* });
*
* // It can also be embedded within other control flow functions to retry
* // individual methods that are not as reliable, like this:
* async.auto({
* users: api.getUsers.bind(api),
* payments: async.retry(3, api.getPayments.bind(api))
* }, function(err, results) {
* // do something with the results
* });
*/
function retry(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t) {
if (typeof t === 'object') {
acc.times = +t.times || DEFAULT_TIMES;
acc.interval = +t.interval || DEFAULT_INTERVAL;
} else if (typeof t === 'number' || typeof t === 'string') {
acc.times = +t || DEFAULT_TIMES;
} else {
throw new Error("Invalid arguments for async.retry");
}
}
if (arguments.length < 3 && typeof times === 'function') {
callback = task || noop;
task = times;
} else {
parseTimes(opts, times);
callback = callback || noop;
}
if (typeof task !== 'function') {
throw new Error("Invalid arguments for async.retry");
}
var attempts = [];
while (opts.times) {
var isFinalAttempt = !(opts.times -= 1);
attempts.push(retryAttempt(isFinalAttempt));
if (!isFinalAttempt && opts.interval > 0) {
attempts.push(retryInterval(opts.interval));
}
}
series(attempts, function (done, data) {
data = data[data.length - 1];
callback(data.err, data.result);
});
function retryAttempt(isFinalAttempt) {
return function (seriesCallback) {
task(function (err, result) {
seriesCallback(!err || isFinalAttempt, {
err: err,
result: result
});
});
};
}
function retryInterval(interval) {
return function (seriesCallback) {
setTimeout(function () {
seriesCallback(null);
}, interval);
};
}
}
/**
* A close relative of `retry`. This method wraps a task and makes it
* retryable, rather than immediately calling it with retries.
*
* @name retryable
* @static
* @memberOf async
* @see async.retry
* @category Control Flow
* @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
* options, exactly the same as from `retry`
* @param {Function} task - the asynchronous function to wrap
* @returns {Functions} The wrapped function, which when invoked, will retry on
* an error, based on the parameters specified in `opts`.
* @example
*
* async.auto({
* dep1: async.retryable(3, getFromFlakyService),
* process: ["dep1", async.retryable(3, function (results, cb) {
* maybeProcessData(results.dep1, cb);
* })]
* }, callback);
*/
function retryable (opts, task) {
if (!task) {
task = opts;
opts = null;
}
return initialParams(function (args, callback) {
function taskFn(cb) {
task.apply(null, args.concat([cb]));
}
if (opts) retry(opts, taskFn, callback);else retry(taskFn, callback);
});
}
/**
* The same as `some` but runs a maximum of `limit` async operations at a time.
*
* @name someLimit
* @static
* @memberOf async
* @see async.some
* @alias anyLimit
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - A truth test to apply to each item in the array
* in parallel. The iteratee is passed a `callback(err, truthValue)` which must
* be called with a boolean argument once it has completed. Invoked with
* (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
*/
var someLimit = _createTester(eachOfLimit, Boolean, identity);
/**
* Returns `true` if at least one element in the `coll` satisfies an async test.
* If any iteratee call returns `true`, the main `callback` is immediately
* called.
*
* @name some
* @static
* @memberOf async
* @alias any
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in the array
* in parallel. The iteratee is passed a `callback(err, truthValue)` which must
* be called with a boolean argument once it has completed. Invoked with
* (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
* @example
*
* async.some(['file1','file2','file3'], function(filePath, callback) {
* fs.access(filePath, function(err) {
* callback(null, !err)
* });
* }, function(err, result) {
* // if result is true then at least one of the files exists
* });
*/
var some = doLimit(someLimit, Infinity);
/**
* The same as `some` but runs only a single async operation at a time.
*
* @name someSeries
* @static
* @memberOf async
* @see async.some
* @alias anySeries
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A truth test to apply to each item in the array
* in parallel. The iteratee is passed a `callback(err, truthValue)` which must
* be called with a boolean argument once it has completed. Invoked with
* (item, callback).
* @param {Function} [callback] - A callback which is called as soon as any
* iteratee returns `true`, or after all the iteratee functions have finished.
* Result will be either `true` or `false` depending on the values of the async
* tests. Invoked with (err, result).
*/
var someSeries = doLimit(someLimit, 1);
/**
* Sorts a list by the results of running each `coll` value through an async
* `iteratee`.
*
* @name sortBy
* @static
* @memberOf async
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {Function} iteratee - A function to apply to each item in `coll`.
* The iteratee is passed a `callback(err, sortValue)` which must be called once
* it has completed with an error (which can be `null`) and a value to use as
* the sort criteria. Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished, or an error occurs. Results is the items
* from the original `coll` sorted by the values returned by the `iteratee`
* calls. Invoked with (err, results).
* @example
*
* async.sortBy(['file1','file2','file3'], function(file, callback) {
* fs.stat(file, function(err, stats) {
* callback(err, stats.mtime);
* });
* }, function(err, results) {
* // results is now the original array of files sorted by
* // modified date
* });
*
* // By modifying the callback parameter the
* // sorting order can be influenced:
*
* // ascending order
* async.sortBy([1,9,3,5], function(x, callback) {
* callback(null, x);
* }, function(err,result) {
* // result callback
* });
*
* // descending order
* async.sortBy([1,9,3,5], function(x, callback) {
* callback(null, x*-1); //<- x*-1 instead of x, turns the order around
* }, function(err,result) {
* // result callback
* });
*/
function sortBy(arr, iteratee, cb) {
map(arr, function (x, cb) {
iteratee(x, function (err, criteria) {
if (err) return cb(err);
cb(null, { value: x, criteria: criteria });
});
}, function (err, results) {
if (err) return cb(err);
cb(null, arrayMap(results.sort(comparator), baseProperty('value')));
});
function comparator(left, right) {
var a = left.criteria,
b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
}
/**
* Sets a time limit on an asynchronous function. If the function does not call
* its callback within the specified miliseconds, it will be called with a
* timeout error. The code property for the error object will be `'ETIMEDOUT'`.
*
* @name timeout
* @static
* @memberOf async
* @category Util
* @param {Function} function - The asynchronous function you want to set the
* time limit.
* @param {number} miliseconds - The specified time limit.
* @param {*} [info] - Any variable you want attached (`string`, `object`, etc)
* to timeout Error for more information..
* @returns {Function} Returns a wrapped function that can be used with any of
* the control flow functions.
* @example
*
* async.timeout(function(callback) {
* doAsyncTask(callback);
* }, 1000);
*/
function timeout(asyncFn, miliseconds, info) {
var originalCallback, timer;
var timedOut = false;
function injectedCallback() {
if (!timedOut) {
originalCallback.apply(null, arguments);
clearTimeout(timer);
}
}
function timeoutCallback() {
var name = asyncFn.name || 'anonymous';
var error = new Error('Callback function "' + name + '" timed out.');
error.code = 'ETIMEDOUT';
if (info) {
error.info = info;
}
timedOut = true;
originalCallback(error);
}
return initialParams(function (args, origCallback) {
originalCallback = origCallback;
// setup timer and call original function
timer = setTimeout(timeoutCallback, miliseconds);
asyncFn.apply(null, args.concat(injectedCallback));
});
}
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil;
var nativeMax$1 = Math.max;
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments to numbers.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/
function baseRange(start, end, step, fromRight) {
var index = -1,
length = nativeMax$1(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* The same as {@link times} but runs a maximum of `limit` async operations at a
* time.
*
* @name timesLimit
* @static
* @memberOf async
* @see async.times
* @category Control Flow
* @param {number} n - The number of times to run the function.
* @param {number} limit - The maximum number of async operations at a time.
* @param {Function} iteratee - The function to call `n` times. Invoked with the
* iteration index and a callback (n, next).
* @param {Function} callback - see {@link async.map}.
*/
function timeLimit(count, limit, iteratee, cb) {
return mapLimit(baseRange(0, count, 1), limit, iteratee, cb);
}
/**
* Calls the `iteratee` function `n` times, and accumulates results in the same
* manner you would use with {@link async.map}.
*
* @name times
* @static
* @memberOf async
* @see async.map
* @category Control Flow
* @param {number} n - The number of times to run the function.
* @param {Function} iteratee - The function to call `n` times. Invoked with the
* iteration index and a callback (n, next).
* @param {Function} callback - see {@link async.map}.
* @example
*
* // Pretend this is some complicated async factory
* var createUser = function(id, callback) {
* callback(null, {
* id: 'user' + id
* });
* };
*
* // generate 5 users
* async.times(5, function(n, next) {
* createUser(n, function(err, user) {
* next(err, user);
* });
* }, function(err, users) {
* // we should now have 5 users
* });
*/
var times = doLimit(timeLimit, Infinity);
/**
* The same as {@link async.times} but runs only a single async operation at a time.
*
* @name timesSeries
* @static
* @memberOf async
* @see async.times
* @category Control Flow
* @param {number} n - The number of times to run the function.
* @param {Function} iteratee - The function to call `n` times. Invoked with the
* iteration index and a callback (n, next).
* @param {Function} callback - see {@link async.map}.
*/
var timesSeries = doLimit(timeLimit, 1);
/**
* A relative of `reduce`. Takes an Object or Array, and iterates over each
* element in series, each step potentially mutating an `accumulator` value.
* The type of the accumulator defaults to the type of collection passed in.
*
* @name transform
* @static
* @memberOf async
* @category Collection
* @param {Array|Object} coll - A collection to iterate over.
* @param {*} [accumulator] - The initial state of the transform. If omitted,
* it will default to an empty Object or Array, depending on the type of `coll`
* @param {Function} iteratee - A function applied to each item in the
* collection that potentially modifies the accumulator. The `iteratee` is
* passed a `callback(err)` which accepts an optional error as its first
* argument. If an error is passed to the callback, the transform is stopped
* and the main `callback` is immediately called with the error.
* Invoked with (accumulator, item, key, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Result is the transformed accumulator.
* Invoked with (err, result).
* @example
*
* async.transform([1,2,3], function(acc, item, index, callback) {
* // pointless async:
* process.nextTick(function() {
* acc.push(item * 2)
* callback(null)
* });
* }, function(err, result) {
* // result is now equal to [2, 4, 6]
* });
*
* @example
*
* async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {
* setImmediate(function () {
* obj[key] = val * 2;
* callback();
* })
* }, function (err, result) {
* // result is equal to {a: 2, b: 4, c: 6}
* })
*/
function transform(arr, acc, iteratee, callback) {
if (arguments.length === 3) {
callback = iteratee;
iteratee = acc;
acc = isArray(arr) ? [] : {};
}
eachOf(arr, function (v, k, cb) {
iteratee(acc, v, k, cb);
}, function (err) {
callback(err, acc);
});
}
/**
* Undoes a {@link async.memoize}d function, reverting it to the original,
* unmemoized form. Handy for testing.
*
* @name unmemoize
* @static
* @memberOf async
* @see async.memoize
* @category Util
* @param {Function} fn - the memoized function
*/
function unmemoize(fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
}
/**
* Repeatedly call `fn` until `test` returns `true`. Calls `callback` when
* stopped, or an error occurs. `callback` will be passed an error and any
* arguments passed to the final `fn`'s callback.
*
* The inverse of {@link async.whilst}.
*
* @name until
* @static
* @memberOf async
* @see async.whilst
* @category Control Flow
* @param {Function} test - synchronous truth test to perform before each
* execution of `fn`. Invoked with ().
* @param {Function} fn - A function which is called each time `test` fails.
* The function is passed a `callback(err)`, which must be called once it has
* completed with an optional `err` argument. Invoked with (callback).
* @param {Function} [callback] - A callback which is called after the test
* function has passed and repeated execution of `fn` has stopped. `callback`
* will be passed an error and any arguments passed to the final `fn`'s
* callback. Invoked with (err, [results]);
*/
function until(test, iteratee, cb) {
return whilst(function () {
return !test.apply(this, arguments);
}, iteratee, cb);
}
/**
* Runs the `tasks` array of functions in series, each passing their results to
* the next in the array. However, if any of the `tasks` pass an error to their
* own callback, the next function is not executed, and the main `callback` is
* immediately called with the error.
*
* @name waterfall
* @static
* @memberOf async
* @category Control Flow
* @param {Array} tasks - An array of functions to run, each function is passed
* a `callback(err, result1, result2, ...)` it must call on completion. The
* first argument is an error (which can be `null`) and any further arguments
* will be passed as arguments in order to the next task.
* @param {Function} [callback] - An optional callback to run once all the
* functions have completed. This will be passed the results of the last task's
* callback. Invoked with (err, [results]).
* @example
*
* async.waterfall([
* function(callback) {
* callback(null, 'one', 'two');
* },
* function(arg1, arg2, callback) {
* // arg1 now equals 'one' and arg2 now equals 'two'
* callback(null, 'three');
* },
* function(arg1, callback) {
* // arg1 now equals 'three'
* callback(null, 'done');
* }
* ], function (err, result) {
* // result now equals 'done'
* });
*
* // Or, with named functions:
* async.waterfall([
* myFirstFunction,
* mySecondFunction,
* myLastFunction,
* ], function (err, result) {
* // result now equals 'done'
* });
* function myFirstFunction(callback) {
* callback(null, 'one', 'two');
* }
* function mySecondFunction(arg1, arg2, callback) {
* // arg1 now equals 'one' and arg2 now equals 'two'
* callback(null, 'three');
* }
* function myLastFunction(arg1, callback) {
* // arg1 now equals 'three'
* callback(null, 'done');
* }
*/
function waterfall (tasks, cb) {
cb = once(cb || noop);
if (!isArray(tasks)) return cb(new Error('First argument to waterfall must be an array of functions'));
if (!tasks.length) return cb();
var taskIndex = 0;
function nextTask(args) {
if (taskIndex === tasks.length) {
return cb.apply(null, [null].concat(args));
}
var taskCallback = onlyOnce(rest(function (err, args) {
if (err) {
return cb.apply(null, [err].concat(args));
}
nextTask(args);
}));
args.push(taskCallback);
var task = tasks[taskIndex++];
task.apply(null, args);
}
nextTask([]);
}
var index = {
applyEach: applyEach,
applyEachSeries: applyEachSeries,
apply: apply$1,
asyncify: asyncify,
auto: auto,
autoInject: autoInject,
cargo: cargo,
compose: compose,
concat: concat,
concatSeries: concatSeries,
constant: constant,
detect: detect,
detectLimit: detectLimit,
detectSeries: detectSeries,
dir: dir,
doDuring: doDuring,
doUntil: doUntil,
doWhilst: doWhilst,
during: during,
each: each,
eachLimit: eachLimit,
eachOf: eachOf,
eachOfLimit: eachOfLimit,
eachOfSeries: eachOfSeries,
eachSeries: eachSeries,
ensureAsync: ensureAsync,
every: every,
everyLimit: everyLimit,
everySeries: everySeries,
filter: filter,
filterLimit: filterLimit,
filterSeries: filterSeries,
forever: forever,
iterator: iterator$1,
log: log,
map: map,
mapLimit: mapLimit,
mapSeries: mapSeries,
memoize: memoize$1,
nextTick: setImmediate$1,
parallel: parallel,
parallelLimit: parallelLimit,
priorityQueue: priorityQueue,
queue: queue$1,
race: race,
reduce: reduce,
reduceRight: reduceRight,
reflect: reflect,
reflectAll: reflectAll,
reject: reject,
rejectLimit: rejectLimit,
rejectSeries: rejectSeries,
retry: retry,
retryable: retryable,
seq: seq,
series: series,
setImmediate: setImmediate$1,
some: some,
someLimit: someLimit,
someSeries: someSeries,
sortBy: sortBy,
timeout: timeout,
times: times,
timesLimit: timeLimit,
timesSeries: timesSeries,
transform: transform,
unmemoize: unmemoize,
until: until,
waterfall: waterfall,
whilst: whilst,
// aliases
all: every,
any: some,
forEach: each,
forEachSeries: eachSeries,
forEachLimit: eachLimit,
forEachOf: eachOf,
forEachOfSeries: eachOfSeries,
forEachOfLimit: eachOfLimit,
inject: reduce,
foldl: reduce,
foldr: reduceRight,
select: filter,
selectLimit: filterLimit,
selectSeries: filterSeries,
wrapSync: asyncify
};
exports['default'] = index;
exports.applyEach = applyEach;
exports.applyEachSeries = applyEachSeries;
exports.apply = apply$1;
exports.asyncify = asyncify;
exports.auto = auto;
exports.autoInject = autoInject;
exports.cargo = cargo;
exports.compose = compose;
exports.concat = concat;
exports.concatSeries = concatSeries;
exports.constant = constant;
exports.detect = detect;
exports.detectLimit = detectLimit;
exports.detectSeries = detectSeries;
exports.dir = dir;
exports.doDuring = doDuring;
exports.doUntil = doUntil;
exports.doWhilst = doWhilst;
exports.during = during;
exports.each = each;
exports.eachLimit = eachLimit;
exports.eachOf = eachOf;
exports.eachOfLimit = eachOfLimit;
exports.eachOfSeries = eachOfSeries;
exports.eachSeries = eachSeries;
exports.ensureAsync = ensureAsync;
exports.every = every;
exports.everyLimit = everyLimit;
exports.everySeries = everySeries;
exports.filter = filter;
exports.filterLimit = filterLimit;
exports.filterSeries = filterSeries;
exports.forever = forever;
exports.iterator = iterator$1;
exports.log = log;
exports.map = map;
exports.mapLimit = mapLimit;
exports.mapSeries = mapSeries;
exports.memoize = memoize$1;
exports.nextTick = setImmediate$1;
exports.parallel = parallel;
exports.parallelLimit = parallelLimit;
exports.priorityQueue = priorityQueue;
exports.queue = queue$1;
exports.race = race;
exports.reduce = reduce;
exports.reduceRight = reduceRight;
exports.reflect = reflect;
exports.reflectAll = reflectAll;
exports.reject = reject;
exports.rejectLimit = rejectLimit;
exports.rejectSeries = rejectSeries;
exports.retry = retry;
exports.retryable = retryable;
exports.seq = seq;
exports.series = series;
exports.setImmediate = setImmediate$1;
exports.some = some;
exports.someLimit = someLimit;
exports.someSeries = someSeries;
exports.sortBy = sortBy;
exports.timeout = timeout;
exports.times = times;
exports.timesLimit = timeLimit;
exports.timesSeries = timesSeries;
exports.transform = transform;
exports.unmemoize = unmemoize;
exports.until = until;
exports.waterfall = waterfall;
exports.whilst = whilst;
exports.all = every;
exports.allLimit = everyLimit;
exports.allSeries = everySeries;
exports.any = some;
exports.anyLimit = someLimit;
exports.anySeries = someSeries;
exports.find = detect;
exports.findLimit = detectLimit;
exports.findSeries = detectSeries;
exports.forEach = each;
exports.forEachSeries = eachSeries;
exports.forEachLimit = eachLimit;
exports.forEachOf = eachOf;
exports.forEachOfSeries = eachOfSeries;
exports.forEachOfLimit = eachOfLimit;
exports.inject = reduce;
exports.foldl = reduce;
exports.foldr = reduceRight;
exports.select = filter;
exports.selectLimit = filterLimit;
exports.selectSeries = filterSeries;
exports.wrapSync = asyncify;
})); |
/**
* Copyright (c) 2012, 2013 Taye Adeyemi
* Open source under the MIT License.
* https://raw.github.com/taye/interact.js/master/LICENSE
*
* @file
* @version 1.0.1
* @author Taye Adeyemi <dev@taye.me>
*/
window.interact = (function () {
'use strict';
var document = window.document,
console = window.console,
SVGElement = window.SVGElement || blank,
SVGSVGElement = window.SVGSVGElement || blank,
SVGElementInstance = window.SVGElementInstance || blank,
HTMLElement = window.HTMLElement || window.Element,
// Previous interact move event pointer position
prevX = 0,
prevY = 0,
prevClientX = 0,
prevClientY = 0,
// Previous interact start event pointer position
x0 = 0,
y0 = 0,
clientX0 = 0,
clientY0 = 0,
gesture = {
start: { x: 0, y: 0 },
startDistance: 0, // distance between two touches of touchStart
prevDistance : 0,
distance : 0,
scale: 1, // gesture.distance / gesture.startDistance
startAngle: 0, // angle of line joining two touches
prevAngle : 0 // angle of the previous gesture event
},
interactables = [], // all set interactables
dropzones = [], // all dropzone element interactables
elements = [], // all elements that have been made interactable
selectors = {}, // all css selector interactables
selectorDZs = [], // all dropzone selector interactables
matches = [], // all selectors that are matched by target element
target = null, // current interactable being interacted with
dropTarget = null, // the dropzone a drag target might be dropped into
prevDropTarget = null, // the dropzone that was recently dragged away from
/**
* @lends IOptions.prototype
*/
defaultOptions = {
draggable : false,
dropzone : false,
resizeable : false,
squareResize: false,
gestureable : false,
styleCursor : true,
// aww snap
snap: {
mode : 'grid',
range : Infinity,
grid : { x: 100, y: 100 },
gridOffset : { x: 0, y: 0 },
anchors : [],
paths : [],
arrayTypes : /^anchors$|^paths$/,
objectTypes : /^grid$|^gridOffset$/,
stringTypes : /^mode$/,
numberTypes : /^range$/
},
snapEnabled : false,
autoScroll: {
container : window, // the item that is scrolled
margin : 60,
interval : 20, // pause in ms between each scroll pulse
distance : 10, // the distance in x and y that the page is scrolled
elementTypes: /^container$/,
numberTypes : /^range$|^interval$|^distance$/
},
autoScrollEnabled: false,
origin : { x: 0, y: 0 },
deltaSource : 'page'
},
snapStatus = {
locked : false,
x : 0,
y : 0,
dx : 0,
dy : 0,
realX : 0,
realY : 0,
anchors: [],
paths : []
},
// Things related to autoScroll
autoScroll = {
margin : 60, // page margin in which pointer triggers autoScroll
interval : 20, // pause in ms between each scroll pulse
i : null, // the handle returned by window.setInterval
distance : 10, // the distance in x and y that the page is scrolled
x: 0, // Direction each pulse is to scroll in
y: 0,
// scroll the window by the values in scroll.x/y
scroll: function () {
var container = target.options.autoScroll.container;
if (container === window) {
window.scrollBy(autoScroll.x, autoScroll.y);
}
else if (container) {
container.scrollLeft += autoScroll.x;
container.scrollTop += autoScroll.y;
}
},
edgeMove: function (event) {
if (target && target.options.autoScrollEnabled && (dragging || resizing)) {
var top,
right,
bottom,
left,
options = target.options.autoScroll;
if (options.container === window) {
left = event.clientX < autoScroll.margin;
top = event.clientY < autoScroll.margin;
right = event.clientX > window.innerWidth - autoScroll.margin;
bottom = event.clientY > window.innerHeight - autoScroll.margin;
}
else {
var rect = interact(options.container).getRect();
left = event.clientX < rect.left + autoScroll.margin;
top = event.clientY < rect.top + autoScroll.margin;
right = event.clientX > rect.right - autoScroll.margin;
bottom = event.clientY > rect.bottom - autoScroll.margin;
}
autoScroll.x = autoScroll.distance * (right ? 1: left? -1: 0);
autoScroll.y = autoScroll.distance * (bottom? 1: top? -1: 0);
if (!autoScroll.isScrolling) {
// set the autoScroll properties to those of the target
autoScroll.margin = options.margin;
autoScroll.distance = options.distance;
autoScroll.interval = options.interval;
autoScroll.start();
}
}
},
isScrolling: false,
start: function () {
autoScroll.isScrolling = true;
window.clearInterval(autoScroll.i);
autoScroll.i = window.setInterval(autoScroll.scroll, autoScroll.interval);
},
stop: function () {
window.clearInterval(autoScroll.i);
autoScroll.isScrolling = false;
}
},
// Does the browser support touch input?
supportsTouch = 'createTouch' in document,
// Less Precision with touch input
margin = supportsTouch? 20: 10,
pointerIsDown = false,
pointerWasMoved = false,
imPropStopped = false,
gesturing = false,
dragging = false,
dynamicDrop = false,
resizing = false,
resizeAxes = 'xy',
// What to do depending on action returned by getAction() of interactable
// Dictates what styles should be used and what pointerMove event Listner
// is to be added after pointerDown
actions = {
drag: {
cursor : 'move',
moveListener: dragMove
},
resizex: {
cursor : 'e-resize',
moveListener: resizeMove
},
resizey: {
cursor : 's-resize',
moveListener: resizeMove
},
resizexy: {
cursor : 'se-resize',
moveListener: resizeMove
},
gesture: {
cursor : '',
moveListener: gestureMove
}
},
actionIsEnabled = {
drag : true,
resize : true,
gesture: true
},
// Action that's ready to be fired on next move event
prepared = null,
// because Webkit and Opera still use 'mousewheel' event type
wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel',
eventTypes = [
'resizestart',
'resizemove',
'resizeend',
'dragstart',
'dragmove',
'dragend',
'dragenter',
'dragleave',
'drop',
'gesturestart',
'gesturemove',
'gestureend',
'click'
],
globalEvents = {},
fireStates = {
onevent : 0,
directBind: 1,
globalBind: 2
},
// Opera Mobile must be handled differently
isOperaMobile = navigator.appName == 'Opera' &&
supportsTouch &&
navigator.userAgent.match('Presto'),
// prefix matchesSelector
matchesSelector = 'matchesSelector' in Element.prototype?
'matchesSelector': 'webkitMatchesSelector' in Element.prototype?
'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype?
'mozMatchesSelector': 'oMatchesSelector' in Element.prototype?
'oMatchesSelector': 'msMatchesSelector',
// will be polyfill function if browser is IE8
IE8MatchesSelector,
// used for adding event listeners to window and document
windowTarget = {
_element: window,
events : {}
},
docTarget = {
_element: document,
events : {}
},
parentWindowTarget = {
_element: window.parent,
events : {}
},
parentDocTarget = {
_element: window.parent.document,
events : {}
},
// Events wrapper
events = (function () {
/* jshint -W001 */ // ignore warning about setting IE8 Event#hasOwnProperty
var Event = window.Event,
useAttachEvent = 'attachEvent' in window && !('addEventListener' in window),
addEvent = !useAttachEvent? 'addEventListener': 'attachEvent',
removeEvent = !useAttachEvent? 'removeEventListener': 'detachEvent',
on = useAttachEvent? 'on': '',
elements = [],
targets = [];
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)?
Math.ceil(from):
Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
if (!('stopPropagation' in Event.prototype)) {
Event.prototype.stopPropagation = function () {
this.cancelBubble = true;
};
Event.prototype.stopImmediatePropagation = function () {
this.cancelBubble = true;
this.immediatePropagationStopped = true;
};
}
if (!('preventDefault' in Event.prototype)) {
Event.prototype.preventDefault = function () {
this.returnValue = false;
};
}
if (!('hasOwnProperty' in Event.prototype)) {
Event.prototype.hasOwnProperty = Object.prototype.hasOwnProperty;
}
function add (element, type, listener, useCapture) {
var target = targets[elements.indexOf(element)];
if (!target) {
target = {
events: {},
typeCount: 0
};
elements.push(element);
targets.push(target);
}
if (!(type in target.events)) {
target.events[type] = [];
target.typeCount++;
}
if (target.events[type].indexOf(listener) === -1) {
var ret;
if (useAttachEvent) {
ret = element[addEvent](on + type, function (event) {
if (!event.immediatePropagationStopped) {
event.target = event.srcElement;
event.currentTarget = element;
if (/mouse|click/.test(event.type)) {
event.pageX = event.clientX + document.documentElement.scrollLeft;
event.pageY = event.clientY + document.documentElement.scrollTop;
}
listener(event);
}
}, listener, useCapture || false);
}
else {
ret = element[addEvent](type, listener, useCapture || false);
}
target.events[type].push(listener);
return ret;
}
}
function remove (element, type, listener, useCapture) {
var i,
target = targets[elements.indexOf(element)];
if (!target || !target.events) {
return;
}
if (type === 'all') {
for (type in target.events) {
if (target.events.hasOwnProperty(type)) {
remove(element, type, 'all');
}
}
return;
}
if (target.events[type]) {
var len = target.events[type].length;
if (listener === 'all') {
for (i = 0; i < len; i++) {
element[removeEvent](on + type, target.events[type][i], useCapture || false);
}
target.events[type] = null;
target.typeCount--;
} else {
for (i = 0; i < len; i++) {
if (target.events[type][i] === listener) {
element[removeEvent](on + type, target.events[type][i], useCapture || false);
target.events[type].splice(i, 1);
break;
}
}
}
if (target.events[type] && target.events[type].length === 0) {
target.events[type] = null;
target.typeCount--;
}
}
if (!target.typeCount) {
targets.splice(targets.indexOf(target), 1);
elements.splice(elements.indexOf(element), 1);
}
}
return {
add: function (target, type, listener, useCapture) {
add(target._element, type, listener, useCapture);
},
remove: function (target, type, listener, useCapture) {
remove(target._element, type, listener, useCapture);
},
addToElement: add,
removeFromElement: remove,
useAttachEvent: useAttachEvent
};
}());
function blank () {}
function setPrevXY (event) {
prevX = event.pageX;
prevY = event.pageY;
prevClientX = event.clientX;
prevClientY = event.clientY;
}
// Get specified X/Y coords for mouse or event.touches[0]
function getXY (type, event) {
var touch,
x,
y;
type = type || 'page';
if (event.touches) {
touch = (event.touches.length)?
event.touches[0]:
event.changedTouches[0];
x = touch[type + 'X'];
y = touch[type + 'Y'];
}
else {
x = event[type + 'X'];
y = event[type + 'Y'];
}
return {
x: x,
y: y
};
}
function getPageXY (event) {
// Opera Mobile handles the viewport and scrolling oddly
if (isOperaMobile) {
var page = getXY('screen', event);
page.x += window.scrollX;
page.y += window.scrollY;
return page;
}
return getXY('page', event);
}
function getClientXY (event) {
// Opera Mobile handles the viewport and scrolling oddly
return getXY(isOperaMobile? 'screen': 'client', event);
}
function getScrollXY () {
return {
x: window.scrollX || document.documentElement.scrollLeft,
y: window.scrollY || document.documentElement.scrollTop
};
}
function touchAverage (event) {
var i,
touches = event.touches,
pageX = 0,
pageY = 0,
clientX = 0,
clientY = 0;
for (i = 0; i < touches.length; i++) {
pageX += touches[i].pageX / touches.length;
pageY += touches[i].pageY / touches.length;
clientX += touches[i].clientX / touches.length;
clientY += touches[i].clientY / touches.length;
}
return {
pageX: pageX,
pageY: pageY,
clientX: clientX,
clientY: clientY
};
}
function getTouchBBox (event) {
if (!event.touches.length) {
return;
}
var i,
touches = event.touches,
minX = event.touches[0].pageX,
minY = event.touches[0].pageY,
maxX = minX,
maxY = minY;
for (i = 1; i < touches.length; i++) {
minX = minX > event.touches[i].pageX?
minX:
event.touches[i].pageX;
minY = minX > event.touches[i].pageX?
minY:
event.touches[i].pageY;
}
return {
left: minX,
top: minY,
width: maxX - minX,
height: maxY - minY
};
}
function touchDistance (event) {
var deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
dx = event.touches[0][sourceX],
dy = event.touches[0][sourceX];
if (event.type === 'touchend' && event.touches.length === 1) {
dx -= event.changedTouches[0][sourceX];
dy -= event.changedTouches[0][sourceX];
}
else {
dx -= event.touches[1][sourceX];
dy -= event.touches[1][sourceX];
}
return Math.sqrt(dx * dx + dy * dy);
}
function touchAngle (event) {
var deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
dx = event.touches[0][sourceX],
dy = event.touches[0][sourceX];
if (event.type === 'touchend' && event.touches.length === 1) {
dx -= event.changedTouches[0][sourceX];
dy -= event.changedTouches[0][sourceX];
}
else {
dx -= event.touches[1][sourceX];
dy -= event.touches[1][sourceX];
}
return 180 * -Math.atan(dy / dx) / Math.PI;
}
function calcRects (interactableList) {
for (var i = 0, len = interactableList.length; i < len; i++) {
interactableList[i].rect = interactableList[i].getRect();
}
}
// Test for the element that's "above" all other qualifiers
function resolveDrops (elements) {
if (elements.length) {
var dropzone,
deepestZone = elements[0],
parent,
deepestZoneParents = [],
dropzoneParents = [],
child,
i,
n;
for (i = 1; i < elements.length; i++) {
dropzone = elements[i];
if (!deepestZoneParents.length) {
parent = deepestZone;
while (parent.parentNode !== document) {
deepestZoneParents.unshift(parent);
parent = parent.parentNode;
}
}
// if this element is an svg element and the current deepest is
// an HTMLElement
if (deepestZone instanceof HTMLElement &&
dropzone instanceof SVGElement &&
!(dropzone instanceof SVGSVGElement)) {
if (dropzone ===
deepestZone.parentNode) {
continue;
}
parent = dropzone.ownerSVGElement;
}
else {
parent = dropzone;
}
dropzoneParents = [];
while (parent.parentNode !== document) {
dropzoneParents.unshift(parent);
parent = parent.parentNode;
}
// get (position of last common ancestor) + 1
n = 0;
while(dropzoneParents[n] &&
dropzoneParents[n] === deepestZoneParents[n]) {
n++;
}
var parents = [
dropzoneParents[n - 1],
dropzoneParents[n],
deepestZoneParents[n]
];
child = parents[0].lastChild;
while (child) {
if (child === parents[1]) {
deepestZone = dropzone;
deepestZoneParents = [];
break;
}
else if (child === parents[2]) {
break;
}
child = child.previousSibling;
}
}
return {
element: deepestZone,
index: elements.indexOf(deepestZone)
};
}
}
function getDrop (event, draggable) {
if (dropzones.length || selectorDZs.length) {
var i,
drops = [],
elements = [],
selectorDrops = [],
selectorElements = [],
drop;
// collect all element dropzones that qualify for a drop
for (i = 0; i < dropzones.length; i++) {
if (dropzones[i].dropCheck(event)) {
drops.push(dropzones[i]);
elements.push(dropzones[i]._element);
}
}
// get the most apprpriate dropzone based on DOM depth and order
drop = resolveDrops(elements);
dropTarget = drop? dropzones[drop.index]: null;
if (selectorDZs.length) {
var draggableElement = target._element;
for (i = 0; i < selectorDZs.length; i++) {
var selector = selectorDZs[i],
nodeList = document.querySelectorAll(selector.selector);
for (var j = 0, len = nodeList.length; j < len; j++) {
selector._element = nodeList[j];
selector.rect = selector.getRect();
if (selector._element !== draggableElement
&& elements.indexOf(selector._element) === -1
&& selectorElements.indexOf(selector._element === -1)
&& selector.dropCheck(event)) {
selectorDrops.push(selector);
selectorElements.push(selector._element);
}
}
}
if (selectorElements.length) {
if (dropTarget) {
selectorDrops.push(dropTarget);
selectorElements.push(dropTarget._element);
}
drop = resolveDrops(selectorElements);
if (drop) {
dropTarget = selectorDrops[drop.index];
if (dropTarget.selector) {
dropTarget._element = selectorElements[drop.index];
}
}
}
}
return dropTarget;
}
}
/**
* Constructor of interact action event objects
* @event
*/
function InteractEvent (event, action, phase, element, related) {
var client,
page,
deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
options = target? target.options: defaultOptions;
element = element || target._element;
if (action === 'gesture') {
var average = touchAverage(event);
page = { x: (average.pageX - options.origin.x), y: (average.pageY - options.origin.y) };
client = { x: (average.clientX - options.origin.x), y: (average.clientY - options.origin.y) };
}
else {
client = getClientXY(event);
page = getPageXY(event);
page.x -= options.origin.x;
page.y -= options.origin.y;
if (target.options.snapEnabled) {
var snap = options.snap;
this.snap = {
mode : snap.mode,
anchors: snapStatus.anchors,
range : snapStatus.range,
locked : snapStatus.locked,
x : snapStatus.x,
y : snapStatus.y,
realX : snapStatus.realX,
realY : snapStatus.realY,
dx : snapStatus.dx,
dy : snapStatus.dy
};
if (snapStatus.locked) {
if (snap.mode === 'path') {
if (snapStatus.xInRange) {
page.x += snapStatus.dx;
client.x += snapStatus.dx;
}
if (snapStatus.yInRange) {
page.y += snapStatus.dy;
client.y += snapStatus.dy;
}
}
else {
page.x += snapStatus.dx;
page.y += snapStatus.dy;
client.x += snapStatus.dx;
client.y += snapStatus.dy;
}
}
}
}
this.x0 = x0;
this.y0 = y0;
this.clientX0 = clientX0;
this.clientY0 = clientY0;
this.pageX = page.x;
this.pageY = page.y;
this.clientX = client.x;
this.clientY = client.y;
this.ctrlKey = event.ctrlKey;
this.altKey = event.altKey;
this.shiftKey = event.shiftKey;
this.metaKey = event.metaKey;
this.button = event.button;
this.target = element;
this.timeStamp = new Date().getTime();
this.type = action + (phase || '');
if (related) {
this.relatedTarget = related;
}
// start/end event dx, dy is difference between start and current points
if (phase === 'start' || phase === 'end' || action === 'drop') {
if (deltaSource === 'client') {
this.dx = client.x - x0;
this.dy = client.y - y0;
}
else {
this.dx = page.x - x0;
this.dy = page.y - y0;
}
}
else {
if (deltaSource === 'client') {
this.dx = client.x - prevClientX;
this.dy = client.y - prevClientY;
}
else {
this.dx = page.x - prevX;
this.dy = page.y - prevY;
}
}
if (action === 'resize') {
if (options.squareResize || event.shiftKey) {
if (resizeAxes === 'y') {
this.dx = this.dy;
}
else {
this.dy = this.dx;
}
this.axes = 'xy';
}
else {
this.axes = resizeAxes;
if (resizeAxes === 'x') {
this.dy = 0;
}
else if (resizeAxes === 'y') {
this.dx = 0;
}
}
}
else if (action === 'gesture') {
this.touches = event.touches;
this.distance = touchDistance(event);
this.box = getTouchBBox(event);
this.angle = touchAngle(event);
if (phase === 'start') {
this.scale = 1;
this.ds = 0;
this.rotation = 0;
}
else {
this.scale = this.distance / gesture.startDistance;
if (phase === 'end') {
this.rotation = this.angle - gesture.startAngle;
this.ds = this.scale - 1;
}
else {
this.rotation = this.angle - gesture.prevAngle;
this.ds = this.scale - gesture.prevScale;
}
}
}
}
/**
* @global
*/
InteractEvent.prototype = {
/**
* Does nothing
* @method
*/
preventDefault: blank,
/**
* Stops the event bubbling similar to Event#stopImmediatePropagation
* @method
*/
stopImmediatePropagation: function (event) {
imPropStopped = true;
},
/**
* Stops the event bubbling similar to Event#stopPropagation
* @method
*/
stopPropagation: blank
};
// Check if action is enabled globally and the current target supports it
// If so, return the validated action. Otherwise, return null
function validateAction (action, interactable) {
if (typeof action !== 'string') { return null; }
interactable = interactable || target;
var actionType = action.indexOf('resize') !== -1? 'resize': action,
options = (interactable || target).options;
if (( (actionType === 'resize' && options.resizeable )
|| (action === 'drag' && options.draggable )
|| (action === 'gesture' && options.gestureable))
&& actionIsEnabled[actionType]) {
if (action === 'resize' || action === 'resizeyx') {
action = 'resizexy';
}
return action;
}
return null;
}
function selectorDown (event, forceAction) {
var action;
// do nothing if interacting
if (dragging || resizing || gesturing) {
return;
}
if (matches.length && event.type === 'mousedown') {
action = validateSelector(event, matches);
}
else {
var selector,
element = (event.target instanceof SVGElementInstance
? event.target.correspondingUseElement
: event.target),
elements;
while (element !== document.documentElement && !action) {
matches = [];
for (selector in selectors) {
elements = Element.prototype[matchesSelector] === IE8MatchesSelector?
document.querySelectorAll(selector): undefined;
if (element[matchesSelector](selector, elements)) {
selectors[selector]._element = element;
matches.push(selectors[selector]);
}
}
action = validateSelector(event, matches);
element = element.parentNode;
}
}
if (action) {
pointerIsDown = true;
return pointerDown(event, action);
}
}
// Determine action to be performed on next pointerMove and add appropriate
// style and event Liseners
function pointerDown (event, forceAction) {
// If it is the second touch of a multi-touch gesture, keep the target
// the same if a target was set by the first touch
// Otherwise, set the target if the pointer is not down
if ((event.touches && event.touches.length < 2 && !target)
|| !pointerIsDown) {
var getFrom = events.useAttachEvent? event.currentTarget: this;
target = interactables.get(getFrom);
}
var options = target && target.options;
if (target && !(dragging || resizing || gesturing)) {
var action = validateAction(forceAction || target.getAction(event)),
average,
page,
client;
if (event.touches) {
average = touchAverage(event);
page = {
x: average.pageX,
y: average.pageY
};
client = {
x: average.clientX,
y: average.clientY
};
}
else {
page = getPageXY(event);
client = getClientXY(event);
}
if (!action) {
return event;
}
// Register that the pointer is down after succesfully validating
// action. This way, a new target can be gotten in the next
// downEvent propagation
pointerIsDown = true;
pointerWasMoved = false;
if (options.styleCursor) {
document.documentElement.style.cursor = actions[action].cursor;
}
resizeAxes = action === 'resizexy'?
'xy':
action === 'resizex'?
'x':
action === 'resizey'?
'y':
'';
prepared = action;
x0 = page.x - options.origin.x;
y0 = page.y - options.origin.y;
clientX0 = client.x - options.origin.x;
clientY0 = client.y - options.origin.y;
snapStatus.x = null;
snapStatus.y = null;
event.preventDefault();
}
}
function pointerMove (event) {
if (pointerIsDown) {
if (x0 === prevX && y0 === prevY) {
pointerWasMoved = true;
}
if (prepared && target) {
if (target.options.snapEnabled) {
var snap = target.options.snap,
page = getPageXY(event),
closest,
range,
inRange,
snapChanged,
distX,
distY,
distance,
i, len;
snapStatus.realX = page.x;
snapStatus.realY = page.y;
page.x -= target.options.origin.x;
page.y -= target.options.origin.y;
// change to infinite range when range is negative
if (snap.range < 0) { snap.range = Infinity; }
if (snap.mode === 'anchor' && snap.anchors.length) {
closest = {
anchor: null,
distance: 0,
range: 0,
distX: 0,
distY: 0
};
for (i = 0, len = snap.anchors.length; i < len; i++) {
var anchor = snap.anchors[i];
range = typeof anchor.range === 'number'? anchor.range: snap.range;
distX = anchor.x - page.x;
distY = anchor.y - page.y;
distance = Math.sqrt(distX * distX + distY * distY);
inRange = distance < range;
// Infinite anchors count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.inRange && closest.range !== Infinity) {
inRange = false;
}
if (!closest.anchor || (inRange?
// is the closest anchor in range?
(closest.inRange && range !== Infinity)?
// the pointer is relatively deeper in this anchor
distance / range < closest.distance / closest.range:
//the pointer is closer to this anchor
distance < closest.distance:
// The other is not in range and the pointer is closer to this anchor
(!closest.inRange && distance < closest.distance))) {
if (range === Infinity) {
inRange = true;
}
closest.anchor = anchor;
closest.distance = distance;
closest.range = range;
closest.inRange = inRange;
closest.distX = distX;
closest.distY = distY;
snapStatus.range = range;
}
}
inRange = closest.inRange;
snapChanged = (closest.anchor.x !== snapStatus.x || closest.anchor.y !== snapStatus.y);
snapStatus.x = closest.anchor.x;
snapStatus.y = closest.anchor.y;
snapStatus.dx = closest.distX;
snapStatus.dy = closest.distY;
target.options.snap.anchors.closest = snapStatus.anchors.closest = closest.anchor;
}
else if (snap.mode === 'grid') {
var gridx = Math.round((page.x - snap.gridOffset.x) / snap.grid.x),
gridy = Math.round((page.y - snap.gridOffset.y) / snap.grid.y),
newX = gridx * snap.grid.x + snap.gridOffset.x,
newY = gridy * snap.grid.y + snap.gridOffset.y;
distX = newX - page.x;
distY = newY - page.y;
distance = Math.sqrt(distX * distX + distY * distY);
inRange = distance < snap.range;
snapChanged = (newX !== snapStatus.x || newY !== snapStatus.y);
snapStatus.x = newX;
snapStatus.y = newY;
snapStatus.dx = distX;
snapStatus.dy = distY;
snapStatus.range = snap.range;
}
if (snap.mode === 'path' && snap.paths.length) {
closest = {
path: {},
distX: 0,
distY: 0,
range: 0
};
for (i = 0, len = snap.paths.length; i < len; i++) {
var path = snap.paths[i],
snapToX = false,
snapToY = false,
pathXY = path,
pathX,
pathY;
if (typeof path === 'function') {
pathXY = path(page.x, page.y);
}
if (typeof pathXY.x === 'number') {
pathX = pathXY.x;
snapToX = true;
}
else {
pathX = page.x;
}
if (typeof pathXY.y === 'number') {
pathY = pathXY.y;
snapToY = true;
}
else {
pathY = page.y;
}
range = typeof pathXY.range === 'number'? pathXY.range: snap.range;
distX = pathX - page.x;
distY = pathY - page.y;
var xInRange = Math.abs(distX) < range && snapToX,
yInRange = Math.abs(distY) < range && snapToY;
// Infinite paths count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.xInRange && closest.range !== Infinity) {
xInRange = false;
}
if (!('x' in closest.path) || (xInRange
// is the closest path in range?
? (closest.xInRange && range !== Infinity)
// the pointer is relatively deeper in this path
? distance / range < closest.distX / closest.range
//the pointer is closer to this path
: Math.abs(distX) < Math.abs(closest.distX)
// The other is not in range and the pointer is closer to this path
: (!closest.xInRange && Math.abs(distX) < Math.abs(closest.distX)))) {
if (range === Infinity) {
xInRange = true;
}
closest.path.x = pathX;
closest.distX = distX;
closest.xInRange = xInRange;
closest.range = range;
snapStatus.range = range;
}
// Infinite paths count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.yInRange && closest.range !== Infinity) {
yInRange = false;
}
if (!('y' in closest.path) || (yInRange
// is the closest path in range?
? (closest.yInRange && range !== Infinity)
// the pointer is relatively deeper in this path
? distance / range < closest.distY / closest.range
//the pointer is closer to this path
: Math.abs(distY) < Math.abs(closest.distY)
// The other is not in range and the pointer is closer to this path
: (!closest.yInRange && Math.abs(distY) < Math.abs(closest.distY)))) {
if (range === Infinity) {
yInRange = true;
}
closest.path.y = pathY;
closest.distY = distY;
closest.yInRange = yInRange;
closest.range = range;
snapStatus.range = range;
}
}
inRange = closest.xInRange || closest.yInRange;
if (closest.xInRange && closest.yInRange && (!snapStatus.xInRange || !snapStatus.yInRange)) {
snapChanged = true;
}
else {
snapChanged = (!closest.xInRange || !closest.yInRange || closest.path.x !== snapStatus.x || closest.path.y !== snapStatus.y);
}
snapStatus.x = closest.path.x;
snapStatus.y = closest.path.y;
snapStatus.dx = closest.distX;
snapStatus.dy = closest.distY;
snapStatus.xInRange = closest.xInRange;
snapStatus.yInRange = closest.yInRange;
target.options.snap.paths.closest = snapStatus.paths.closest = closest.path;
}
if ((snapChanged || !snapStatus.locked) && inRange) {
snapStatus.locked = true;
actions[prepared].moveListener(event);
}
else if (snapChanged || !inRange) {
snapStatus.locked = false;
actions[prepared].moveListener(event);
}
}
else {
actions[prepared].moveListener(event);
}
}
}
if (dragging || resizing) {
autoScroll.edgeMove(event);
}
}
function dragMove (event) {
event.preventDefault();
var dragEvent,
dragEnterEvent,
dragLeaveEvent,
dropTarget,
leaveDropTarget;
if (!dragging) {
dragEvent = new InteractEvent(event, 'drag', 'start');
dragging = true;
if (!dynamicDrop) {
calcRects(dropzones);
for (var i = 0; i < selectorDZs.length; i++) {
selectorDZs[i]._elements = document.querySelectorAll(selectorDZs[i].selector);
}
}
}
else {
var draggableElement = target._element,
dropzoneElement = dropTarget? dropTarget._element: null;
dragEvent = new InteractEvent(event, 'drag', 'move');
dropTarget = getDrop(event, target);
// Make sure that the target selector draggable's element is
// restored after dropChecks
target._element = draggableElement;
if (dropTarget !== prevDropTarget) {
// if there was a prevDropTarget, create a dragleave event
if (prevDropTarget) {
dragLeaveEvent = new InteractEvent(event, 'drag', 'leave', dropzoneElement, draggableElement);
dragEvent.dragLeave = prevDropTarget._element;
leaveDropTarget = prevDropTarget;
prevDropTarget = null;
}
// if the dropTarget is not null, create a dragenter event
if (dropTarget) {
dragEnterEvent = new InteractEvent(event, 'drag', 'enter', dropzoneElement, draggableElement);
dragEvent.dragEnter = dropTarget._element;
prevDropTarget = dropTarget;
}
}
}
target.fire(dragEvent);
if (dragLeaveEvent) {
leaveDropTarget.fire(dragLeaveEvent);
}
if (dragEnterEvent) {
dropTarget.fire(dragEnterEvent);
}
setPrevXY(dragEvent);
}
function resizeMove (event) {
event.preventDefault();
var resizeEvent;
if (!resizing) {
resizeEvent = new InteractEvent(event, 'resize', 'start');
target.fire(resizeEvent);
resizing = true;
}
else {
resizeEvent = new InteractEvent(event, 'resize', 'move');
target.fire(resizeEvent);
}
setPrevXY(resizeEvent);
}
function gestureMove (event) {
if (!event.touches || event.touches.length < 2) {
return;
}
event.preventDefault();
var gestureEvent;
if (!gesturing) {
gestureEvent = new InteractEvent(event, 'gesture', 'start');
gestureEvent.ds = 0;
gesture.startDistance = gestureEvent.distance;
gesture.startAngle = gestureEvent.angle;
gesture.scale = 1;
target.fire(gestureEvent);
gesturing = true;
}
else {
gestureEvent = new InteractEvent(event, 'gesture', 'move');
gestureEvent.ds = gestureEvent.scale - gesture.scale;
target.fire(gestureEvent);
}
setPrevXY(gestureEvent);
gesture.prevAngle = gestureEvent.angle;
gesture.prevDistance = gestureEvent.distance;
if (gestureEvent.scale !== Infinity &&
gestureEvent.scale !== null &&
gestureEvent.scale !== undefined &&
!isNaN(gestureEvent.scale)) {
gesture.scale = gestureEvent.scale;
}
}
function validateSelector (event, matches) {
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i],
action = validateAction(match.getAction(event, match), match);
if (action) {
target = match;
return action;
}
}
}
function pointerOver (event) {
if (pointerIsDown || dragging || resizing || gesturing) { return; }
var curMatches = [],
prevTargetElement = target && target._element,
eventTarget = (event.target instanceof SVGElementInstance
? event.target.correspondingUseElement
: event.target);
for (var selector in selectors) {
if (selectors.hasOwnProperty(selector)
&& selectors[selector]
&& eventTarget[matchesSelector](selector)) {
selectors[selector]._element = eventTarget;
curMatches.push(selectors[selector]);
}
}
var elementInteractable = interactables.get(eventTarget),
action = elementInteractable
&& validateAction(
elementInteractable.getAction(event, elementInteractable),
elementInteractable);
if (!elementInteractable || !validateAction(elementInteractable.getAction(event))) {
if (validateSelector(event, curMatches)) {
matches = curMatches;
pointerHover(event, matches);
events.addToElement(eventTarget, 'mousemove', pointerHover);
}
else if (target) {
var prevTargetChildren = prevTargetElement.querySelectorAll('*');
if (Array.prototype.indexOf.call(prevTargetChildren, eventTarget) !== -1) {
// reset the elements of the matches to the old target
for (var i = 0; i < matches.length; i++) {
matches[i]._element = prevTargetElement;
}
pointerHover(event, matches);
events.addToElement(target._element, 'mousemove', pointerHover);
}
else {
target = null;
matches = [];
}
}
}
}
function pointerOut (event) {
// Remove temporary event listeners for selector Interactables
var eventTarget = (event.target instanceof SVGElementInstance
? event.target.correspondingUseElement
: event.target);
if (!interactables.get(eventTarget)) {
events.removeFromElement(eventTarget, pointerHover);
}
if (target && target.options.styleCursor && !(dragging || resizing || gesturing)) {
document.documentElement.style.cursor = '';
}
}
// Check what action would be performed on pointerMove target if a mouse
// button were pressed and change the cursor accordingly
function pointerHover (event, matches) {
if (!(pointerIsDown || dragging || resizing || gesturing)) {
var action;
if (matches) {
action = validateSelector(event, matches);
}
else if (target) {
action = validateAction(target.getAction(event));
}
if (target && target.options.styleCursor) {
if (action) {
document.documentElement.style.cursor = actions[action].cursor;
}
else {
document.documentElement.style.cursor = '';
}
}
}
else {
event.preventDefault();
}
}
// End interact move events and stop auto-scroll
function docPointerUp (event) {
var endEvent;
if (event.touches && event.touches.length >= 2) {
return;
}
if (dragging) {
endEvent = new InteractEvent(event, 'drag', 'end');
var dropEvent,
draggableElement = target._element,
drop = getDrop(event, target),
dropzoneElement = drop? drop._element: null;
// getDrop changes target._element
target._element = draggableElement;
// get the most apprpriate dropzone based on DOM depth and order
if (drop) {
dropEvent = new InteractEvent(event, 'drop', null, dropzoneElement, draggableElement);
endEvent.dropzone = dropzoneElement;
}
// if there was a prevDropTarget (perhaps if for some reason this
// dragend happens without the mouse moving of the previous drop
// target)
else if (prevDropTarget) {
var dragLeaveEvent = new InteractEvent(event, 'drag', 'leave', dropzoneElement, draggableElement);
prevDropTarget.fire(dragLeaveEvent, draggableElement);
endEvent.dragLeave = prevDropTarget._element;
}
target.fire(endEvent);
if (dropEvent) {
dropTarget.fire(dropEvent);
}
}
else if (resizing) {
endEvent = new InteractEvent(event, 'resize', 'end');
target.fire(endEvent);
}
else if (gesturing) {
endEvent = new InteractEvent(event, 'gesture', 'end');
endEvent.ds = endEvent.scale;
target.fire(endEvent);
}
else if ((event.type === 'mouseup' || event.type === 'touchend') && target && pointerIsDown && !pointerWasMoved) {
var click = {};
for (var prop in event) {
if (event.hasOwnProperty(prop)) {
click[prop] = event[prop];
}
}
click.type = 'click';
target.fire(click);
}
interact.stop();
return event;
}
interactables.indexOfElement = dropzones.indexOfElement = function indexOfElement (element) {
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if (interactable.selector === element
|| (!interactable.selector && interactable._element === element)) {
return i;
}
}
return -1;
};
interactables.get = function interactableGet (element) {
if (typeof element === 'string') {
return selectors[element];
}
return this[this.indexOfElement(element)];
};
dropzones.get = function dropzoneGet (element) {
return this[this.indexOfElement(element)];
};
function clearTargets () {
if (!target.selector) {
target = null;
}
dropTarget = prevDropTarget = null;
}
/**
* The properties of this variable can be used to set elements as
* interactables and also to change various settings (see {@link module:interact}).
*
* Calling it as a function and passing an element or a CSS selector string
* returns an Interactable object which has various methods to configure
* it.
*
* @function interact
* @param {Element | string} element The Element to interact with or CSS selector
* @returns {Interactable}
*/
/**
* @exports interact
* @global
*/
function interact (element) {
return interactables.get(element) || new Interactable(element);
}
/**
* A class for easy inheritance and setting of an Interactable's options
*
* @class
*/
function IOptions (options) {
for (var option in defaultOptions) {
if (options.hasOwnProperty(option)
&& typeof options[option] === typeof defaultOptions[option]) {
this[option] = options[option];
}
}
}
/**
* @global
*/
IOptions.prototype = defaultOptions;
/**
* Object type returned by interact(element)
*
* @class Interactable
*/
function Interactable (element, options) {
this._element = element;
this._iEvents = this._iEvents || {};
if (typeof element === 'string') {
// if the selector is invalid,
// an exception will be raised
document.querySelector(element);
selectors[element] = this;
this.selector = element;
}
else {
if(element instanceof Element) {
events.add(this, 'mousemove' , pointerHover);
events.add(this, 'mousedown' , pointerDown );
events.add(this, 'touchmove' , pointerHover);
events.add(this, 'touchstart', pointerDown );
}
elements.push(this);
}
interactables.push(this);
this.set(options);
}
/**
* @global
*/
Interactable.prototype = {
setOnEvents: function (action, phases) {
var start = phases.onstart || phases.onStart,
move = phases.onmove || phases.onMove,
end = phases.onend || phases.onEnd;
action = 'on' + action;
if (typeof start === 'function') { this[action + 'start'] = start; }
if (typeof move === 'function') { this[action + 'move' ] = move ; }
if (typeof end === 'function') { this[action + 'end' ] = end ; }
},
/**
* Returns or sets whether drag actions can be performed on the
* Interactable
*
* @method
* @param {bool | Object} options
* @returns {bool | Interactable}
*/
draggable: function (options) {
if (options instanceof Object) {
this.options.draggable = true;
this.setOnEvents('drag', options);
return this;
}
if (typeof options === 'boolean') {
this.options.draggable = options;
return this;
}
if (options === null) {
delete this.options.draggable;
return this;
}
return this.options.draggable;
},
/**
* Returns or sets whether elements can be dropped onto this
* Interactable to trigger drop events
*
* @function
* @param {bool | Object} [options] The new value to be set. Passing null returns
* the current value
* @returns {bool | Interactable}
*/
dropzone: function (options) {
if (options instanceof Object) {
var ondrop = options.ondrop || options.onDrop;
if (typeof ondrop === 'function') { this.ondrop = ondrop; }
this.options.dropzone = true;
(this.selector? selectorDZs: dropzones).push(this);
if (!dynamicDrop && !this.selector) {
this.rect = this.getRect();
}
return this;
}
if (typeof options === 'boolean') {
if (options) {
(this.selector? selectorDZs: dropzones).push(this);
if (!dynamicDrop && !this.selector) {
this.rect = this.getRect();
}
}
else {
var array = this.selector? selectorDZs: dropzones,
index = array.indexOf(this);
if (index !== -1) {
array.splice(index, 1);
}
}
this.options.dropzone = options;
return this;
}
if (options === null) {
delete this.options.dropzone;
return this;
}
return this.options.dropzone;
},
/**
* The default function to determine if adragend event occured
* over this Interactable's element
*
* @function
* @param {MouseEvent | TouchEvent} event The event that ends an
* interactdrag
* @returns {bool}
*/
dropCheck: function (event) {
var page = getPageXY(event),
horizontal,
vertical;
if (dynamicDrop) {
this.rect = this.getRect();
}
horizontal = (page.x > this.rect.left) && (page.x < this.rect.right);
vertical = (page.y > this.rect.top ) && (page.y < this.rect.bottom);
return horizontal && vertical;
},
/**
* Returns or sets the function used to check if a dragged element is
* dropped over this Interactable
*
* @function
* @param {function} [newValue] A function which takes a mouseUp/touchEnd
* event as a parameter and returns true or false to
* indicate if the the current draggable can be
* dropped into this Interactable
* @returns {Function | Interactable}
*/
dropChecker: function (newValue) {
if (typeof newValue === 'function') {
this.dropCheck = newValue;
return this;
}
return this.dropCheck;
},
/**
* Returns or sets whether resize actions can be performed on the
* Interactable
*
* @function
* @param {bool | Object} [options] An object with event listeners to be fired on resize events
* @returns {bool | Interactable}
*/
resizeable: function (options) {
if (options instanceof Object) {
this.options.resizeable = true;
this.setOnEvents('resize', options);
return this;
}
if (typeof options === 'boolean') {
this.options.resizeable = options;
return this;
}
return this.options.resizeable;
},
/**
* Returns or sets whether resizing is forced 1:1 aspect
*
* @function
* @param {bool} [newValue]
* @returns {bool | Interactable}
*/
squareResize: function (newValue) {
if (typeof newValue === 'boolean') {
this.options.squareResize = newValue;
return this;
}
if (newValue === null) {
delete this.options.squareResize;
return this;
}
return this.options.squareResize;
},
/**
* Returns or sets whether multitouch gestures can be performed on the
* Interactables element
*
* @function
* @param {bool} [options]
* @returns {bool | Interactable}
*/
gestureable: function (options) {
if (options instanceof Object) {
this.options.gestureable = true;
this.setOnEvents('gesture', options);
return this;
}
if (typeof options === 'boolean') {
this.options.gestureable = options;
return this;
}
if (options === null) {
delete this.options.gestureable;
return this;
}
return this.options.gestureable;
},
/**
* Returns or sets whether or not any actions near the edges of the
* window/container trigger autoScroll for this Interactable
*
* @function
* @param {Object | Boolean | null} [options] either
* - an object with margin, distance and interval properties,
* - true or false to enable or disable autoScroll or
* - null to use default settings
* @returns {Boolean | Object | Interactable}
*/
autoScroll: function (options) {
var defaults = defaultOptions.autoScroll;
if (options instanceof Object) {
var autoScroll = this.options.autoScroll;
if (autoScroll === defaults) {
autoScroll = this.options.autoScroll = {
margin : defaults.margin,
distance : defaults.distance,
interval : defaults.interval,
container: defaults.container,
};
}
autoScroll.margin = this.validateSetting('autoScroll', 'margin' , options.margin);
autoScroll.distance = this.validateSetting('autoScroll', 'distance' , options.distance);
autoScroll.interval = this.validateSetting('autoScroll', 'interval' , options.interval);
autoScroll.container = this.validateSetting('autoScroll', 'container', options.container);
this.options.autoScrollEnabled = true;
this.options.autoScroll = autoScroll;
return this;
}
if (typeof options === 'boolean') {
this.options.autoScrollEnabled = options;
return this;
}
if (options === null) {
delete this.options.autoScrollEnabled;
delete this.options.autoScroll;
return this;
}
return (this.options.autoScrollEnabled
? this.options.autoScroll
: false);
},
/**
*
* @function
* @param {Object | Boolean | null} [options] either
* - an object with margin, distance and interval properties,
* - true or false to enable or disable autoScroll or
* - null to use default settings
* @returns {Boolean | Object | Interactable}
*/
snap: function (options) {
var defaults = defaultOptions.snap;
if (options instanceof Object) {
var snap = this.options.snap;
if (snap === defaults) {
snap = this.options.snap = {
mode : defaults.mode,
range : defaults.range,
grid : defaults.grid,
gridOffset: defaults.gridOffset,
anchors : defaults.anchors
};
}
snap.mode = this.validateSetting('snap', 'mode' , options.mode);
snap.range = this.validateSetting('snap', 'range' , options.range);
snap.paths = this.validateSetting('snap', 'paths' , options.paths);
snap.grid = this.validateSetting('snap', 'grid' , options.grid);
snap.gridOffset = this.validateSetting('snap', 'gridOffset', options.gridOffset);
snap.anchors = this.validateSetting('snap', 'anchors' , options.anchors);
this.options.snapEnabled = true;
this.options.snap = snap;
return this;
}
if (typeof options === 'boolean') {
this.options.snapEnabled = options;
return this;
}
if (options === null) {
delete this.options.snapEnabled;
delete this.options.snap;
return this;
}
return (this.options.snapEnabled
? this.options.snap
: false);
},
/**
* @private
* @returns {String} action to be performed - drag/resize[axes]/gesture
*/
getAction: function actionCheck (event) {
var rect = this.getRect(),
right,
bottom,
action,
page = getPageXY(event),
options = this.options;
if (actionIsEnabled.resize && options.resizeable) {
right = page.x > (rect.right - margin);
bottom = page.y > (rect.bottom - margin);
}
if (actionIsEnabled.gesture &&
event.touches && event.touches.length >= 2 &&
!(dragging || resizing)) {
action = 'gesture';
}
else {
resizeAxes = (right?'x': '') + (bottom?'y': '');
action = (resizeAxes)?
'resize' + resizeAxes:
actionIsEnabled.drag && options.draggable?
'drag':
null;
}
return action;
},
/**
* Returns or sets the function used to check action to be performed on
* pointerDown
*
* @function
* @param {function} [newValue]
* @returns {Function | Interactable}
*/
actionChecker: function (newValue) {
if (typeof newValue === 'function') {
this.getAction = newValue;
return this;
}
if (newValue === null) {
delete this.options.getAction;
return this;
}
return this.getAction;
},
/**
* Return an object with the left, right, top, bottom, width and height
* of the interactable's element
*
* @function
* @param {function} [newValue]
* @returns {Function | Interactable}
*/
getRect: function rectCheck () {
var scroll = getScrollXY(),
clientRect = (this._element instanceof SVGElement)?
this._element.getBoundingClientRect():
this._element.getClientRects()[0];
return {
left : clientRect.left + scroll.x,
right : clientRect.right + scroll.x,
top : clientRect.top + scroll.y,
bottom: clientRect.bottom + scroll.y,
width : clientRect.width || clientRect.right - clientRect.left,
height: clientRect.heigh || clientRect.bottom - clientRect.top
};
},
/**
* Returns or sets the function used to calculate the interactable's
* element rectangle
*
* @function
* @param {function} [newValue]
* @returns {Function | Interactable}
*/
rectChecker: function (newValue) {
if (typeof newValue === 'function') {
this.getRect = newValue;
return this;
}
if (newValue === null) {
delete this.options.getRect;
return this;
}
return this.getRect;
},
/**
* Returns or sets whether the action that would be performed when the
* mouse hovers over the element are checked. If so, the cursor may be
* styled appropriately
*
* @function
* @param {function} [newValue]
* @returns {Function | Interactable}
*/
styleCursor: function (newValue) {
if (typeof newValue === 'boolean') {
this.options.styleCursor = newValue;
return this;
}
if (newValue === null) {
delete this.options.styleCursor;
return this;
}
return this.options.styleCursor;
},
/**
* Returns or sets the origin of the Interactable's element
*
* @function
* @param {Object} [newValue]
* @returns {Object | Interactable}
*/
origin: function (newValue) {
if (newValue instanceof Object) {
this.options.origin = newValue;
return this;
}
if (newValue === null) {
delete this.options.origin;
return this;
}
return this.options.origin;
},
/**
* Returns or sets the mouse coordinate types used to calculate the
* movement of the pointer.
*
* @function
* @param {string} [newValue] Use:
* 'client' if you will be scrolling while interacting
* 'page' if you want autoScroll to work
* @returns {Object | Interactable}
*/
deltaSource: function (newValue) {
if (newValue === 'page' || newValue === 'client') {
this.options.deltaSource = newValue;
return this;
}
if (newValue === null) {
delete this.options.deltaSource;
return this;
}
return this.options.deltaSource;
},
/**
* @function
* @param {String} context eg. 'snap', 'autoScroll'
* @param {String} option The name of the value being set
* @param {Array | Object | String | Number} value The value being validated
* @returns {Null | Array | Object | String | Number}
* null if defaultOptions[context][value] is undefined
* value if it is the same type as defaultOptions[context][value],
* or this.options[context][value] if it is the same type as defaultOptions[context][value],
* or defaultOptions[context][value]
*/
validateSetting: function (context, option, value) {
var defaults = defaultOptions[context],
current = this.options[context];
if (defaults !== undefined && defaults[option] !== undefined) {
if ('objectTypes' in defaults && defaults.objectTypes.test(option)) {
if (value instanceof Object) { return value; }
else {
return (option in current && current[option] instanceof Object
? current [option]
: defaults[option]);
}
}
if ('arrayTypes' in defaults && defaults.arrayTypes.test(option)) {
if (value instanceof Array) { return value; }
else {
return (option in current && current[option] instanceof Array
? current[option]
: defaults[option]);
}
}
if ('stringTypes' in defaults && defaults.stringTypes.test(option)) {
if (typeof value === 'string') { return value; }
else {
return (option in current && typeof current[option] === 'string'
? current[option]
: defaults[option]);
}
}
if ('numberTypes' in defaults && defaults.numberTypes.test(option)) {
if (typeof value === 'number') { return value; }
else {
return (option in current && typeof current[option] === 'number'
? current[option]
: defaults[option]);
}
}
if ('elementTypes' in defaults && defaults.elementTypes.test(option)) {
if (value instanceof Element) { return value; }
else {
return (option in current && current[option] instanceof Element
? current[option]
: defaults[option]);
}
}
}
return null;
},
/**
* Returns the element this interactable represents
*
* @function
* @returns {HTMLElement | SVGElement}
*/
element: function () {
return this._element;
},
/**
* Calls listeners for the given event type bound globablly
* and directly to this Interactable
*
* @function
* @param {InteractEvent} iEvent The InteractEvent object to be fired on this
* Interactable
* @returns {Interactable}
*/
fire: function (iEvent) {
if (!(iEvent && iEvent.type) || eventTypes.indexOf(iEvent.type) === -1) {
return this;
}
var listeners,
fireState = 0,
i = 0,
len,
onEvent = 'on' + iEvent.type;
// Try-catch and loop so an exception thrown from a listener
// doesn't ruin everything for everyone
while (fireState < 3) {
try {
switch (fireState) {
// interactable.onevent listener
case fireStates.onevent:
if (typeof this[onEvent] === 'function') {
this[onEvent](iEvent);
}
break;
// Interactable#on() listeners
case fireStates.directBind:
if (iEvent.type in this._iEvents) {
listeners = this._iEvents[iEvent.type];
for (len = listeners.length; i < len && !imPropStopped; i++) {
listeners[i](iEvent);
}
break;
}
break;
// interact.on() listeners
case fireStates.globalBind:
if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) {
listeners = globalEvents[iEvent.type];
for (len = listeners.length; i < len && !imPropStopped; i++) {
listeners[i](iEvent);
}
}
}
i = 0;
fireState++;
}
catch (error) {
console.error('Error thrown from ' + iEvent.type + ' listener');
console.error(error);
i++;
if (fireState === fireStates.onevent) {
fireState++;
}
}
}
imPropStopped = false;
return this;
},
/**
* Binds a listener to an InteractEvent or DOM event
*
* @function
* @param {string} eventType The type of event to listen for
* @param {Function} listener The function to be called on that event
* @param {bool} [useCapture]
* @returns {Interactable}
*/
on: function (eventType, listener, useCapture) {
if (eventType === 'wheel') {
eventType = wheelEvent;
}
if (eventTypes.indexOf(eventType) !== -1) {
// if this type of event was never bound to this Interactable
if (!(eventType in this._iEvents)) {
this._iEvents[eventType] = [listener];
}
// if the event listener is not already bound for this type
else if (this._iEvents[eventType].indexOf(listener) === -1) {
this._iEvents[eventType].push(listener);
}
}
else if (this.selector) {
var elements = document.querySelectorAll(this.selector);
for (var i = 0, len = elements.length; i < len; i++) {
events.addToElement(elements[i], eventType, listener, useCapture);
}
}
else {
events.add(this, eventType, listener, useCapture);
}
return this;
},
/**
* Removes an InteractEvent or DOM event listener
*
* @function
* @param {string} eventType The type of event that was listened for
* @param {Function} listener The listener function to be removed
* @param {bool} [useCapture]
* @returns {Interactable}
*/
off: function (eventType, listener, useCapture) {
if (eventType === 'wheel') {
eventType = wheelEvent;
}
if (eventTypes.indexOf(eventType) !== -1) {
var eventArray = this._iEvents[eventType],
index;
if (eventArray && (index = eventArray.indexOf(listener)) !== -1) {
this._iEvents[eventType].splice(index, 1);
}
}
else if (this.selector) {
var elements = document.querySelectorAll(this.selector);
for (var i = 0, len = elements.length; i < len; i++) {
events.removeFromElement(elements[i], eventType, listener, useCapture);
}
}
else {
events.remove(this._element, listener, useCapture);
}
return this;
},
/**
* @function
* @description Reset the options of this Interactable
* @param {Object} options
* @returns {Interactable}
*/
set: function (options) {
if (!options || typeof options !== 'object') {
options = {};
}
this.options = new IOptions(options);
this.draggable ('draggable' in options? options.draggable : this.options.draggable );
this.dropzone ('dropzone' in options? options.dropzone : this.options.dropzone );
this.resizeable ('resizeable' in options? options.resizeable : this.options.resizeable );
this.gestureable('gestureable' in options? options.gestureable: this.options.gestureable);
if ('autoScroll' in options) { this.autoScroll (options.autoScroll ); }
return this;
},
/**
* Remove this interactable from the list of interactables
*remove it's drag, drop, resize and gesture capabilities and remove it's drag, drop, resize and gesture capabilities
*
* @function
* @returns {interact}
*/
unset: function () {
events.remove(this, 'all');
if (typeof this.selector === 'string') {
delete selectors[this.selector];
}
else {
events.remove(this, 'all');
if (this.options.styleCursor) {
this._element.style.cursor = '';
}
elements.splice(elements.indexOf(this.element()));
}
this.dropzone (false);
interactables.splice(interactables.indexOf(this), 1);
return interact;
}
};
/**
* @method
* @memberof interact
* @description Check if an element has been set
* @param {HTMLElement | SVGElement} element The Element being searched for
* @returns {bool}
*/
interact.isSet = function(element) {
return interactables.indexOfElement(element) !== -1;
};
/**
* Adds a global listener to an InteractEvent
*
* @function
* @param {string} eventType The type of event to listen for
* @param {Function} listener The function to be called on that event
* @returns {interact}
*/
interact.on = function (iEventType, listener) {
// The event must be an InteractEvent type
if (eventTypes.indexOf(iEventType) !== -1) {
// if this type of event was never bound to this Interactable
if (!globalEvents[iEventType]) {
globalEvents[iEventType] = [listener];
}
// if the event listener is not already bound for this type
else if (globalEvents[iEventType].indexOf(listener) === -1) {
globalEvents[iEventType].push(listener);
}
}
return interact;
};
/**
* Removes a global InteractEvent listener
*
* @function
* @param {string} eventType The type of event that was listened for
* @param {Function} listener The listener function to be removed
* @returns {interact}
*/
interact.off = function (iEventType, listener) {
var index = globalEvents[iEventType].indexOf(listener);
if (index !== -1) {
globalEvents[iEventType].splice(index, 1);
}
return interact;
};
/**
* @function
* @description Simulate pointer down to interact with an interactable element
* @param {String} action The action to be performed - drag, resize, etc.
* @param {HTMLElement | SVGElement} element The DOM Element to resize/drag
* @param {MouseEvent | TouchEvent} [pointerEvent] A pointer event whose pageX/Y
* coordinates will be the starting point of the interact drag/resize
* @returns {interact}
*/
interact.simulate = function (action, element, pointerEvent) {
var event = {},
prop,
clientRect;
if (action === 'resize') {
action = 'resizexy';
}
// return if the action is not recognised
if (!(action in actions)) {
return interact;
}
if (pointerEvent) {
for (prop in pointerEvent) {
if (pointerEvent.hasOwnProperty(prop)) {
event[prop] = pointerEvent[prop];
}
}
}
else {
clientRect = (target._element instanceof SVGElement)?
element.getBoundingClientRect():
clientRect = element.getClientRects()[0];
if (action === 'drag') {
event.pageX = clientRect.left + clientRect.width / 2;
event.pageY = clientRect.top + clientRect.height / 2;
}
else {
event.pageX = clientRect.right;
event.pageY = clientRect.bottom;
}
}
event.target = event.currentTarget = element;
event.preventDefault = event.stopPropagation = blank;
pointerDown(event, action);
return interact;
};
/**
* Returns or sets whether dragging is disabled for all Interactables
*
* @function
* @param {bool} [newValue]
* @returns {bool | interact}
*/
interact.enableDragging = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.drag = newValue;
return interact;
}
return actionIsEnabled.drag;
};
/**
* Returns or sets whether resizing is disabled for all Interactables
*
* @function
* @param {bool} [newValue]
* @returns {bool | interact}
*/
interact.enableResizing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.resize = newValue;
return interact;
}
return actionIsEnabled.resize;
};
/**
* Returns or sets whether gestures are disabled for all Interactables
*
* @function
* @param {bool} [newValue]
* @returns {bool | interact}
*/
interact.enableGesturing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.gesture = newValue;
return interact;
}
return actionIsEnabled.gesture;
};
interact.eventTypes = eventTypes;
/**
* Returns debugging data
* @function
*/
interact.debug = function () {
return {
target : target,
dragging : dragging,
resizing : resizing,
gesturing : gesturing,
prevX : prevX,
prevY : prevY,
x0 : x0,
y0 : y0,
Interactable : Interactable,
IOptions : IOptions,
interactables : interactables,
dropzones : dropzones,
pointerIsDown : pointerIsDown,
supportsTouch : supportsTouch,
defaultOptions : defaultOptions,
defaultActionChecker : Interactable.prototype.getAction,
dragMove : dragMove,
resizeMove : resizeMove,
gestureMove : gestureMove,
pointerUp : docPointerUp,
pointerDown : pointerDown,
pointerHover : pointerHover,
events : events,
globalEvents : globalEvents,
log: function () {
console.log('target : ' + target);
console.log('prevX, prevY : ' + prevX, prevY);
console.log('x0, y0 : ' + x0, y0);
console.log('supportsTouch : ' + supportsTouch);
console.log('pointerIsDown : ' + pointerIsDown);
console.log('currentAction : ' + interact.currentAction());
}
};
};
/**
* Returns or sets the margin for autocheck resizing. That is the distance
* from the bottom and right edges of an element clicking in which will
* start resizing
*
* @function
* @param {number} [newvalue]
* @returns {number | interact}
*/
interact.margin = function (newvalue) {
if (typeof newvalue === 'number') {
margin = newvalue;
return interact;
}
return margin;
};
/**
* Returns or sets whether if the cursor style of the document is changed
* depending on what action is being performed
*
* @function
* @param {bool} [newValue]
* @returns {bool | interact}
*/
interact.styleCursor = function (newValue) {
if (typeof newValue === 'boolean') {
defaultOptions.styleCursor = newValue;
return interact;
}
return defaultOptions.styleCursor;
};
/**
* Returns or sets whether or not any actions near the edges of the page
* trigger autoScroll by default
*
* @function
* @param {bool | Object} [options] true or false to simply enable or disable
or an object with margin, distance and interval properties
* @returns {bool | interact}
*/
interact.autoScroll = function (options) {
var defaults = defaultOptions.autoScroll;
if (options instanceof Object) {
defaultOptions.autoScrollEnabled = true;
if (typeof (options.margin) === 'number') { defaults.margin = options.margin ; }
if (typeof (options.distance) === 'number') { defaults.distance = options.distance ; }
if (typeof (options.interval) === 'number') { defaults.interval = options.interval ; }
defaults.container = options.container instanceof Element?
options.container:
defaults.container;
return interact;
}
if (typeof options === 'boolean') {
defaultOptions.autoScrollEnabled = options;
return interact;
}
// return the autoScroll settings if autoScroll is enabled
// otherwise, return false
return defaultOptions.autoScrollEnabled? defaults: false;
};
/**
* Returns or sets whether actions are constrained to a grid or a
* collection of coordinates
*
* @function
* @param {bool | Object} [options] true or false to simply enable or disable
* or an object with properties
* mode : 'grid' or 'anchor',
* range : the distance within which snapping to a point occurs,
* grid : an object with properties
* x : the distance between x-axis snap points,
* y : the distance between y-axis snap points,
* offset: an object with
* x, y: the x/y-axis values of the grid origin
* anchors: an array of objects with x, y and optional range
* eg [{x: 200, y: 300, range: 40}, {x: 5, y: 0}],
*
* @returns {Object | interact}
*/
interact.snap = function (options) {
var snap = defaultOptions.snap;
if (options instanceof Object) {
defaultOptions.snapEnabled = true;
if (typeof options.mode === 'string') { snap.mode = options.mode; }
if (typeof options.range === 'number') { snap.range = options.range; }
if (options.anchors instanceof Array ) { snap.anchors = options.anchors;}
if (options.grid instanceof Object ) { snap.grid = options.grid; }
if (options.gridOffset instanceof Object) { snap.gridOffset = options.gridOffset; }
return interact;
}
if (typeof options === 'boolean') {
defaultOptions.snapEnabled = options;
return interact;
}
return {
enabled : defaultOptions.snapEnabled,
mode : snap.mode,
grid : snap.grid,
gridOffset: snap.gridOffset,
anchors : snap.anchors,
paths : snap.paths,
range : snap.range,
locked : snapStatus.locked,
x : snapStatus.x,
y : snapStatus.y,
realX : snapStatus.realX,
realY : snapStatus.realY,
dx : snapStatus.dx,
dy : snapStatus.dy
};
};
/**
* Returns or sets whether or not the browser supports touch input
*
* @function
* @returns {bool}
*/
interact.supportsTouch = function () {
return supportsTouch;
};
/**
* Returns what action is currently being performed
*
* @function
* @returns {String | null}
*/
interact.currentAction = function () {
return (dragging && 'drag') || (resizing && 'resize') || (gesturing && 'gesture') || null;
};
/**
* Ends the current interaction
*
* @function
* @param {Event} [event] An event on which to call preventDefault()
* @returns {interact}
*/
interact.stop = function (event) {
if (dragging || resizing || gesturing) {
autoScroll.stop();
matches = [];
if (target.options.styleCursor) {
document.documentElement.style.cursor = '';
}
clearTargets();
for (var i = 0; i < selectorDZs.length; i++) {
selectorDZs._elements = [];
}
// prevent Default only if were previously interacting
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
}
pointerIsDown = snapStatus.locked = dragging = resizing = gesturing = false;
pointerWasMoved = true;
prepared = null;
return interact;
};
/**
* Returns or sets wheather the dimensions of dropzone elements are
* calculated on every dragmove or only on dragstart for the default
* dropChecker
*
* @function
* @param {bool} [newValue] True to check on each move
* @returns {bool | interact}
*/
interact.dynamicDrop = function (newValue) {
if (typeof newValue === 'boolean') {
if (dragging && dynamicDrop !== newValue && !newValue) {
calcRects(dropzones);
}
dynamicDrop = newValue;
return interact;
}
return dynamicDrop;
};
/**
* Returns or sets weather pageX or clientX is used to calculate dx/dy
*
* @function
* @param {string} [newValue] 'page' or 'client'
* @returns {string | Interactable}
*/
interact.deltaSource = function (newValue) {
if (newValue === 'page' || newValue === 'client') {
defaultOptions.deltaSource = newValue;
return this;
}
return defaultOptions.deltaSource;
};
events.add(docTarget , 'mousedown' , selectorDown);
events.add(docTarget , 'touchstart' , selectorDown);
events.add(docTarget , 'mousemove' , pointerMove );
events.add(docTarget , 'touchmove' , pointerMove );
events.add(docTarget , 'mouseover' , pointerOver );
events.add(docTarget , 'mouseout' , pointerOut );
events.add(docTarget , 'mouseup' , docPointerUp);
events.add(docTarget , 'touchend' , docPointerUp);
events.add(docTarget , 'touchcancel' , docPointerUp);
events.add(windowTarget, 'blur' , docPointerUp);
if (window.parent !== window) {
try {
events.add(parentDocTarget , 'mouseup' , docPointerUp);
events.add(parentDocTarget , 'touchend' , docPointerUp);
events.add(parentDocTarget , 'touchcancel' , docPointerUp);
events.add(parentWindowTarget, 'blur' , docPointerUp);
}
catch (error) {
interact.windowParentError = error;
}
}
// For IE's lack of Event#preventDefault
events.add(docTarget, 'selectstart', function (e) {
if (dragging || resizing || gesturing) {
e.preventDefault();
}
});
// For IE8's lack of an Element#matchesSelector
if (!(matchesSelector in Element.prototype) || typeof (Element.prototype[matchesSelector]) !== 'function') {
Element.prototype[matchesSelector] = IE8MatchesSelector = function (selector, elems) {
// http://tanalin.com/en/blog/2012/12/matches-selector-ie8/
// modified for better performance
elems = elems || this.parentNode.querySelectorAll(selector);
count = elems.length;
for (var i = 0; i < count; i++) {
if (elems[i] === this) {
return true;
}
}
return false;
};
}
return interact;
} ());
|
/*!
* Copyright 2015 Netflix, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.falcor = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var falcor = require(30);
var jsong = require(145);
falcor.atom = jsong.atom;
falcor.ref = jsong.ref;
falcor.error = jsong.error;
falcor.pathValue = jsong.pathValue;
falcor.HttpDataSource = require(140);
module.exports = falcor;
},{"140":140,"145":145,"30":30}],2:[function(require,module,exports){
var ModelRoot = require(4);
var ModelDataSourceAdapter = require(3);
var RequestQueue = require(53);
var GetResponse = require(56);
var ModelResponse = require(59);
var SetResponse = require(60);
var CallResponse = require(55);
var InvalidateResponse = require(58);
var ASAPScheduler = require(61);
var TimeoutScheduler = require(63);
var ImmediateScheduler = require(62);
var identity = require(96);
var arrayClone = require(79);
var arraySlice = require(83);
var collectLru = require(47);
var pathSyntax = require(149);
var getSize = require(92);
var isObject = require(103);
var isFunction = require(100);
var isPathValue = require(104);
var isPrimitive = require(105);
var isJsonEnvelope = require(101);
var isJsonGraphEnvelope = require(102);
var setCache = require(64);
var setJsonGraphAsJsonDense = require(65);
var jsong = require(145);
var ID = 0;
var validateInput = require(122);
var GET_VALID_INPUT = {
path: true,
pathValue: true,
pathSyntax: true,
json: true
};
var SET_VALID_INPUT = {
pathValue: true,
pathSyntax: true,
json: true,
jsonGraph: true
};
module.exports = Model;
Model.ref = jsong.ref;
Model.atom = jsong.atom;
Model.error = jsong.error;
Model.pathValue = jsong.pathValue;
/**
* This callback is invoked when the Model's cache is changed.
* @callback Model~onChange
*/
/**
* This function is invoked on every JSONGraph Error retrieved from the DataSource. This function allows Error objects to be transformed before being stored in the Model's cache.
* @callback Model~errorSelector
* @param {Object} jsonGraphError - the JSONGraph Error object to transform before it is stored in the Model's cache.
* @returns {Object} the JSONGraph Error object to store in the Model cache.
*/
/**
* This function is invoked every time a value in the Model cache is about to be replaced with a new value. If the function returns true, the existing value is replaced with a new value and the version flag on all of the value's ancestors in the tree are incremented.
* @callback Model~comparator
* @param {Object} existingValue - the current value in the Model cache.
* @param {Object} newValue - the value about to be set into the Model cache.
* @returns {Boolean} the Boolean value indicating whether the new value and the existing value are equal.
*/
/**
* A Model object is used to execute commands against a {@link JSONGraph} object. {@link Model}s can work with a local JSONGraph cache, or it can work with a remote {@link JSONGraph} object through a {@link DataSource}.
* @constructor
* @param {?Object} options - a set of options to customize behavior
* @param {?DataSource} options.source - a data source to retrieve and manage the {@link JSONGraph}
* @param {?JSONGraph} options.cache - initial state of the {@link JSONGraph}
* @param {?number} options.maxSize - the maximum size of the cache
* @param {?number} options.collectRatio - the ratio of the maximum size to collect when the maxSize is exceeded
* @param {?Model~errorSelector} options.errorSelector - a function used to translate errors before they are returned
* @param {?Model~onChange} options.onChange - a function called whenever the Model's cache is changed
* @param {?Model~comparator} options.comparator - a function called whenever a value in the Model's cache is about to be replaced with a new value.
*/
function Model(o) {
var options = o || {};
this._root = options._root || new ModelRoot(options);
this._path = options.path || options._path || [];
this._scheduler = options.scheduler || options._scheduler || new ImmediateScheduler();
this._source = options.source || options._source;
this._request = options.request || options._request || new RequestQueue(this, this._scheduler);
this._ID = ID++;
if (typeof options.maxSize === "number") {
this._maxSize = options.maxSize;
} else {
this._maxSize = options._maxSize || Model.prototype._maxSize;
}
if (typeof options.collectRatio === "number") {
this._collectRatio = options.collectRatio;
} else {
this._collectRatio = options._collectRatio || Model.prototype._collectRatio;
}
if (options.boxed || options.hasOwnProperty("_boxed")) {
this._boxed = options.boxed || options._boxed;
}
if (options.materialized || options.hasOwnProperty("_materialized")) {
this._materialized = options.materialized || options._materialized;
}
if (typeof options.treatErrorsAsValues === "boolean") {
this._treatErrorsAsValues = options.treatErrorsAsValues;
} else if (options.hasOwnProperty("_treatErrorsAsValues")) {
this._treatErrorsAsValues = options._treatErrorsAsValues;
}
if (options.cache) {
this.setCache(options.cache);
}
}
Model.prototype.constructor = Model;
Model.prototype._materialized = false;
Model.prototype._boxed = false;
Model.prototype._progressive = false;
Model.prototype._treatErrorsAsValues = false;
Model.prototype._maxSize = Math.pow(2, 53) - 1;
Model.prototype._collectRatio = 0.75;
/**
* The get method retrieves several {@link Path}s or {@link PathSet}s from a {@link Model}. The get method loads each value into a JSON object and returns in a ModelResponse.
* @function
* @param {...PathSet} path - the path(s) to retrieve
* @return {ModelResponse.<JSONEnvelope>} - the requested data as JSON
*/
Model.prototype.get = function get() {
var out = validateInput(arguments, GET_VALID_INPUT, "get");
if (out !== true) {
return new ModelResponse(function(o) {
o.onError(out);
});
}
return this._get.apply(this, arguments);
};
/**
* Sets the value at one or more places in the JSONGraph model. The set method accepts one or more {@link PathValue}s, each of which is a combination of a location in the document and the value to place there. In addition to accepting {@link PathValue}s, the set method also returns the values after the set operation is complete.
* @function
* @return {ModelResponse.<JSON>} - an {@link Observable} stream containing the values in the JSONGraph model after the set was attempted
*/
Model.prototype.set = function set() {
var out = validateInput(arguments, SET_VALID_INPUT, "set");
if (out !== true) {
return new ModelResponse(function(o) {
o.onError(out);
});
}
return this._set.apply(this, arguments);
};
/**
* The preload method retrieves several {@link Path}s or {@link PathSet}s from a {@link Model} and loads them into the Model cache.
* @function
* @param {...PathSet} path - the path(s) to retrieve
* @return {ModelResponse.<Object>} - a ModelResponse that completes when the data has been loaded into the cache.
*/
Model.prototype.preload = function preload() {
var out = validateInput(arguments, GET_VALID_INPUT, "preload");
if (out !== true) {
return new ModelResponse(function(o) {
o.onError(out);
});
}
var args = Array.prototype.slice.apply(arguments, []);
var preloadOperation = this._get.apply(this, args.concat(identity));
return new ModelResponse(function preloadModelResponse(observer) {
preloadOperation.
subscribe(
identity,
function(e) {
observer.onError(e);
}, function() {
observer.onCompleted();
});
});
};
Model.prototype._get = function _get() {
var args;
var argsIdx = -1;
var argsLen = arguments.length;
var selector = arguments[argsLen - 1];
if (isFunction(selector)) {
argsLen = argsLen - 1;
} else {
selector = void 0;
}
args = new Array(argsLen);
while (++argsIdx < argsLen) {
args[argsIdx] = arguments[argsIdx];
}
return GetResponse.create(this, args, selector);
};
Model.prototype._set = function _set() {
var args;
var argsIdx = -1;
var argsLen = arguments.length;
var selector = arguments[argsLen - 1];
if (isFunction(selector)) {
argsLen = argsLen - 1;
} else {
selector = void 0;
}
args = new Array(argsLen);
while (++argsIdx < argsLen) {
args[argsIdx] = arguments[argsIdx];
}
return SetResponse.create(this, args, selector);
};
/*
* Invokes a function in the JSON Graph.
* @function
* @param {Path} functionPath - the path to the function to invoke
* @param {Array.<Object>} args - the arguments to pass to the function
* @param {Array.<PathSet>} refPaths - the paths to retrieve from the JSON Graph References in the message returned from the function
* @param {Array.<PathSet>} thisPaths - the paths to retrieve from function's this object after successful function execution
* @returns {ModelResponse.<JSONEnvelope> - a JSONEnvelope contains the values returned from the function
*/
Model.prototype.call = function call() {
var args;
var argsIdx = -1;
var argsLen = arguments.length;
args = new Array(argsLen);
while (++argsIdx < argsLen) {
var arg = arguments[argsIdx];
args[argsIdx] = arg;
var argType = typeof arg;
if (argsIdx > 1 && !Array.isArray(arg) ||
argsIdx === 0 && !Array.isArray(arg) && argType !== "string" ||
argsIdx === 1 && !Array.isArray(arg) && !isPrimitive(arg)) {
/* eslint-disable no-loop-func */
return new ModelResponse(function(o) {
o.onError(new Error("Invalid argument"));
});
/* eslint-enable no-loop-func */
}
}
return CallResponse.create(this, args);
};
/**
* The invalidate method synchronously removes several {@link Path}s or {@link PathSet}s from a {@link Model} cache.
* @function
* @param {...PathSet} path - the paths to remove from the {@link Model}'s cache.
*/
Model.prototype.invalidate = function invalidate() {
var args;
var argsIdx = -1;
var argsLen = arguments.length;
var selector = arguments[argsLen - 1];
if (isFunction(selector)) {
argsLen = argsLen - 1;
} else {
selector = void 0;
}
args = new Array(argsLen);
while (++argsIdx < argsLen) {
args[argsIdx] = arguments[argsIdx];
if (typeof args[argsIdx] !== "object") {
/* eslint-disable no-loop-func */
return new ModelResponse(function(o) {
o.onError(new Error("Invalid argument"));
});
/* eslint-enable no-loop-func */
}
}
InvalidateResponse.create(this, args, selector).subscribe();
};
/**
* Returns a new {@link Model} bound to a location within the {@link JSONGraph}. The bound location is never a {@link Reference}: any {@link Reference}s encountered while resolving the bound {@link Path} are always replaced with the {@link Reference}s target value. For subsequent operations on the {@link Model}, all paths will be evaluated relative to the bound path. Deref allows you to:
* - Expose only a fragment of the {@link JSONGraph} to components, rather than the entire graph
* - Hide the location of a {@link JSONGraph} fragment from components
* - Optimize for executing multiple operations and path looksup at/below the same location in the {@link JSONGraph}
* @method
* @param {Path} derefPath - the path to the object that the new Model should refer to
* @param {...PathSet} relativePathsToPreload - paths (relative to the dereference path) to preload before Model is created
* @return {Observable.<Model>} - an Observable stream with a single value, the dereferenced {@link Model}, or an empty stream if nothing is found at the path
* @example
var model = new falcor.Model({
cache: {
users: [
{ $type: "ref", value: ["usersById", 32] }
],
usersById: {
32: {
name: "Steve",
surname: "McGuire"
}
}
}
});
model.deref(["users", 0], "name").subscribe(function(userModel){
console.log(userModel.getPath());
});
// prints ["usersById", 32] because userModel refers to target of reference at ["users", 0]
*/
Model.prototype.deref = require(5);
/**
* Get data for a single {@link Path}.
* @param {Path} path - the path to retrieve
* @return {Observable.<*>} - the value for the path
* @example
var model = new falcor.Model({source: new falcor.HttpDataSource("/model.json") });
model.
getValue('user.name').
subscribe(function(name) {
console.log(name);
});
// The code above prints "Jim" to the console.
*/
Model.prototype.getValue = function getValue(path) {
var parsedPath = pathSyntax.fromPath(path);
var pathIdx = 0;
var pathLen = parsedPath.length;
while (++pathIdx < pathLen) {
if (typeof parsedPath[pathIdx] === "object") {
/* eslint-disable no-loop-func */
return new ModelResponse(function(o) {
o.onError(new Error("Paths must be simple paths"));
});
/* eslint-enable no-loop-func */
}
}
return this._get(parsedPath, identity);
};
/**
* Set value for a single {@link Path}.
* @param {Path} path - the path to set
* @param {Object} value - the value to set
* @return {Observable.<*>} - the value for the path
* @example
var model = new falcor.Model({source: new falcor.HttpDataSource("/model.json") });
model.
setValue('user.name', 'Jim').
subscribe(function(name) {
console.log(name);
});
// The code above prints "Jim" to the console.
*/
Model.prototype.setValue = function setValue(pathArg, valueArg) {
var value = isPathValue(pathArg) ? pathArg : Model.pathValue(pathArg, valueArg);
var pathIdx = 0;
var path = value.path;
var pathLen = path.length;
while (++pathIdx < pathLen) {
if (typeof path[pathIdx] === "object") {
/* eslint-disable no-loop-func */
return new ModelResponse(function(o) {
o.onError(new Error("Paths must be simple paths"));
});
/* eslint-enable no-loop-func */
}
}
return this._set(value, identity);
};
// TODO: Does not throw if given a PathSet rather than a Path, not sure if it should or not.
// TODO: Doc not accurate? I was able to invoke directly against the Model, perhaps because I don't have a data source?
// TODO: Not clear on what it means to "retrieve objects in addition to JSONGraph values"
/**
* Synchronously retrieves a single path from the local {@link Model} only and will not retrieve missing paths from the {@link DataSource}. This method can only be invoked when the {@link Model} does not have a {@link DataSource} or from within a selector function. See {@link Model.prototype.get}. The getValueSync method differs from the asynchronous get methods (ex. get, getValues) in that it can be used to retrieve objects in addition to JSONGraph values.
* @method
* @private
* @arg {Path} path - the path to retrieve
* @return {*} - the value for the specified path
*/
Model.prototype._getValueSync = require(21);
Model.prototype._setValueSync = require(77);
Model.prototype._derefSync = require(6);
/**
* Set the local cache to a {@link JSONGraph} fragment. This method can be a useful way of mocking a remote document, or restoring the local cache from a previously stored state.
* @param {JSONGraph} jsonGraph - the {@link JSONGraph} fragment to use as the local cache
*/
Model.prototype.setCache = function modelSetCache(cacheOrJSONGraphEnvelope) {
var cache = this._root.cache;
if (cacheOrJSONGraphEnvelope !== cache) {
var modelRoot = this._root;
this._root.cache = {};
if (typeof cache !== "undefined") {
collectLru(modelRoot, modelRoot.expired, getSize(cache), 0);
}
if (isJsonGraphEnvelope(cacheOrJSONGraphEnvelope)) {
setJsonGraphAsJsonDense(this, [cacheOrJSONGraphEnvelope], []);
} else if (isJsonEnvelope(cacheOrJSONGraphEnvelope)) {
setCache(this, cacheOrJSONGraphEnvelope.json);
} else if (isObject(cacheOrJSONGraphEnvelope)) {
setCache(this, cacheOrJSONGraphEnvelope);
}
} else if (typeof cache === "undefined") {
this._root.cache = {};
}
return this;
};
/**
* Get the local {@link JSONGraph} cache. This method can be a useful to store the state of the cache.
* @param {...Array.<PathSet>} [pathSets] - The path(s) to retrieve. If no paths are specified, the entire {@link JSONGraph} is returned.
* @return {JSONGraph} all of the {@link JSONGraph} data in the {@link Model} cache.
* @example
// Storing the boxshot of the first 10 titles in the first 10 genreLists to local storage.
localStorage.setItem('cache', JSON.stringify(model.getCache("genreLists[0...10][0...10].boxshot")));
*/
Model.prototype.getCache = function getCache() {
var paths = arraySlice(arguments);
if (paths.length === 0) {
paths[0] = {
json: this._root.cache
};
}
var result;
this.get.apply(this.withoutDataSource().boxValues().treatErrorsAsValues().materialize(), paths).
toJSONG().
subscribe(function(envelope) {
result = envelope.jsonGraph || envelope.jsong;
});
return result;
};
/**
* Retrieves a number which is incremented every single time a value is changed underneath the Model or the object at an optionally-provided Path beneath the Model.
* @param {Path?} path - a path at which to retrieve the version number
* @return {Number} a version number which changes whenever a value is changed underneath the Model or provided Path
*/
Model.prototype.getVersion = function getVersion(pathArg) {
var path = pathArg && pathSyntax.fromPath(pathArg) || [];
if (Array.isArray(path) === false) {
throw new Error("Model#getVersion must be called with an Array path.");
}
if (this._path.length) {
path = this._path.concat(path);
}
return this._getVersion(this, path);
};
Model.prototype.syncCheck = function syncCheck(name) {
if (Boolean(this._source) && this._root.syncRefCount <= 0 && this._root.unsafeMode === false) {
throw new Error("Model#" + name + " may only be called within the context of a request selector.");
}
return true;
};
/* eslint-disable guard-for-in */
Model.prototype.clone = function cloneModel(opts) {
var clone = new Model(this);
for (var key in opts) {
var value = opts[key];
if (value === "delete") {
delete clone[key];
} else {
clone[key] = value;
}
}
clone.setCache = void 0;
return clone;
};
/* eslint-enable */
/**
* Returns a clone of the {@link Model} that enables batching. Within the configured time period, paths for get operations are collected and sent to the {@link DataSource} in a batch. Batching can be more efficient if the {@link DataSource} access the network, potentially reducing the number of HTTP requests to the server.
* @param {?Scheduler|number} schedulerOrDelay - Either a {@link Scheduler} that determines when to send a batch to the {@link DataSource}, or the number in milliseconds to collect a batch before sending to the {@link DataSource}. If this parameter is omitted, then batch collection ends at the end of the next tick.
* @return {Model} a Model which schedules a batch of get requests to the DataSource.
*/
Model.prototype.batch = function batch(schedulerOrDelayArg) {
var schedulerOrDelay = schedulerOrDelayArg;
if (typeof schedulerOrDelay === "number") {
schedulerOrDelay = new TimeoutScheduler(Math.round(Math.abs(schedulerOrDelay)));
} else if (!schedulerOrDelay || !schedulerOrDelay.schedule) {
schedulerOrDelay = new ASAPScheduler();
}
var clone = this.clone();
clone._request = new RequestQueue(clone, schedulerOrDelay);
return clone;
};
/**
* Returns a clone of the {@link Model} that disables batching. This is the default mode. Each get operation will be executed on the {@link DataSource} separately.
* @name unbatch
* @memberof Model.prototype
* @function
* @return {Model} a {@link Model} that batches requests of the same type and sends them to the data source together
*/
Model.prototype.unbatch = function unbatch() {
var clone = this.clone();
clone._request = new RequestQueue(clone, new ImmediateScheduler());
return clone;
};
/**
* Returns a clone of the {@link Model} that treats errors as values. Errors will be reported in the same callback used to report data. Errors will appear as objects in responses, rather than being sent to the {@link Observable~onErrorCallback} callback of the {@link ModelResponse}.
* @return {Model}
*/
Model.prototype.treatErrorsAsValues = function treatErrorsAsValues() {
return this.clone({
_treatErrorsAsValues: true
});
};
/**
* Adapts a Model to the {@link DataSource} interface.
* @return {DataSource}
* @example
var model =
new falcor.Model({
cache: {
user: {
name: "Steve",
surname: "McGuire"
}
}
}),
proxyModel = new falcor.Model({ source: model.asDataSource() });
// Prints "Steve"
proxyModel.getValue("user.name").
then(function(name) {
console.log(name);
});
*/
Model.prototype.asDataSource = function asDataSource() {
return new ModelDataSourceAdapter(this);
};
Model.prototype.materialize = function materialize() {
return this.clone({
_materialized: true
});
};
Model.prototype.dematerialize = function dematerialize() {
return this.clone({
_materialized: "delete"
});
};
/**
* Returns a clone of the {@link Model} that boxes values returning the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the value inside it. This allows any metadata attached to the wrapper to be inspected.
* @return {Model}
*/
Model.prototype.boxValues = function boxValues() {
return this.clone({
_boxed: true
});
};
/**
* Returns a clone of the {@link Model} that unboxes values, returning the value inside of the wrapper ({@link Atom}, {@link Reference}, or {@link Error}), rather than the wrapper itself. This is the default mode.
* @return {Model}
*/
Model.prototype.unboxValues = function unboxValues() {
return this.clone({
_boxed: "delete"
});
};
/**
* Returns a clone of the {@link Model} that only uses the local {@link JSONGraph} and never uses a {@link DataSource} to retrieve missing paths.
* @return {Model}
*/
Model.prototype.withoutDataSource = function withoutDataSource() {
return this.clone({
_source: "delete"
});
};
Model.prototype.toJSON = function toJSON() {
return {
$type: "ref",
value: this._path
};
};
/**
* Returns the {@link Path} to the object within the JSON Graph that this Model references.
* @return {Path}
* @example
var model = new falcor.Model({
cache: {
users: [
{ $type: "ref", value: ["usersById", 32] }
],
usersById: {
32: {
name: "Steve",
surname: "McGuire"
}
}
}
});
model.deref(["users", 0], "name").subscribe(function(userModel){
console.log(userModel.getPath());
});
// prints ["usersById", 32] because userModel refers to target of reference at ["users", 0]
*/
Model.prototype.getPath = function getPath() {
return arrayClone(this._path);
};
var getWalk = require(17);
Model.prototype._getBoundValue = require(14);
Model.prototype._getVersion = require(16);
Model.prototype._getValueSync = require(15);
Model.prototype._getPathValuesAsValues = require(13)(getWalk);
Model.prototype._getPathValuesAsJSON = require(10)(getWalk);
Model.prototype._getPathValuesAsPathMap = require(12)(getWalk);
Model.prototype._getPathValuesAsJSONG = require(11)(getWalk);
Model.prototype._getPathMapsAsValues = require(13)(getWalk);
Model.prototype._getPathMapsAsJSON = require(10)(getWalk);
Model.prototype._getPathMapsAsPathMap = require(12)(getWalk);
Model.prototype._getPathMapsAsJSONG = require(11)(getWalk);
Model.prototype._setPathValuesAsJSON = require(73);
Model.prototype._setPathValuesAsJSONG = require(74);
Model.prototype._setPathValuesAsPathMap = require(75);
Model.prototype._setPathValuesAsValues = require(76);
Model.prototype._setPathMapsAsJSON = require(69);
Model.prototype._setPathMapsAsJSONG = require(70);
Model.prototype._setPathMapsAsPathMap = require(71);
Model.prototype._setPathMapsAsValues = require(72);
Model.prototype._setJSONGsAsJSON = require(65);
Model.prototype._setJSONGsAsJSONG = require(66);
Model.prototype._setJSONGsAsPathMap = require(67);
Model.prototype._setJSONGsAsValues = require(68);
Model.prototype._setCache = require(64);
Model.prototype._invalidatePathValuesAsJSON = require(46);
Model.prototype._invalidatePathMapsAsJSON = require(45);
},{"10":10,"100":100,"101":101,"102":102,"103":103,"104":104,"105":105,"11":11,"12":12,"122":122,"13":13,"14":14,"145":145,"149":149,"15":15,"16":16,"17":17,"21":21,"3":3,"4":4,"45":45,"46":46,"47":47,"5":5,"53":53,"55":55,"56":56,"58":58,"59":59,"6":6,"60":60,"61":61,"62":62,"63":63,"64":64,"65":65,"66":66,"67":67,"68":68,"69":69,"70":70,"71":71,"72":72,"73":73,"74":74,"75":75,"76":76,"77":77,"79":79,"83":83,"92":92,"96":96}],3:[function(require,module,exports){
function ModelDataSourceAdapter(model) {
this._model = model.materialize().boxValues().treatErrorsAsValues();
}
ModelDataSourceAdapter.prototype.get = function get(pathSets) {
return this._model.get.apply(this._model, pathSets).toJSONG();
};
ModelDataSourceAdapter.prototype.set = function set(jsongResponse) {
return this._model.set(jsongResponse).toJSONG();
};
ModelDataSourceAdapter.prototype.call = function call(path, args, suffixes, paths) {
var params = [path, args, suffixes].concat(paths);
return this._model.call.apply(this._model, params).toJSONG();
};
module.exports = ModelDataSourceAdapter;
},{}],4:[function(require,module,exports){
var isFunction = require(100);
var ImmediateScheduler = require(62);
function ModelRoot(o) {
var options = o || {};
this.syncRefCount = 0;
this.expired = options.expired || [];
this.unsafeMode = options.unsafeMode || false;
this.collectionScheduler = options.collectionScheduler || new ImmediateScheduler();
this.cache = {};
if (isFunction(options.comparator)) {
this.comparator = options.comparator;
}
if (isFunction(options.errorSelector)) {
this.errorSelector = options.errorSelector;
}
if (isFunction(options.onChange)) {
this.onChange = options.onChange;
}
}
ModelRoot.prototype.errorSelector = function errorSelector(x, y) {
return y;
};
ModelRoot.prototype.comparator = function comparator(a, b) {
if (Boolean(a) && typeof a === "object" && a.hasOwnProperty("value") &&
Boolean(b) && typeof b === "object" && b.hasOwnProperty("value")) {
return a.value === b.value;
}
return a === b;
};
module.exports = ModelRoot;
},{"100":100,"62":62}],5:[function(require,module,exports){
var Rx = require(171);
var pathSyntax = require(149);
module.exports = function deref(boundPathArg) {
var model = this;
var modelRoot = model._root;
var pathsIndex = -1;
var pathsCount = arguments.length - 1;
var paths = new Array(pathsCount);
var boundPath = pathSyntax.fromPath(boundPathArg);
while (++pathsIndex < pathsCount) {
paths[pathsIndex] = pathSyntax.fromPath(arguments[pathsIndex + 1]);
}
if (modelRoot.syncRefCount <= 0 && pathsCount === 0) {
throw new Error("Model#deref requires at least one value path.");
}
return Rx.Observable.defer(function() {
var value;
var errorHappened = false;
try {
++modelRoot.syncRefCount;
value = model._derefSync(boundPath);
} catch (e) {
value = e;
errorHappened = true;
} finally {
--modelRoot.syncRefCount;
return errorHappened ?
Rx.Observable.throw(value) :
Rx.Observable.return(value);
}
}).
flatMap(function(boundModel) {
if (Boolean(boundModel)) {
if (pathsCount > 0) {
return boundModel._get.apply(boundModel, paths.concat(function() {
return boundModel;
})).catch(Rx.Observable.empty());
}
return Rx.Observable.return(boundModel);
} else if (pathsCount > 0) {
return (model._get.apply(model, paths.map(function(path) {
return boundPath.concat(path);
}).concat(function() {
return model.deref(boundPath);
}))
.mergeAll());
}
return Rx.Observable.empty();
});
};
},{"149":149,"171":171}],6:[function(require,module,exports){
var $error = require(125);
var pathSyntax = require(149);
var getBoundValue = require(14);
var getType = require(93);
module.exports = function derefSync(boundPathArg) {
var boundPath = pathSyntax.fromPath(boundPathArg);
if (!Array.isArray(boundPath)) {
throw new Error("Model#derefSync must be called with an Array path.");
}
var boundValue = this.syncCheck("bindSync") && getBoundValue(this, this._path.concat(boundPath));
var path = boundValue.path;
var node = boundValue.value;
var found = boundValue.found;
if (!found) {
return void 0;
}
var type = getType(node);
if (Boolean(node) && Boolean(type)) {
if (type === $error) {
if (this._boxed) {
throw node;
}
throw node.value;
} else if (node.value === void 0) {
return void 0;
}
}
return this.clone({ _path: path });
};
},{"125":125,"14":14,"149":149,"93":93}],7:[function(require,module,exports){
/**
* An InvalidModelError can only happen when a user binds, whether sync
* or async to shorted value. See the unit tests for examples.
*
* @param {String} message
* @private
*/
function InvalidModelError(boundPath, shortedPath) {
this.message = "The boundPath of the model is not valid since a value or error was found before the path end.";
this.stack = (new Error()).stack;
this.boundPath = boundPath;
this.shortedPath = shortedPath;
}
// instanceof will be an error, but stack will be correct because its defined in the constructor.
InvalidModelError.prototype = new Error();
InvalidModelError.prototype.name = "InvalidModel";
module.exports = InvalidModelError;
},{}],8:[function(require,module,exports){
var NAME = "InvalidSourceError";
/**
* InvalidSourceError happens when a dataSource syncronously throws
* an exception during a get/set/call operation.
*
* @param {Error} error - The error that was thrown.
* @private
*/
function InvalidSourceError(error) {
this.message = "An exception was thrown when making a request.";
this.stack = (new Error()).stack;
this.innerError = error;
}
// instanceof will be an error, but stack will be correct because its defined
// in the constructor.
InvalidSourceError.prototype = new Error();
InvalidSourceError.prototype.name = NAME;
InvalidSourceError.name = NAME;
InvalidSourceError.is = function(e) {
return e && e.name === NAME;
};
module.exports = InvalidSourceError;
},{}],9:[function(require,module,exports){
var hardLink = require(23);
var createHardlink = hardLink.create;
var onValue = require(20);
var isExpired = require(24);
var $ref = require(126);
var __context = require(31);
var promote = require(27).promote;
/* eslint-disable no-constant-condition */
function followReference(model, root, nodeArg, referenceContainerArg, referenceArg, seed, outputFormat) {
var node = nodeArg;
var reference = referenceArg;
var referenceContainer = referenceContainerArg;
var depth = 0;
var k, next;
while (true) {
if (depth === 0 && referenceContainer[__context]) {
depth = reference.length;
next = referenceContainer[__context];
} else {
k = reference[depth++];
next = node[k];
}
if (next) {
var type = next.$type;
var value = type && next.value || next;
if (depth < reference.length) {
if (type) {
node = next;
break;
}
node = next;
continue;
}
// We need to report a value or follow another reference.
else {
node = next;
if (type && isExpired(next)) {
break;
}
if (!referenceContainer[__context]) {
createHardlink(referenceContainer, next);
}
// Restart the reference follower.
if (type === $ref) {
if (outputFormat === "JSONG") {
onValue(model, next, seed, null, null, reference, null, outputFormat);
} else {
promote(model, next);
}
depth = 0;
reference = value;
referenceContainer = next;
node = root;
continue;
}
break;
}
} else {
node = void 0;
}
break;
}
if (depth < reference.length && node !== void 0) {
var ref = [];
for (var i = 0; i < depth; i++) {
ref[i] = reference[i];
}
reference = ref;
}
return [node, reference];
}
/* eslint-enable */
module.exports = followReference;
},{"126":126,"20":20,"23":23,"24":24,"27":27,"31":31}],10:[function(require,module,exports){
var getBoundValue = require(14);
var isPathValue = require(26);
module.exports = function(walk) {
return function getAsJSON(model, paths, valuesArg) {
var values = valuesArg;
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var requestedMissingPaths = results.requestedMissingPaths;
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
"Paths" : "JSON";
var cache = model._root.cache;
var boundPath = model._path;
var currentCachePosition;
var missingIdx = 0;
var boundOptimizedPath, optimizedPath;
var i, j, len, bLen;
var valueNode, length;
results.values = values;
if (!values) {
values = [];
}
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (i = 0, len = paths.length; i < len; i++) {
valueNode = void 0;
var pathSet = paths[i];
if (values[i]) {
valueNode = values[i];
}
if (len > 1) {
optimizedPath = [];
for (j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
if (inputFormat === "JSON") {
pathSet = pathSet.json;
} else if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, "JSON");
if (missingIdx < requestedMissingPaths.length) {
for (j = missingIdx, length = requestedMissingPaths.length; j < length; j++) {
requestedMissingPaths[j].pathSetIndex = i;
}
missingIdx = length;
}
}
return results;
};
};
},{"14":14,"26":26}],11:[function(require,module,exports){
var isPathValue = require(26);
module.exports = function(walk) {
return function getAsJSONG(model, paths, values) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
"Paths" : "JSON";
results.values = values;
var cache = model._root.cache;
var boundPath = model._path;
var currentCachePosition;
if (boundPath.length) {
throw new Error("It is not legal to use the JSON Graph format from a bound Model. JSON Graph format can only be used from a root model.");
} else {
currentCachePosition = cache;
}
for (var i = 0, len = paths.length; i < len; i++) {
var pathSet = paths[i];
if (inputFormat === "JSON") {
pathSet = pathSet.json;
} else if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, values[0], [], results, [], [], inputFormat, "JSONG");
}
return results;
};
};
},{"26":26}],12:[function(require,module,exports){
var getBoundValue = require(14);
var isPathValue = require(26);
module.exports = function(walk) {
return function getAsPathMap(model, paths, values) {
var valueNode;
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
"Paths" : "JSON";
valueNode = values[0];
results.values = values;
var cache = model._root.cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (var j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
var pathSet = paths[i];
if (inputFormat === "JSON") {
pathSet = pathSet.json;
} else if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, valueNode, [], results, optimizedPath, [], inputFormat, "PathMap");
}
return results;
};
};
},{"14":14,"26":26}],13:[function(require,module,exports){
var getBoundValue = require(14);
var isPathValue = require(26);
module.exports = function(walk) {
return function getAsValues(model, paths, onNext) {
var results = {
values: [],
errors: [],
requestedPaths: [],
optimizedPaths: [],
requestedMissingPaths: [],
optimizedMissingPaths: []
};
var inputFormat = Array.isArray(paths[0]) || isPathValue(paths[0]) ?
"Paths" : "JSON";
var cache = model._root.cache;
var boundPath = model._path;
var currentCachePosition;
var optimizedPath, boundOptimizedPath;
if (boundPath.length) {
var boundValue = getBoundValue(model, boundPath);
currentCachePosition = boundValue.value;
optimizedPath = boundOptimizedPath = boundValue.path;
} else {
currentCachePosition = cache;
optimizedPath = boundOptimizedPath = [];
}
for (var i = 0, len = paths.length; i < len; i++) {
if (len > 1) {
optimizedPath = [];
for (var j = 0, bLen = boundOptimizedPath.length; j < bLen; j++) {
optimizedPath[j] = boundOptimizedPath[j];
}
}
var pathSet = paths[i];
if (inputFormat === "JSON") {
pathSet = pathSet.json;
} else if (pathSet.path) {
pathSet = pathSet.path;
}
walk(model, cache, currentCachePosition, pathSet, 0, onNext, null, results, optimizedPath, [], inputFormat, "Values");
}
return results;
};
};
},{"14":14,"26":26}],14:[function(require,module,exports){
var getValueSync = require(15);
var InvalidModelError = require(7);
module.exports = function getBoundValue(model, pathArg) {
var path = pathArg;
var boundPath = pathArg;
var boxed, materialized,
treatErrorsAsValues,
value, shorted, found;
boxed = model._boxed;
materialized = model._materialized;
treatErrorsAsValues = model._treatErrorsAsValues;
model._boxed = true;
model._materialized = true;
model._treatErrorsAsValues = true;
value = getValueSync(model, path.concat(null), true);
model._boxed = boxed;
model._materialized = materialized;
model._treatErrorsAsValues = treatErrorsAsValues;
path = value.optimizedPath;
shorted = value.shorted;
found = value.found;
value = value.value;
while (path.length && path[path.length - 1] === null) {
path.pop();
}
if (found && shorted) {
throw new InvalidModelError(boundPath, path);
}
return {
path: path,
value: value,
shorted: shorted,
found: found
};
};
},{"15":15,"7":7}],15:[function(require,module,exports){
var followReference = require(9);
var clone = require(22);
var isExpired = require(24);
var promote = require(27).promote;
var $ref = require(126);
var $atom = require(124);
var $error = require(125);
module.exports = function getValueSync(model, simplePath, noClone) {
var root = model._root.cache;
var len = simplePath.length;
var optimizedPath = [];
var shorted = false, shouldShort = false;
var depth = 0;
var key, i, next = root, curr = root, out = root, type, ref, refNode;
var found = true;
while (next && depth < len) {
key = simplePath[depth++];
if (key !== null) {
next = curr[key];
optimizedPath[optimizedPath.length] = key;
}
if (!next) {
out = void 0;
shorted = true;
found = false;
break;
}
type = next.$type;
// Up to the last key we follow references
if (depth < len) {
if (type === $ref) {
ref = followReference(model, root, root, next, next.value);
refNode = ref[0];
// The next node is also set to undefined because nothing
// could be found, this reference points to nothing, so
// nothing must be returned.
if (!refNode) {
out = void 0;
next = void 0;
break;
}
type = refNode.$type;
next = refNode;
optimizedPath = ref[1].slice(0);
}
if (type) {
break;
}
}
// If there is a value, then we have great success, else, report an undefined.
else {
out = next;
}
curr = next;
}
if (depth < len) {
// Unfortunately, if all that follows are nulls, then we have not shorted.
for (i = depth; i < len; ++i) {
if (simplePath[depth] !== null) {
shouldShort = true;
break;
}
}
// if we should short or report value. Values are reported on nulls.
if (shouldShort) {
shorted = true;
out = void 0;
} else {
out = next;
}
for (i = depth; i < len; ++i) {
optimizedPath[optimizedPath.length] = simplePath[i];
}
}
// promotes if not expired
if (out && type) {
if (isExpired(out)) {
out = void 0;
} else {
promote(model, out);
}
}
// if (out && out.$type === $error && !model._treatErrorsAsValues) {
if (out && type === $error && !model._treatErrorsAsValues) {
throw {
path: depth === len ? simplePath : simplePath.slice(0, depth),
value: out.value
};
} else if (out && model._boxed) {
out = Boolean(type) && !noClone ? clone(out) : out;
} else if (!out && model._materialized) {
out = {$type: $atom};
} else if (out) {
out = out.value;
}
return {
value: out,
shorted: shorted,
optimizedPath: optimizedPath,
found: found
};
};
},{"124":124,"125":125,"126":126,"22":22,"24":24,"27":27,"9":9}],16:[function(require,module,exports){
var __version = require(44);
module.exports = function _getVersion(model, path) {
// ultra fast clone for boxed values.
var gen = model._getValueSync({
_boxed: true,
_root: model._root,
_treatErrorsAsValues: model._treatErrorsAsValues
}, path, true).value;
var version = gen && gen[__version];
return (version == null) ? -1 : version;
};
},{"44":44}],17:[function(require,module,exports){
var followReference = require(9);
var onError = require(18);
var onMissing = require(19);
var onValue = require(20);
var lru = require(27);
var hardLink = require(23);
var isMaterialized = require(25);
var removeHardlink = hardLink.remove;
var splice = lru.splice;
var isExpired = require(24);
var iterateKeySet = require(157).iterateKeySet;
var $ref = require(126);
var $error = require(125);
var __invalidated = require(33);
var prefix = require(38);
function getWalk(model, root, curr, pathOrJSON, depthArg, seedOrFunction, positionalInfoArg, outerResults, optimizedPath, requestedPath, inputFormat, outputFormat, fromReferenceArg) {
var depth = depthArg;
var fromReference = fromReferenceArg;
var positionalInfo = positionalInfoArg;
if ((!curr || curr && curr.$type) &&
evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfo, outerResults, outputFormat, fromReference)) {
return;
}
// We continue the search to the end of the path/json structure.
else {
// Base case of the searching: Have we hit the end of the road?
// Paths
// 1) depth === path.length
// PathMaps (json input)
// 2) if its an object with no keys
// 3) its a non-object
var jsonQuery = inputFormat === "JSON";
var atEndOfJSONQuery = false;
var keySet, i, len;
if (jsonQuery) {
// it has a $type property means we have hit a end.
if (pathOrJSON && pathOrJSON.$type) {
atEndOfJSONQuery = true;
}
else if (pathOrJSON && typeof pathOrJSON === "object") {
keySet = Object.keys(pathOrJSON);
// Parses out all the prefix keys so that later parts
// of the algorithm do not have to consider them.
var parsedKeys = [];
var parsedKeysLength = -1;
for (i = 0, len = keySet.length; i < len; ++i) {
if (keySet[i][0] !== prefix && keySet[i][0] !== "$") {
parsedKeys[++parsedKeysLength] = keySet[i];
}
}
keySet = parsedKeys;
if (keySet.length === 1) {
keySet = keySet[0];
}
}
// found a primitive, we hit the end.
else {
atEndOfJSONQuery = true;
}
} else {
keySet = pathOrJSON[depth];
}
// BaseCase: we have hit the end of our query without finding a "leaf" node, therefore emit missing.
if (atEndOfJSONQuery || !jsonQuery && depth === pathOrJSON.length) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
return;
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
return;
}
var iteratorNote = {};
var permutePosition = positionalInfo;
var permuteRequested = requestedPath;
var permuteOptimized = optimizedPath;
var asJSONG = outputFormat === "JSONG";
var asJSON = outputFormat === "JSON";
var isKeySet = false;
var hasChildren = false;
depth++;
var key = iterateKeySet(keySet, iteratorNote);
// Checks for empty keyset values. This happens when the iterator
// comes back empty.
if (key === void 0 && iteratorNote.done) {
return;
}
isKeySet = !iteratorNote.done;
if (asJSON && isKeySet) {
permutePosition = [];
for (i = 0, len = positionalInfo.length; i < len; i++) {
permutePosition[i] = positionalInfo[i];
}
permutePosition.push(depth - 1);
}
do {
fromReference = false;
if (isKeySet) {
permuteOptimized = [];
permuteRequested = [];
for (i = 0, len = requestedPath.length; i < len; i++) {
permuteRequested[i] = requestedPath[i];
}
for (i = 0, len = optimizedPath.length; i < len; i++) {
permuteOptimized[i] = optimizedPath[i];
}
}
var nextPathOrPathMap = jsonQuery ? pathOrJSON[key] : pathOrJSON;
if (jsonQuery && nextPathOrPathMap) {
if (typeof nextPathOrPathMap === "object") {
if (nextPathOrPathMap.$type) {
hasChildren = false;
} else {
hasChildren = Object.keys(nextPathOrPathMap).length > 0;
}
}
}
var next;
if (key === null || jsonQuery && key === "__null") {
next = curr;
} else {
next = curr[key];
permuteOptimized.push(key);
permuteRequested.push(key);
}
if (next) {
var nType = next.$type;
var value = nType && next.value || next;
if (jsonQuery && hasChildren || !jsonQuery && depth < pathOrJSON.length) {
if (nType && nType === $ref && !isExpired(next)) {
if (asJSONG) {
onValue(model, next, seedOrFunction, outerResults, false, permuteOptimized, permutePosition, outputFormat);
}
var ref = followReference(model, root, root, next, value, seedOrFunction, outputFormat);
fromReference = true;
next = ref[0];
var refPath = ref[1];
permuteOptimized = [];
for (i = 0, len = refPath.length; i < len; i++) {
permuteOptimized[i] = refPath[i];
}
}
}
}
getWalk(model, root, next, nextPathOrPathMap, depth, seedOrFunction, permutePosition, outerResults, permuteOptimized, permuteRequested, inputFormat, outputFormat, fromReference);
if (!iteratorNote.done) {
key = iterateKeySet(keySet, iteratorNote);
}
} while (!iteratorNote.done);
}
}
function evaluateNode(model, curr, pathOrJSON, depth, seedOrFunction, requestedPath, optimizedPath, positionalInfoArg, outerResults, outputFormat, fromReference) {
var positionalInfo = positionalInfoArg;
// BaseCase: This position does not exist, emit missing.
if (!curr) {
if (isMaterialized(model)) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
}
return true;
}
var currType = curr.$type;
positionalInfo = positionalInfo || [];
// The Base Cases. There is a type, therefore we have hit a "leaf" node.
if (currType === $error) {
if (fromReference) {
requestedPath.push(null);
}
if (outputFormat === "JSONG" || model._treatErrorsAsValues) {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
} else {
onError(model, curr, requestedPath, optimizedPath, outerResults);
}
}
// Else we have found a value, emit the current position information.
else if (isExpired(curr)) {
if (!curr[__invalidated]) {
splice(model, curr);
removeHardlink(curr);
}
onMissing(model, curr, pathOrJSON, depth, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat);
} else {
onValue(model, curr, seedOrFunction, outerResults, requestedPath, optimizedPath, positionalInfo, outputFormat, fromReference);
}
return true;
}
module.exports = getWalk;
},{"125":125,"126":126,"157":157,"18":18,"19":19,"20":20,"23":23,"24":24,"25":25,"27":27,"33":33,"38":38,"9":9}],18:[function(require,module,exports){
var lru = require(27);
var clone = require(22);
var promote = lru.promote;
module.exports = function onError(model, node, permuteRequested, permuteOptimized, outerResults) {
var value = node.value;
if (model._boxed) {
value = clone(node);
}
outerResults.errors.push({path: permuteRequested, value: value});
promote(model, node);
};
},{"22":22,"27":27}],19:[function(require,module,exports){
var support = require(29);
var fastCat = support.fastCat,
fastCatSkipNulls = support.fastCatSkipNulls,
fastCopy = support.fastCopy;
var spreadJSON = require(28);
module.exports = function onMissing(model, node, path, depth, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat) {
var pathSlice;
if (Array.isArray(path)) {
if (depth < path.length) {
pathSlice = fastCopy(path, depth);
} else {
pathSlice = [];
}
concatAndInsertMissing(pathSlice, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat);
} else {
pathSlice = [];
spreadJSON(path, pathSlice);
for (var i = 0, len = pathSlice.length; i < len; i++) {
concatAndInsertMissing(pathSlice[i], outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, true);
}
}
};
function concatAndInsertMissing(remainingPath, results, permuteRequestedArg, permuteOptimized, permutePosition, outputFormat, __null) {
var permuteRequested = permuteRequestedArg;
var i = 0, len;
if (__null) {
for (i = 0, len = remainingPath.length; i < len; i++) {
if (remainingPath[i] === "__null") {
remainingPath[i] = null;
}
}
}
if (outputFormat === "JSON") {
permuteRequested = fastCat(permuteRequested, remainingPath);
for (i = 0, len = permutePosition.length; i < len; i++) {
var idx = permutePosition[i];
var r = permuteRequested[idx];
permuteRequested[idx] = [r];
}
results.requestedMissingPaths.push(permuteRequested);
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
} else {
results.requestedMissingPaths.push(fastCat(permuteRequested, remainingPath));
results.optimizedMissingPaths.push(fastCatSkipNulls(permuteOptimized, remainingPath));
}
}
},{"28":28,"29":29}],20:[function(require,module,exports){
var lru = require(27);
var clone = require(22);
var promote = lru.promote;
var $ref = require(126);
var $atom = require(124);
var $error = require(125);
module.exports = function onValue(model, node, seedOrFunction, outerResults, permuteRequested, permuteOptimized, permutePosition, outputFormat, fromReference) {
var i, len, k, key, curr, prev, prevK;
var materialized = false, valueNode;
if (node) {
promote(model, node);
}
if (!node || node.value === void 0) {
materialized = model._materialized;
}
// materialized
if (materialized) {
valueNode = {$type: $atom};
}
// Boxed Mode will clone the node.
else if (model._boxed) {
valueNode = clone(node);
}
// JSONG always clones the node.
else if (node.$type === $ref || node.$type === $error) {
if (outputFormat === "JSONG") {
valueNode = clone(node);
} else {
valueNode = node.value;
}
}
else if (outputFormat === "JSONG") {
if (typeof node.value === "object") {
valueNode = clone(node);
} else {
valueNode = node.value;
}
}
else {
valueNode = node.value;
}
if (permuteRequested) {
if (fromReference && permuteRequested[permuteRequested.length - 1] !== null) {
permuteRequested.push(null);
}
outerResults.requestedPaths.push(permuteRequested);
outerResults.optimizedPaths.push(permuteOptimized);
}
switch (outputFormat) {
case "Values":
// Its difficult to invert this statement, so for now i am going
// to leave it as is. This just prevents onNexts from happening on
// undefined nodes
if (valueNode === void 0 ||
!materialized && !model._boxed && valueNode &&
valueNode.$type === $atom && valueNode.value === void 0) {
return;
}
seedOrFunction({path: permuteRequested, value: valueNode});
break;
case "PathMap":
len = permuteRequested.length - 1;
if (len === -1) {
seedOrFunction.json = valueNode;
} else {
curr = seedOrFunction.json;
if (!curr) {
curr = seedOrFunction.json = {};
}
for (i = 0; i < len; i++) {
k = permuteRequested[i];
if (!curr[k]) {
curr[k] = {};
}
prev = curr;
prevK = k;
curr = curr[k];
}
k = permuteRequested[i];
if (k !== null) {
curr[k] = valueNode;
} else {
prev[prevK] = valueNode;
}
}
break;
case "JSON":
if (seedOrFunction) {
if (permutePosition.length) {
if (!seedOrFunction.json) {
seedOrFunction.json = {};
}
curr = seedOrFunction.json;
for (i = 0, len = permutePosition.length - 1; i < len; i++) {
k = permutePosition[i];
key = permuteRequested[k];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
k = permutePosition[i];
key = permuteRequested[k];
curr[key] = valueNode;
} else {
seedOrFunction.json = valueNode;
}
}
break;
case "JSONG":
curr = seedOrFunction.jsonGraph;
if (!curr) {
curr = seedOrFunction.jsonGraph = {};
seedOrFunction.paths = [];
}
for (i = 0, len = permuteOptimized.length - 1; i < len; i++) {
key = permuteOptimized[i];
if (!curr[key]) {
curr[key] = {};
}
curr = curr[key];
}
// assign the last
key = permuteOptimized[i];
// TODO: Special case? do string comparisons make big difference?
curr[key] = materialized ? {$type: $atom} : valueNode;
if (permuteRequested) {
seedOrFunction.paths.push(permuteRequested);
}
break;
default:
break;
}
};
},{"124":124,"125":125,"126":126,"22":22,"27":27}],21:[function(require,module,exports){
var pathSyntax = require(149);
module.exports = function getValueSync(pathArg) {
var path = pathSyntax.fromPath(pathArg);
if (Array.isArray(path) === false) {
throw new Error("Model#getValueSync must be called with an Array path.");
}
if (this._path.length) {
path = this._path.concat(path);
}
return this.syncCheck("getValueSync") && this._getValueSync(this, path).value;
};
},{"149":149}],22:[function(require,module,exports){
// Copies the node
var prefix = require(38);
module.exports = function clone(node) {
var outValue, i, len;
var keys = Object.keys(node);
outValue = {};
for (i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
if (k[0] === prefix) {
continue;
}
outValue[k] = node[k];
}
return outValue;
};
},{"38":38}],23:[function(require,module,exports){
var __ref = require(41);
var __context = require(31);
var __refIndex = require(40);
var __refsLength = require(42);
function createHardlink(from, to) {
// create a back reference
var backRefs = to[__refsLength] || 0;
to[__ref + backRefs] = from;
to[__refsLength] = backRefs + 1;
// create a hard reference
from[__refIndex] = backRefs;
from[__context] = to;
}
function removeHardlink(cacheObject) {
var context = cacheObject[__context];
if (context) {
var idx = cacheObject[__refIndex];
var len = context[__refsLength];
while (idx < len) {
context[__ref + idx] = context[__ref + idx + 1];
++idx;
}
context[__refsLength] = len - 1;
cacheObject[__context] = void 0;
cacheObject[__refIndex] = void 0;
}
}
module.exports = {
create: createHardlink,
remove: removeHardlink
};
},{"31":31,"40":40,"41":41,"42":42}],24:[function(require,module,exports){
var now = require(109);
module.exports = function isExpired(node) {
var $expires = node.$expires === void 0 && -1 || node.$expires;
return $expires !== -1 && $expires !== 1 && ($expires === 0 || $expires < now());
};
},{"109":109}],25:[function(require,module,exports){
module.exports = function isMaterialized(model) {
return model._materialized && !model._source;
};
},{}],26:[function(require,module,exports){
module.exports = function isPathValue(x) {
return x.path && x.value;
};
},{}],27:[function(require,module,exports){
var __head = require(32);
var __tail = require(43);
var __next = require(35);
var __prev = require(39);
var __invalidated = require(33);
// [H] -> Next -> ... -> [T]
// [T] -> Prev -> ... -> [H]
function lruPromote(model, object) {
var root = model._root;
var head = root[__head];
if (head === object) {
return;
}
// First insert
if (!head) {
root[__head] = object;
return;
}
// The head and the tail need to separate
if (!root[__tail]) {
root[__head] = object;
root[__tail] = head;
object[__next] = head;
// Now tail
head[__prev] = object;
return;
}
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = void 0;
// Insert into head position
root[__head] = object;
object[__next] = head;
head[__prev] = object;
}
function lruSplice(model, object) {
var root = model._root;
// Its in the cache. Splice out.
var prev = object[__prev];
var next = object[__next];
if (next) {
next[__prev] = prev;
}
if (prev) {
prev[__next] = next;
}
object[__prev] = void 0;
if (object === root[__head]) {
root[__head] = void 0;
}
if (object === root[__tail]) {
root[__tail] = void 0;
}
object[__invalidated] = true;
root.expired.push(object);
}
module.exports = {
promote: lruPromote,
splice: lruSplice
};
},{"32":32,"33":33,"35":35,"39":39,"43":43}],28:[function(require,module,exports){
var fastCopy = require(29).fastCopy;
module.exports = function spreadJSON(root, bins, binArg) {
var bin = binArg || [];
if (!bins.length) {
bins.push(bin);
}
if (!root || typeof root !== "object" || root.$type) {
return [];
}
var keys = Object.keys(root);
if (keys.length === 1) {
bin.push(keys[0]);
spreadJSON(root[keys[0]], bins, bin);
} else {
for (var i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
var nextBin = fastCopy(bin);
nextBin.push(k);
bins.push(nextBin);
spreadJSON(root[k], bins, nextBin);
}
}
};
},{"29":29}],29:[function(require,module,exports){
function fastCopy(arr, iArg) {
var a = [], len, j, i;
for (j = 0, i = iArg || 0, len = arr.length; i < len; j++, i++) {
a[j] = arr[i];
}
return a;
}
function fastCatSkipNulls(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
if (arr2[j] !== null) {
a[i++] = arr2[j];
}
}
return a;
}
function fastCat(arr1, arr2) {
var a = [], i, len, j;
for (i = 0, len = arr1.length; i < len; i++) {
a[i] = arr1[i];
}
for (j = 0, len = arr2.length; j < len; j++) {
a[i++] = arr2[j];
}
return a;
}
module.exports = {
fastCat: fastCat,
fastCatSkipNulls: fastCatSkipNulls,
fastCopy: fastCopy
};
},{}],30:[function(require,module,exports){
"use strict";
function falcor(opts) {
return new falcor.Model(opts);
}
if (typeof Promise !== "undefined" && Promise) {
falcor.Promise = Promise;
} else {
falcor.Promise = require(162);
}
module.exports = falcor;
falcor.Model = require(2);
},{"162":162,"2":2}],31:[function(require,module,exports){
module.exports = require(38) + "context";
},{"38":38}],32:[function(require,module,exports){
module.exports = require(38) + "head";
},{"38":38}],33:[function(require,module,exports){
module.exports = require(38) + "invalidated";
},{"38":38}],34:[function(require,module,exports){
module.exports = require(38) + "key";
},{"38":38}],35:[function(require,module,exports){
module.exports = require(38) + "next";
},{"38":38}],36:[function(require,module,exports){
module.exports = require(38) + "offset";
},{"38":38}],37:[function(require,module,exports){
module.exports = require(38) + "parent";
},{"38":38}],38:[function(require,module,exports){
/**
* http://en.wikipedia.org/wiki/Delimiter#ASCIIDelimitedText
* record separator character.
*/
module.exports = String.fromCharCode(30);
},{}],39:[function(require,module,exports){
module.exports = require(38) + "prev";
},{"38":38}],40:[function(require,module,exports){
module.exports = require(38) + "ref-index";
},{"38":38}],41:[function(require,module,exports){
module.exports = require(38) + "ref";
},{"38":38}],42:[function(require,module,exports){
module.exports = require(38) + "refs-length";
},{"38":38}],43:[function(require,module,exports){
module.exports = require(38) + "tail";
},{"38":38}],44:[function(require,module,exports){
module.exports = require(38) + "version";
},{"38":38}],45:[function(require,module,exports){
module.exports = invalidateJsonSparseAsJsonDense;
var clone = require(84);
var arrayClone = require(79);
var arraySlice = require(83);
var options = require(110);
var walkPathMap = require(130);
var isObject = require(103);
var getValidKey = require(94);
var updateGraph = require(121);
var invalidateNode = require(98);
var positions = require(112);
var _cache = positions.cache;
var _json = positions.json;
function invalidateJsonSparseAsJsonDense(model, pathmaps, values, errorSelector, comparator) {
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var keysStack = [];
var json, hasValue, hasValues;
roots[_cache] = roots.root;
while (++index < count) {
json = values && values[index];
if (isObject(json)) {
roots.json = roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
} else {
roots.json = roots[_json] = parents[_json] = nodes[_json] = void 0;
}
var pathmap = pathmaps[index].json;
roots.index = index;
walkPathMap(onNode, onEdge, pathmap, keysStack, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (Boolean(hasValue)) {
hasValues = true;
if (isObject(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (isObject(json)) {
delete json.json;
}
}
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_json];
parent = parents[_cache];
} else {
json = isKeyset && nodes[_json] || parents[_json];
parent = nodes[_cache];
}
var node = parent[key];
if (isReference) {
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
parents[_json] = json;
if (isBranch) {
parents[_cache] = nodes[_cache] = node;
if (isKeyset && Boolean(json)) {
nodes[_json] = json[keyset] || (json[keyset] = {});
}
return;
}
nodes[_cache] = node;
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidateNode(parent, node, key, lru);
updateGraph(parent, size, version, lru);
}
function onEdge(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
if (keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else {
json = parents[_json];
if (Boolean(json)) {
json[keyset] = clone(roots, node, type, node && node.value);
}
}
roots.hasValue = true;
roots.requestedPaths.push(arraySlice(requested, roots.offset));
}
},{"103":103,"110":110,"112":112,"121":121,"130":130,"79":79,"83":83,"84":84,"94":94,"98":98}],46:[function(require,module,exports){
module.exports = invalidatePathSetsAsJsonDense;
var clone = require(84);
var arrayClone = require(79);
var arraySlice = require(83);
var options = require(110);
var walkPathSet = require(132);
var isObject = require(103);
var getValidKey = require(94);
var updateGraph = require(121);
var invalidateNode = require(98);
var positions = require(112);
var _cache = positions.cache;
var _json = positions.json;
function invalidatePathSetsAsJsonDense(model, pathsets, values) {
var roots = options([], model);
var index = -1;
var count = pathsets.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = [];
var json;
roots[_cache] = roots.root;
while (++index < count) {
json = values && values[index];
if (isObject(json)) {
roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
} else {
roots[_json] = parents[_json] = nodes[_json] = void 0;
}
var pathset = pathsets[index];
roots.index = index;
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
if (isObject(json)) {
json.json = roots.json;
}
delete roots.json;
}
return {
values: values,
errors: roots.errors,
hasValue: true,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_json];
parent = parents[_cache];
} else {
json = isKeyset && nodes[_json] || parents[_json];
parent = nodes[_cache];
}
var node = parent[key];
if (isReference) {
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
parents[_json] = json;
if (isBranch) {
parents[_cache] = nodes[_cache] = node;
if (isKeyset && Boolean(json)) {
nodes[_json] = json[keyset] || (json[keyset] = {});
}
return;
}
nodes[_cache] = node;
var lru = roots.lru;
var size = node.$size || 0;
var version = roots.version;
invalidateNode(parent, node, key, roots.lru);
updateGraph(parent, size, version, lru);
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
if (keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else {
json = parents[_json];
if (Boolean(json)) {
json[keyset] = clone(roots, node, type, node && node.value);
}
}
roots.hasValue = true;
roots.requestedPaths.push(arraySlice(requested, roots.offset));
}
},{"103":103,"110":110,"112":112,"121":121,"132":132,"79":79,"83":83,"84":84,"94":94,"98":98}],47:[function(require,module,exports){
var __key = require(34);
var __parent = require(37);
var __head = require(32);
var __tail = require(43);
var __next = require(35);
var __prev = require(39);
var removeNode = require(113);
var updateGraph = require(121);
module.exports = function collect(lru, expired, totalArg, max, ratioArg, version) {
var total = totalArg;
var ratio = ratioArg;
if (typeof ratio !== "number") {
ratio = 0.75;
}
var shouldUpdate = typeof version === "number";
var targetSize = max * ratio;
var parent, node, size;
node = expired.pop();
while (node) {
size = node.$size || 0;
total -= size;
if (shouldUpdate === true) {
updateGraph(node, size, version, lru);
} else if (parent = node[__parent]) {
removeNode(parent, node, node[__key], lru);
}
node = expired.pop();
}
if (total >= max) {
var prev = lru[__tail];
node = prev;
while ((total >= targetSize) && node) {
prev = prev[__prev];
size = node.$size || 0;
total -= size;
if (shouldUpdate === true) {
updateGraph(node, size, version, lru);
}
node = prev;
}
lru[__tail] = lru[__prev] = node;
if (node == null) {
lru[__head] = lru[__next] = void 0;
} else {
node[__next] = void 0;
}
}
};
},{"113":113,"121":121,"32":32,"34":34,"35":35,"37":37,"39":39,"43":43}],48:[function(require,module,exports){
var $expiresNever = require(127);
var __head = require(32);
var __tail = require(43);
var __next = require(35);
var __prev = require(39);
var isObject = require(103);
module.exports = function lruPromote(root, node) {
if (isObject(node) && (node.$expires !== $expiresNever)) {
var head = root[__head],
tail = root[__tail],
next = node[__next],
prev = node[__prev];
if (node !== head) {
if (next != null && typeof next === "object") {
next[__prev] = prev;
}
if (prev != null && typeof prev === "object") {
prev[__next] = next;
}
next = head;
if (head != null && typeof head === "object") {
head[__prev] = node;
}
root[__head] = root[__next] = head = node;
head[__next] = next;
head[__prev] = void 0;
}
if (tail == null || node === tail) {
root[__tail] = root[__prev] = tail = prev || node;
}
}
return node;
};
},{"103":103,"127":127,"32":32,"35":35,"39":39,"43":43}],49:[function(require,module,exports){
var __head = require(32);
var __tail = require(43);
var __next = require(35);
var __prev = require(39);
module.exports = function lruSplice(root, node) {
var head = root[__head],
tail = root[__tail],
next = node[__next],
prev = node[__prev];
if (next != null && typeof next === "object") {
next[__prev] = prev;
}
if (prev != null && typeof prev === "object") {
prev[__next] = next;
}
if (node === head) {
root[__head] = root[__next] = next;
}
if (node === tail) {
root[__tail] = root[__prev] = prev;
}
node[__next] = node[__prev] = void 0;
head = tail = next = prev = void 0;
};
},{"32":32,"35":35,"39":39,"43":43}],50:[function(require,module,exports){
var Rx = require(171) && require(170);
var Observable = Rx.Observable;
var immediateScheduler = Rx.Scheduler.immediate;
var Request = require(52);
function BatchedRequest() {
Request.call(this);
}
BatchedRequest.create = Request.create;
BatchedRequest.prototype = Object.create(Request.prototype);
BatchedRequest.prototype.constructor = BatchedRequest;
BatchedRequest.prototype.getSourceObservable = function getSourceObservable() {
if (this.refCountedObservable) {
return this.refCountedObservable;
}
var count = 0;
var source = this;
var subject = new Rx.ReplaySubject(null, null, immediateScheduler);
var connection = null;
var refCountedObservable = Observable.create(function subscribe(observer) {
if (++count === 1 && !connection) {
connection = source.subscribe(subject);
}
var subscription = subject.subscribe(observer);
return function dispose() {
subscription.dispose();
if (--count === 0) {
connection.dispose();
}
};
});
this.refCountedObservable = refCountedObservable;
return refCountedObservable;
};
module.exports = BatchedRequest;
},{"170":170,"171":171,"52":52}],51:[function(require,module,exports){
var Rx = require(171);
var Observer = Rx.Observer;
var BatchedRequest = require(50);
var falcorPathUtils = require(157);
var toPaths = falcorPathUtils.toPaths;
var arrayMap = require(82);
var setJsonGraphAsJsonDense = require(65);
var setJsonValuesAsJsonDense = require(73);
var emptyArray = new Array(0);
var $error = require(125);
function GetRequest() {
BatchedRequest.call(this);
}
GetRequest.create = BatchedRequest.create;
GetRequest.prototype = Object.create(BatchedRequest.prototype);
GetRequest.prototype.constructor = GetRequest;
GetRequest.prototype.method = "get";
GetRequest.prototype.getSourceArgs = function getSourceArgs() {
this.paths = toPaths(this.pathmaps);
return this.paths;
};
GetRequest.prototype.getSourceObserver = function getSourceObserver(observer) {
var model = this.model;
var bound = model._path;
var paths = this.paths;
var modelRoot = model._root;
var errorSelector = modelRoot.errorSelector;
var comparator = modelRoot.comparator;
return BatchedRequest.prototype.getSourceObserver.call(this, Observer.create(
function onNext(jsonGraphEnvelope) {
model._path = emptyArray;
var result = setJsonGraphAsJsonDense(model, [{
paths: paths,
jsonGraph: jsonGraphEnvelope.jsonGraph
}], emptyArray, errorSelector, comparator);
jsonGraphEnvelope.paths = result.requestedPaths.concat(result.errors.map(getPath));
model._path = bound;
observer.onNext(jsonGraphEnvelope);
},
function onError(errorArg) {
var error = errorArg;
model._path = emptyArray;
// Converts errors to objects, a more friendly storage
// of errors.
if (error instanceof Error) {
error = {
message: error.message
};
}
// Not all errors are value $types.
if (!error.$type) {
error = {
$type: $error,
value: error
};
}
setJsonValuesAsJsonDense(model, arrayMap(paths, function(path) {
return {
path: path,
value: error
};
}), emptyArray, errorSelector, comparator);
model._path = bound;
observer.onError(error);
},
function onCompleted() {
observer.onCompleted();
}
));
};
function getPath(pv) {
return pv.path;
}
module.exports = GetRequest;
},{"125":125,"157":157,"171":171,"50":50,"65":65,"73":73,"82":82}],52:[function(require,module,exports){
var Rx = require(171);
var Observer = Rx.Observer;
var Observable = Rx.Observable;
var Disposable = Rx.Disposable;
var SerialDisposable = Rx.SerialDisposable;
var CompositeDisposable = Rx.CompositeDisposable;
var InvalidSourceError = require(8);
var falcorPathUtils = require(157);
var iterateKeySet = falcorPathUtils.iterateKeySet;
function Request() {
this.length = 0;
this.pending = false;
this.pathmaps = [];
Observable.call(this, this._subscribe);
}
Request.create = function create(queue, model, index) {
var request = new this();
request.queue = queue;
request.model = model;
request.index = index;
return request;
};
Request.prototype = Object.create(Observable.prototype);
Request.prototype.constructor = Request;
Request.prototype.insertPath = function insertPathIntoRequest(path, union, parentArg, indexArg, countArg) {
var index = indexArg || 0;
var count = countArg || path.length - 1;
var parent = parentArg || this.pathmaps[count + 1] || (this.pathmaps[count + 1] = Object.create(null));
if (parent === void 0 || parent === null) {
return false;
}
var key, node;
var keySet = path[index];
var iteratorNote = {};
key = iterateKeySet(keySet, iteratorNote);
// Determines if the key needs to go through permutation or not.
// All object based keys require this.
do {
node = parent[key];
if (index < count) {
if (node == null) {
if (union) {
return false;
}
node = parent[key] = Object.create(null);
}
if (this.insertPath(path, union, node, index + 1, count) === false) {
return false;
}
} else {
parent[key] = (node || 0) + 1;
this.length += 1;
}
if (!iteratorNote.done) {
key = iterateKeySet(keySet, iteratorNote);
}
} while (!iteratorNote.done);
return true;
};
/* eslint-disable guard-for-in */
Request.prototype.removePath = function removePathFromRequest(path, parentArg, indexArg, countArg) {
var index = indexArg || 0;
var count = countArg || path.length - 1;
var parent = parentArg || this.pathmaps[count + 1];
if (parent === void 0 || parent === null) {
return true;
}
var key, node, deleted = 0;
var keySet = path[index];
var iteratorNote = {};
key = iterateKeySet(keySet, iteratorNote);
do {
node = parent[key];
if (node === void 0 || node === null) {
continue;
} else if (index < count) {
deleted += this.removePath(path, node, index + 1, count);
var emptyNodeKey = void 0;
for (emptyNodeKey in node) {
break;
}
if (emptyNodeKey === void 0) {
delete parent[key];
}
} else {
node = parent[key] = (node || 1) - 1;
if (node === 0) {
delete parent[key];
}
deleted += 1;
this.length -= 1;
}
if (!iteratorNote.done) {
key = iterateKeySet(keySet, iteratorNote);
}
} while (!iteratorNote.done);
return deleted;
};
/* eslint-enable */
Request.prototype.getSourceObserver = function getSourceObserver(observer) {
var request = this;
return Observer.create(
function onNext(envelope) {
envelope.jsonGraph = envelope.jsonGraph ||
envelope.jsong ||
envelope.values ||
envelope.value;
envelope.index = request.index;
observer.onNext(envelope);
},
function onError(e) {
observer.onError(e);
},
function onCompleted() {
observer.onCompleted();
});
};
Request.prototype._subscribe = function _subscribe(observer) {
var request = this;
var queue = this.queue;
request.pending = true;
var isDisposed = false;
var sourceSubscription = new SerialDisposable();
var queueDisposable = Disposable.create(function() {
if (!isDisposed) {
isDisposed = true;
if (queue) {
queue._remove(request);
}
}
});
var disposables = new CompositeDisposable(sourceSubscription, queueDisposable);
try {
sourceSubscription.setDisposable(
this.model._source[this.method](this.getSourceArgs())
.subscribe(this.getSourceObserver(observer)));
} catch (e) {
// We need a way to communicate out to the rest of the world that
// this error needs to continue its propagation.
throw new InvalidSourceError(e);
}
return disposables;
};
module.exports = Request;
},{"157":157,"171":171,"8":8}],53:[function(require,module,exports){
var Rx = require(171) && require(169);
var Observable = Rx.Observable;
var GetRequest = require(51);
var SetRequest = require(54);
var prefix = require(38);
var getType = require(93);
var isObject = require(103);
var arrayClone = require(79);
var falcorPathUtils = require(157);
/* eslint-disable no-labels block-scoped-var */
function RequestQueue(model, scheduler) {
this.total = 0;
this.model = model;
this.requests = [];
this.scheduler = scheduler;
}
RequestQueue.prototype.get = function getRequest(paths) {
var self = this;
return Observable.defer(function() {
var requests = self.distributePaths(paths, self.requests, GetRequest);
return (Observable.defer(function() {
return Observable.fromArray(requests.map(function(request) {
return request.getSourceObservable();
}));
})
.mergeAll()
.reduce(self.mergeJSONGraphs, {
index: -1,
jsonGraph: {}
})
.map(function(response) {
return {
paths: paths,
index: response.index,
jsonGraph: response.jsonGraph
};
})
.subscribeOn(self.scheduler).finally(function() {
var paths2 = arrayClone(paths);
var pathCount = paths2.length;
var requestIndex = -1;
var requestCount = requests.length;
while (pathCount > 0 && requestCount > 0 && ++requestIndex < requestCount) {
var request = requests[requestIndex];
if (request.pending) {
continue;
}
var pathIndex = -1;
while (++pathIndex < pathCount) {
var path = paths2[pathIndex];
if (request.removePath(path)) {
paths2.splice(pathIndex--, 1);
if (--pathCount === 0) {
break;
}
}
}
if (request.length === 0) {
requests.splice(requestIndex--, 1);
if (--requestCount === 0) {
break;
}
}
}
}));
});
};
RequestQueue.prototype.set = function setRequest(jsonGraphEnvelope) {
jsonGraphEnvelope.paths = falcorPathUtils.collapse(jsonGraphEnvelope.paths);
return SetRequest.create(this.model, jsonGraphEnvelope);
};
RequestQueue.prototype._remove = function removeRequest(request) {
var requests = this.requests;
var index = requests.indexOf(request);
if (index !== -1) {
requests.splice(index, 1);
}
};
RequestQueue.prototype.distributePaths = function distributePathsAcrossRequests(paths, requests, RequestType) {
var model = this.model;
var pathsIndex = -1;
var pathsCount = paths.length;
var requestIndex = -1;
var requestCount = requests.length;
var participatingRequests = [];
var pendingRequest;
var request;
insertPath: while (++pathsIndex < pathsCount) {
var path = paths[pathsIndex];
requestIndex = -1;
while (++requestIndex < requestCount) {
request = requests[requestIndex];
if (request.insertPath(path, request.pending)) {
participatingRequests[requestIndex] = request;
continue insertPath;
}
}
if (!pendingRequest) {
pendingRequest = RequestType.create(this, model, this.total++);
requests[requestIndex] = pendingRequest;
participatingRequests[requestCount++] = pendingRequest;
}
pendingRequest.insertPath(path, false);
}
var pathRequests = [];
var pathRequestsIndex = -1;
requestIndex = -1;
while (++requestIndex < requestCount) {
request = participatingRequests[requestIndex];
if (request != null) {
pathRequests[++pathRequestsIndex] = request;
}
}
return pathRequests;
};
RequestQueue.prototype.mergeJSONGraphs = function mergeJSONGraphs(aggregate, response) {
var depth = 0;
var contexts = [];
var messages = [];
var keystack = [];
var latestIndex = aggregate.index;
var responseIndex = response.index;
aggregate.index = Math.max(latestIndex, responseIndex);
contexts[-1] = aggregate.jsonGraph || {};
messages[-1] = response.jsonGraph || {};
recursing: while (depth > -1) {
var context = contexts[depth - 1];
var message = messages[depth - 1];
var keys = keystack[depth - 1] || (keystack[depth - 1] = Object.keys(message));
while (keys.length > 0) {
var key = keys.pop();
if (key[0] === prefix) {
continue;
}
if (context.hasOwnProperty(key)) {
var node = context[key];
var nodeType = getType(node);
var messageNode = message[key];
var messageType = getType(messageNode);
if (isObject(node) && isObject(messageNode) && !nodeType && !messageType) {
contexts[depth] = node;
messages[depth] = messageNode;
depth += 1;
continue recursing;
} else if (responseIndex > latestIndex) {
context[key] = messageNode;
}
} else {
context[key] = message[key];
}
}
depth -= 1;
}
return aggregate;
};
/* eslint-enable */
module.exports = RequestQueue;
},{"103":103,"157":157,"169":169,"171":171,"38":38,"51":51,"54":54,"79":79,"93":93}],54:[function(require,module,exports){
var Rx = require(171);
var Observer = Rx.Observer;
var Request = require(52);
var arrayMap = require(82);
var setJsonGraphAsJsonDense = require(65);
var setJsonValuesAsJsonDense = require(73);
var collapse = require(157).collapse;
var emptyArray = new Array(0);
function SetRequest() {
Request.call(this);
}
SetRequest.create = function create(model, jsonGraphEnvelope) {
var request = new SetRequest();
request.model = model;
request.jsonGraphEnvelope = jsonGraphEnvelope;
return request;
};
SetRequest.prototype = Object.create(Request.prototype);
SetRequest.prototype.constructor = SetRequest;
SetRequest.prototype.method = "set";
SetRequest.prototype.insertPath = function() {
return false;
};
SetRequest.prototype.removePath = function() {
return 0;
};
SetRequest.prototype.getSourceArgs = function getSourceArgs() {
return this.jsonGraphEnvelope;
};
SetRequest.prototype.getSourceObserver = function getSourceObserver(observer) {
var model = this.model;
var bound = model._path;
var paths = this.jsonGraphEnvelope.paths;
var modelRoot = model._root;
var errorSelector = modelRoot.errorSelector;
var comparator = modelRoot.comparator;
return Request.prototype.getSourceObserver.call(this, Observer.create(
function onNext(jsonGraphEnvelope) {
model._path = emptyArray;
var result = setJsonGraphAsJsonDense(model.materialize(), [{
paths: paths,
jsonGraph: jsonGraphEnvelope.jsonGraph
}], emptyArray, errorSelector, comparator);
jsonGraphEnvelope.paths = result.requestedPaths.concat(result.errors.map(getPath));
model._path = bound;
observer.onNext(jsonGraphEnvelope);
},
function onError(error) {
model._path = emptyArray;
setJsonValuesAsJsonDense(model.materialize(), arrayMap(paths, function(path) {
return {
path: path,
value: error
};
}), emptyArray, errorSelector, comparator);
model._path = bound;
observer.onError(error);
},
function onCompleted() {
observer.onCompleted();
}
));
};
function getPath(pv) {
return pv.path;
}
module.exports = SetRequest;
},{"157":157,"171":171,"52":52,"65":65,"73":73,"82":82}],55:[function(require,module,exports){
var Rx = require(171);
var Observable = Rx.Observable;
var CompositeDisposable = Rx.CompositeDisposable;
var ModelResponse = require(59);
var InvalidSourceError = require(8);
var pathSyntax = require(149);
var $ref = require(126);
function CallResponse(subscribe) {
Observable.call(this, subscribe || subscribeToResponse);
}
CallResponse.create = ModelResponse.create;
CallResponse.prototype = Object.create(Observable.prototype);
CallResponse.prototype.constructor = CallResponse;
CallResponse.prototype.invokeSourceRequest = function invokeSourceRequest(model) {
return this;
};
CallResponse.prototype.ensureCollect = function ensureCollect(model) {
return this;
};
CallResponse.prototype.initialize = function initializeResponse() {
return this;
};
function subscribeToResponse(observer) {
var args = this.args;
var model = this.model;
var selector = this.selector;
var callPath = pathSyntax.fromPath(args[0]);
var callArgs = args[1] || [];
var suffixes = (args[2] || []).map(pathSyntax.fromPath);
var extraPaths = (args[3] || []).map(pathSyntax.fromPath);
var rootModel = model.clone({
_path: []
});
var localRoot = rootModel.withoutDataSource();
var boundPath = model._path;
var boundCallPath = boundPath.concat(callPath);
var boundThisPath = boundCallPath.slice(0, -1);
var setCallValuesObs = model
.withoutDataSource()
._get(callPath, function(localFn) {
return {
model: rootModel._derefSync(boundThisPath).boxValues(),
localFn: localFn
};
})
.flatMap(getLocalCallObs)
.defaultIfEmpty(getRemoteCallObs(model._source))
.mergeAll()
.flatMap(setCallEnvelope);
var disposables = new CompositeDisposable();
disposables.add(setCallValuesObs.subscribe(function(envelope) {
var paths = envelope.paths;
var invalidated = envelope.invalidated;
if (selector) {
paths.push(function() {
return selector.call(model, paths);
});
}
var innerObs = model.get.apply(model, paths);
if (observer.outputFormat === "AsJSONG") {
innerObs = innerObs.toJSONG().doAction(function(envelope2) {
envelope2.invalidated = invalidated;
});
}
disposables.add(innerObs.subscribe(observer));
},
function(e) {
observer.onError(e);
}
));
return disposables;
function getLocalCallObs(tuple) {
var localFn = tuple && tuple.localFn;
if (typeof localFn === "function") {
var localFnModel = tuple.model;
var localThisPath = localFnModel._path;
var remoteGetValues = localFn
.apply(localFnModel, callArgs)
.reduce(aggregateFnResults, {
values: [],
references: [],
invalidations: [],
localThisPath: localThisPath
})
.flatMap(setLocalValues)
.flatMap(getRemoteValues);
return Observable.return(remoteGetValues);
}
return Observable.empty();
function aggregateFnResults(results, pathValue) {
if (Boolean(pathValue.invalidated)) {
results.invalidations.push(results.localThisPath.concat(pathValue.path));
} else {
var path = pathValue.path;
var value = pathValue.value;
if (Boolean(value) && typeof value === "object" && value.$type === $ref) {
results.references.push({
path: prependThisPath(path),
value: pathValue.value
});
} else {
results.values.push({
path: prependThisPath(path),
value: pathValue.value
});
}
}
return results;
}
function setLocalValues(results) {
var values = results.values.concat(results.references);
if (values.length > 0) {
return localRoot.set
.apply(localRoot, values)
.toJSONG()
.map(function(envelope) {
return {
results: results,
envelope: envelope
};
});
} else {
return Observable.return({
results: results,
envelope: {
jsonGraph: {},
paths: []
}
});
}
}
function getRemoteValues(tuple2) {
var envelope = tuple2.envelope;
var results = tuple2.results;
var values = results.values;
var references = results.references;
var invalidations = results.invalidations;
var rootValues = values.map(pluckPath).map(prependThisPath);
var rootSuffixes = references.reduce(prependRefToSuffixes, []);
var rootExtraPaths = extraPaths.map(prependThisPath);
var rootPaths = rootSuffixes.concat(rootExtraPaths);
var envelopeObs;
if (rootPaths.length > 0) {
envelopeObs = rootModel.get.apply(rootModel, rootValues.concat(rootPaths)).toJSONG();
} else {
envelopeObs = Observable.return(envelope);
}
return envelopeObs.doAction(function(envelope2) {
envelope2.invalidated = invalidations;
});
}
function prependRefToSuffixes(refPaths, refPathValue) {
var refPath = refPathValue.path;
refPaths.push.apply(refPaths, suffixes.map(function(pathSuffix) {
return refPath.concat(pathSuffix);
}));
return refPaths;
}
function pluckPath(pathValue) {
return pathValue.path;
}
function prependThisPath(path) {
return boundThisPath.concat(path);
}
}
function getRemoteCallObs(dataSource) {
if (dataSource && typeof dataSource === "object") {
return Rx.Observable.defer(function() {
var obs;
try {
obs = dataSource.call(callPath, callArgs, suffixes, extraPaths);
} catch (e) {
obs = Observable.throw(new InvalidSourceError(e));
}
return obs;
}).map(invalidateLocalValues);
}
return Observable.empty();
function invalidateLocalValues(envelope) {
var invalidations = envelope.invalidated;
if (invalidations && invalidations.length) {
rootModel.invalidate.apply(rootModel, invalidations);
}
return envelope;
}
}
function setCallEnvelope(envelope) {
return localRoot.
set(envelope).
reduce(function(acc) {
return acc;
}, {}).
map(function() {
return {
invalidated: envelope.invalidated,
paths: envelope.paths.map(function(path) {
return path.slice(boundPath.length);
})
};
});
}
}
module.exports = CallResponse;
},{"126":126,"149":149,"171":171,"59":59,"8":8}],56:[function(require,module,exports){
var Rx = require(171);
var Observable = Rx.Observable;
var Disposable = Rx.Disposable;
var IdempotentResponse = require(57);
var InvalidSourceError = require(8);
var arrayMap = require(82);
var arrayConcat = require(80);
var isFunction = require(100);
function GetResponse(subscribe) {
IdempotentResponse.call(this, subscribe || subscribeToGetResponse);
}
GetResponse.create = IdempotentResponse.create;
GetResponse.prototype = Object.create(IdempotentResponse.prototype);
GetResponse.prototype.method = "get";
GetResponse.prototype.constructor = GetResponse;
GetResponse.prototype.invokeSourceRequest = function invokeSourceRequest(model) {
var source = this;
var caught = this.catch(function getMissingPaths(results) {
if (results && results.invokeSourceRequest === true) {
var optimizedMissingPaths = results.optimizedMissingPaths;
return (model._request.get(optimizedMissingPaths).
do(null, function setResponseError() {
source.isCompleted = true;
})
.materialize()
.flatMap(function(notification) {
if (notification.kind === "C") {
return Observable.empty();
}
if (notification.kind === "E") {
var ex = notification.exception;
if (InvalidSourceError.is(ex)) {
return Observable.throw(notification.exception);
}
}
return caught;
}));
}
return Observable.throw(results);
});
return new this.constructor(function(observer) {
return caught.subscribe(observer);
});
};
// Executes the local cache search for the GetResponse's operation groups.
function subscribeToGetResponse(observer) {
if (this.subscribeCount++ >= this.subscribeLimit) {
observer.onError("Loop kill switch thrown.");
return Disposable.empty;
}
var model = this.model;
var modelRoot = model._root;
var method = this.method;
var boundPath = this.boundPath;
var outputFormat = this.outputFormat;
var isMaster = this.isMaster;
var isCompleted = this.isCompleted;
var isProgressive = this.isProgressive;
var asJSONG = outputFormat === "AsJSONG";
var asValues = outputFormat === "AsValues";
var hasValue = false;
var errors = [];
var requestedMissingPaths = [];
var optimizedMissingPaths = [];
var groups = this.groups;
var groupIndex = -1;
var groupCount = groups.length;
while (++groupIndex < groupCount) {
var group = groups[groupIndex];
var groupValues = !asValues && group.values || onPathValueNext;
var inputType = group.inputType;
var methodArgs = group.arguments;
if (methodArgs.length > 0) {
var operationName = "_" + method + inputType + outputFormat;
var operationFunc = model[operationName];
var results = operationFunc(model, methodArgs, groupValues);
errors.push.apply(errors, results.errors);
requestedMissingPaths.push.apply(requestedMissingPaths, results.requestedMissingPaths);
optimizedMissingPaths.push.apply(optimizedMissingPaths, results.optimizedMissingPaths);
if (asValues) {
group.arguments = results.requestedMissingPaths;
} else {
hasValue = hasValue || results.hasValue || results.requestedPaths.length > 0;
}
}
}
isCompleted = isCompleted || requestedMissingPaths.length === 0;
var hasError = errors.length > 0;
try {
modelRoot.syncRefCount++;
if (hasValue && (isProgressive || isCompleted || isMaster)) {
var values = this.values;
var selector = this.selector;
if (isFunction(selector)) {
observer.onNext(selector.apply(model, values.map(pluckJSON)));
} else {
var valueIndex = -1;
var valueCount = values.length;
while (++valueIndex < valueCount) {
observer.onNext(values[valueIndex]);
}
}
}
if (isCompleted || isMaster) {
if (hasError) {
observer.onError(errors);
} else {
observer.onCompleted();
}
} else {
if (asJSONG) {
this.values[0].paths = [];
}
observer.onError({
method: method,
requestedMissingPaths: arrayMap(requestedMissingPaths, prependBoundPath),
optimizedMissingPaths: optimizedMissingPaths,
invokeSourceRequest: true
});
}
} catch (e) {
throw e;
} finally {
--modelRoot.syncRefCount;
}
return Disposable.empty;
function prependBoundPath(path) {
return arrayConcat(boundPath, path);
}
function onPathValueNext(x) {
++modelRoot.syncRefCount;
try {
observer.onNext(x);
} catch (e) {
throw e;
} finally {
--modelRoot.syncRefCount;
}
}
}
function pluckJSON(jsonEnvelope) {
return jsonEnvelope.json;
}
module.exports = GetResponse;
},{"100":100,"171":171,"57":57,"8":8,"80":80,"82":82}],57:[function(require,module,exports){
var Rx = require(171);
var Observable = Rx.Observable;
var ModelResponse = require(59);
var pathSyntax = require(149);
var getSize = require(92);
var collectLru = require(47);
var arrayClone = require(79);
var isArray = Array.isArray;
var isFunction = require(100);
var isPathValue = require(104);
var isJsonEnvelope = require(101);
var isJsonGraphEnvelope = require(102);
function IdempotentResponse(subscribe) {
Observable.call(this, subscribe);
}
IdempotentResponse.create = ModelResponse.create;
IdempotentResponse.prototype = Object.create(Observable.prototype);
IdempotentResponse.prototype.constructor = IdempotentResponse;
IdempotentResponse.prototype.subscribeCount = 0;
IdempotentResponse.prototype.subscribeLimit = 10;
IdempotentResponse.prototype.initialize = function initializeResponse() {
var model = this.model;
var selector = this.selector;
var outputFormat = this.outputFormat || "AsPathMap";
var isProgressive = this.isProgressive;
var values = [];
var seedIndex = 0;
var seedLimit = 0;
if (isFunction(selector)) {
outputFormat = "AsJSON";
seedLimit = selector.length;
while (seedIndex < seedLimit) {
values[seedIndex++] = {};
}
seedIndex = 0;
} else if (outputFormat === "AsJSON") {
seedLimit = -1;
} else if (outputFormat === "AsValues") {
values[0] = {};
isProgressive = false;
} else {
values[0] = {};
}
var groups = [];
var args = this.args;
var group, groupType;
var argIndex = -1;
var argCount = args.length;
// Validation of arguments have been moved out of this function.
while (++argIndex < argCount) {
var seedCount = seedIndex + 1;
var arg = args[argIndex];
var argType;
if (isArray(arg) || typeof arg === "string") {
arg = pathSyntax.fromPath(arg);
argType = "PathValues";
} else if (isPathValue(arg)) {
arg.path = pathSyntax.fromPath(arg.path);
argType = "PathValues";
} else if (isJsonGraphEnvelope(arg)) {
argType = "JSONGs";
seedCount += arg.paths.length;
} else if (isJsonEnvelope(arg)) {
argType = "PathMaps";
}
if (groupType !== argType) {
groupType = argType;
group = {
inputType: argType,
arguments: []
};
groups.push(group);
if (outputFormat === "AsJSON") {
group.values = [];
} else if (outputFormat !== "AsValues") {
group.values = values;
}
}
group.arguments.push(arg);
if (outputFormat === "AsJSON") {
var nextSeed;
if (seedLimit === -1) {
while (seedIndex < seedCount) {
nextSeed = values[seedIndex++] = {};
group.values.push(nextSeed);
}
} else {
if (seedLimit < seedCount) {
seedCount = seedLimit;
}
while (seedIndex < seedCount) {
nextSeed = values[seedIndex++] = {};
group.values.push(nextSeed);
}
}
}
}
this.boundPath = arrayClone(model._path);
this.groups = groups;
this.outputFormat = outputFormat;
this.isProgressive = isProgressive;
this.isCompleted = false;
this.isMaster = model._source == null;
this.values = values;
return this;
};
IdempotentResponse.prototype.invokeSourceRequest = function invokeSourceRequest(model) {
return this;
};
IdempotentResponse.prototype.ensureCollect = function ensureCollect(model) {
var ensured = this.finally(function ensureCollect() {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
modelRoot.collectionScheduler.schedule(function collectThisPass() {
collectLru(modelRoot, modelRoot.expired, getSize(modelCache), model._maxSize, model._collectRatio);
});
});
return new this.constructor(function(observer) {
return ensured.subscribe(observer);
});
};
module.exports = IdempotentResponse;
},{"100":100,"101":101,"102":102,"104":104,"149":149,"171":171,"47":47,"59":59,"79":79,"92":92}],58:[function(require,module,exports){
var Rx = require(171);
var Disposable = Rx.Disposable;
var IdempotentResponse = require(57);
var emptyArray = new Array(0);
function InvalidateResponse(subscribe) {
IdempotentResponse.call(this, subscribe || subscribeToInvalidateResponse);
}
InvalidateResponse.create = IdempotentResponse.create;
InvalidateResponse.prototype = Object.create(IdempotentResponse.prototype);
InvalidateResponse.prototype.method = "invalidate";
InvalidateResponse.prototype.constructor = InvalidateResponse;
function subscribeToInvalidateResponse(observer) {
var model = this.model;
var method = this.method;
var groups = this.groups;
var groupIndex = -1;
var groupCount = groups.length;
while (++groupIndex < groupCount) {
var group = groups[groupIndex];
var inputType = group.inputType;
var methodArgs = group.arguments;
if (methodArgs.length > 0) {
var operationName = "_" + method + inputType + "AsJSON";
var operationFunc = model[operationName];
operationFunc(model, methodArgs, emptyArray);
}
}
observer.onCompleted();
return Disposable.empty;
}
module.exports = InvalidateResponse;
},{"171":171,"57":57}],59:[function(require,module,exports){
var falcor = require(30);
var Rx = require(171);
var Observable = Rx.Observable;
var arraySlice = require(83);
var noop = require(108);
var jsongMixin = { outputFormat: { value: "AsJSONG" } };
var valuesMixin = { outputFormat: { value: "AsValues" } };
var pathMapMixin = { outputFormat: { value: "AsPathMap" } };
var compactJSONMixin = { outputFormat: { value: "AsJSON" } };
var progressiveMixin = { isProgressive: { value: true } };
function ModelResponse(subscribe) {
this._subscribe = subscribe;
}
ModelResponse.create = function create(model, args, selector) {
var response = new ModelResponse(subscribeToResponse);
// TODO: make these private
response.args = args;
response.type = this;
response.model = model;
response.selector = selector;
return response;
};
ModelResponse.prototype = Object.create(Observable.prototype);
ModelResponse.prototype.constructor = ModelResponse;
ModelResponse.prototype.mixin = function mixin() {
var self = this;
var mixins = arraySlice(arguments);
return new self.constructor(function(observer) {
return self.subscribe(mixins.reduce(function(proto, mixin2) {
return Object.create(proto, mixin2);
}, observer));
});
};
/**
* Converts the data format of the data in a JSONGraph Model response to a stream of path values.
* @name toPathValues
* @memberof ModelResponse.prototype
* @function
* @return ModelResponse.<PathValue>
* @example
var model = new falcor.Model({
cache: {
user: {
name: "Steve",
surname: "McGuire"
}
}
});
model.
get(["user",["name", "surname"]]).
toPathValues().
// this method will be called twice, once with the result of ["user", "name"]
// and once with the result of ["user", "surname"]
subscribe(function(pathValue){
console.log(JSON.stringify(pathValue));
});
// prints...
"{\"path\":[\"user\",\"name\"],\"value\":\"Steve\"}"
"{\"path\":[\"user\",\"surname\"],\"value\":\"McGuire\"}"
*/
ModelResponse.prototype.toPathValues = function toPathValues() {
return this.mixin(valuesMixin).asObservable();
};
ModelResponse.prototype.toCompactJSON = function toCompactJSON() {
return this.mixin(compactJSONMixin);
};
ModelResponse.prototype.toJSON = function toJSON() {
return this.mixin(pathMapMixin);
};
ModelResponse.prototype.toJSONG = function toJSONG() {
return this.mixin(jsongMixin);
};
/**
* The progressively method breaks the response up into two parts: the data immediately available in the Model cache, and the data in the Model cache after the missing data has been retrieved from the DataSource.
* The progressively method creates a ModelResponse that immediately returns the requested data that is available in the Model cache. If any requested paths are not available in the cache, the ModelResponse will send another JSON message with all of the requested data after it has been retrieved from the DataSource.
* @name progressively
* @memberof ModelResponse.prototype
* @function
* @return {ModelResponse.<JSONEnvelope>} the values found at the requested paths.
* @example
var dataSource = (new falcor.Model({
cache: {
user: {
name: "Steve",
surname: "McGuire",
age: 31
}
}
})).asDataSource();
var model = new falcor.Model({
source: dataSource,
cache: {
user: {
name: "Steve",
surname: "McGuire"
}
}
});
model.
get(["user",["name", "surname", "age"]]).
progressively().
// this callback will be invoked twice, once with the data in the
// Model cache, and again with the additional data retrieved from the DataSource.
subscribe(function(json){
console.log(JSON.stringify(json,null,4));
});
// prints...
// {
// "json": {
// "user": {
// "name": "Steve",
// "surname": "McGuire"
// }
// }
// }
// ...and then prints...
// {
// "json": {
// "user": {
// "name": "Steve",
// "surname": "McGuire",
// "age": 31
// }
// }
// }
*/
ModelResponse.prototype.progressively = function progressively() {
return this.mixin(progressiveMixin);
};
ModelResponse.prototype.subscribe = function subscribe(a, b, c) {
var observer = a;
if (!observer || typeof observer !== "object") {
observer = { onNext: a || noop, onError: b || noop, onCompleted: c || noop };
}
var subscription = this._subscribe(observer);
switch (typeof subscription) {
case "function":
return { dispose: subscription };
case "object":
return subscription || { dispose: noop };
default:
return { dispose: noop };
}
};
ModelResponse.prototype.then = function then(onNext, onError) {
var self = this;
return new falcor.Promise(function(resolve, reject) {
var value, rejected = false;
self.toArray().subscribe(
function(values) {
if (values.length <= 1) {
value = values[0];
} else {
value = values;
}
},
function(errors) {
rejected = true;
reject(errors);
},
function() {
if (rejected === false) {
resolve(value);
}
}
);
}).then(onNext, onError);
};
function subscribeToResponse(observer) {
var model = this.model;
var response = new this.type();
response.model = model;
response.args = this.args;
response.selector = this.selector;
response.outputFormat = observer.outputFormat || "AsPathMap";
response.isProgressive = observer.isProgressive || false;
response.subscribeCount = 0;
response.subscribeLimit = observer.retryLimit || 10;
return (response
.initialize()
.invokeSourceRequest(model)
.ensureCollect(model)
.subscribe(observer));
}
module.exports = ModelResponse;
},{"108":108,"171":171,"30":30,"83":83}],60:[function(require,module,exports){
var Rx = require(171);
var Observable = Rx.Observable;
var Disposable = Rx.Disposable;
var IdempotentResponse = require(57);
var InvalidSourceError = require(8);
var arrayMap = require(82);
var arrayFlatMap = require(81);
var isFunction = require(100);
var emptyArray = new Array(0);
function SetResponse(subscribe) {
IdempotentResponse.call(this, subscribe || subscribeToSetResponse);
}
SetResponse.create = IdempotentResponse.create;
SetResponse.prototype = Object.create(IdempotentResponse.prototype);
SetResponse.prototype.method = "set";
SetResponse.prototype.constructor = SetResponse;
SetResponse.prototype.invokeSourceRequest = function invokeSourceRequest(model) {
var source = this;
var caught = this.catch(function setJSONGraph(results) {
var requestObs;
if (results && results.invokeSourceRequest === true) {
var envelope = {};
var boundPath = model._path;
var optimizedPaths = results.optimizedPaths;
model._path = emptyArray;
model._getPathValuesAsJSONG(model, optimizedPaths, [envelope]);
model._path = boundPath;
requestObs = model.
_request.set(envelope).
do(
function setResponseEnvelope(envelope2) {
source.isCompleted = optimizedPaths.length === envelope2.paths.length;
},
function setResponseError() {
source.isCompleted = true;
}
).
materialize().
flatMap(function(notification) {
if (notification.kind === "C") {
return Observable.empty();
}
if (notification.kind === "E") {
var ex = notification.exception;
if (InvalidSourceError.is(ex)) {
return Observable.throw(notification.exception);
}
}
return caught;
});
}
else {
requestObs = Observable.throw(results);
}
return requestObs;
});
return new this.constructor(function(observer) {
return caught.subscribe(observer);
});
};
function subscribeToSetResponse(observer) {
if (this.subscribeCount >= this.subscribeLimit) {
observer.onError("Loop kill switch thrown.");
return Disposable.empty;
}
var model = this.model;
var modelRoot = model._root;
var method = this.method;
var outputFormat = this.outputFormat;
var errorSelector = modelRoot.errorSelector;
var comparator = this.subscribeCount++ > 0 && modelRoot.comparator || void 0;
var isMaster = this.isMaster;
var isCompleted = this.isCompleted;
var isProgressive = this.isProgressive;
var asJSONG = outputFormat === "AsJSONG";
var asValues = outputFormat === "AsValues";
var hasValue = false;
var errors = [];
var optimizedPaths = [];
var groups = this.groups;
var groupIndex = -1;
var groupCount = groups.length;
if (isCompleted) {
method = "get";
}
while (++groupIndex < groupCount) {
var group = groups[groupIndex];
var groupValues = !asValues && group.values || onPathValueNext;
var inputType = group.inputType;
var methodArgs = group.arguments;
if (isCompleted) {
if (inputType === "PathValues") {
inputType = "PathValues";
methodArgs = arrayMap(methodArgs, pluckPath);
} else if (inputType === "JSONGs") {
inputType = "PathValues";
methodArgs = arrayFlatMap(methodArgs, pluckPaths);
}
}
if (methodArgs.length > 0) {
var operationName = "_" + method + inputType + outputFormat;
var operationFunc = model[operationName];
var results = operationFunc(model, methodArgs, groupValues, errorSelector, comparator);
errors.push.apply(errors, results.errors);
optimizedPaths.push.apply(optimizedPaths, results.optimizedPaths);
hasValue = !asValues && (hasValue || results.hasValue || results.requestedPaths.length > 0);
}
}
var hasError = errors.length > 0;
try {
modelRoot.syncRefCount++;
if (hasValue && (isProgressive || isCompleted || isMaster) && !asValues) {
var values = this.values;
var selector = this.selector;
if (isFunction(selector)) {
observer.onNext(selector.apply(model, values.map(pluckJSON)));
} else {
var valueIndex = -1;
var valueCount = values.length;
while (++valueIndex < valueCount) {
observer.onNext(values[valueIndex]);
}
}
}
if (isCompleted || isMaster) {
if (hasError) {
observer.onError(errors);
} else {
observer.onCompleted();
}
} else {
if (asJSONG) {
this.values[0].paths = [];
}
observer.onError({
method: method,
optimizedPaths: optimizedPaths,
invokeSourceRequest: true
});
}
} catch (e) {
throw e;
} finally {
--modelRoot.syncRefCount;
}
return Disposable.empty;
function onPathValueNext(x) {
++modelRoot.syncRefCount;
try {
observer.onNext(x);
} catch (e) {
throw e;
} finally {
--modelRoot.syncRefCount;
}
}
}
function pluckJSON(jsonEnvelope) {
return jsonEnvelope.json;
}
function pluckPath(pathValue) {
return pathValue.path;
}
function pluckPaths(jsonGraphEnvelope) {
return jsonGraphEnvelope.paths;
}
module.exports = SetResponse;
},{"100":100,"171":171,"57":57,"8":8,"81":81,"82":82}],61:[function(require,module,exports){
var asap = require(134);
var Rx = require(171);
var Disposable = Rx.Disposable;
function ASAPScheduler() {}
ASAPScheduler.prototype.schedule = function schedule(action) {
asap(action);
return Disposable.empty;
};
ASAPScheduler.prototype.scheduleWithState = function scheduleWithState(state, action) {
var self = this;
asap(function() {
action(self, state);
});
return Disposable.empty;
};
module.exports = ASAPScheduler;
},{"134":134,"171":171}],62:[function(require,module,exports){
var Rx = require(171);
var Disposable = Rx.Disposable;
function ImmediateScheduler() {}
ImmediateScheduler.prototype.schedule = function schedule(action) {
action();
return Disposable.empty;
};
ImmediateScheduler.prototype.scheduleWithState = function scheduleWithState(state, action) {
action(this, state);
return Disposable.empty;
};
module.exports = ImmediateScheduler;
},{"171":171}],63:[function(require,module,exports){
var Rx = require(171);
var Disposable = Rx.Disposable;
function TimeoutScheduler(delay) {
this.delay = delay;
}
TimeoutScheduler.prototype.schedule = function schedule(action) {
var id = setTimeout(action, this.delay);
return Disposable.create(function() {
if (id !== void 0) {
clearTimeout(id);
id = void 0;
}
});
};
TimeoutScheduler.prototype.scheduleWithState = function scheduleWithState(state, action) {
var self = this;
var id = setTimeout(function() {
action(self, state);
}, this.delay);
return Disposable.create(function() {
if (id !== void 0) {
clearTimeout(id);
id = void 0;
}
});
};
module.exports = TimeoutScheduler;
},{"171":171}],64:[function(require,module,exports){
module.exports = setCache;
var $error = require(125);
var $atom = require(124);
var arrayClone = require(79);
var options = require(110);
var walkPathMap = require(130);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
/**
* Populates a model's cache from an existing deserialized cache.
* Traverses the existing cache as a path map, writing all the leaves
* into the model's cache as they're encountered.
* @private
*/
function setCache(model, pathmap, errorSelector) {
var modelRoot = model._root;
var roots = options([], model, errorSelector);
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = [];
var keysStack = [];
roots[_cache] = roots.root;
walkPathMap(onNode, onEdge, pathmap, keysStack, 0, roots, parents, nodes, requested, optimized);
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler) {
rootChangeHandler();
}
return model;
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
parent = parents[_cache];
} else {
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = nodes[_cache] = node;
return;
}
var selector = roots.errorSelector;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var mess = pathmap;
type = isObject(mess) && mess.$type || void 0;
mess = wrapNode(mess, type, Boolean(type) ? mess.value : mess);
type = type || $atom;
if (type === $error && Boolean(selector)) {
mess = selector(requested, mess);
}
node = replaceNode(parent, node, mess, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
nodes[_cache] = node;
}
function onEdge(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
if (depth > 0) {
promote(roots.lru, nodes[_cache]);
}
}
},{"103":103,"110":110,"112":112,"114":114,"121":121,"123":123,"124":124,"125":125,"130":130,"48":48,"79":79,"90":90,"94":94,"95":95}],65:[function(require,module,exports){
module.exports = setJsonGraphAsJsonDense;
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(131);
var isObject = require(103);
var getValidKey = require(94);
var mergeNode = require(107);
var setNodeIfMissingPath = require(118);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _message = positions.message;
var _json = positions.json;
function setJsonGraphAsJsonDense(model, envelopes, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, errorSelector, comparator);
var index = -1;
var index2 = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = [];
var json, hasValue, hasValues;
roots[_cache] = roots.root;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsonGraph || envelope.jsong || envelope.values || envelope.value;
var index3 = -1;
var count2 = pathsets.length;
roots[_message] = jsong;
nodes[_message] = jsong;
while (++index3 < count2) {
json = values && values[++index2];
if (isObject(json)) {
roots.json = roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
} else {
roots.json = roots[_json] = parents[_json] = nodes[_json] = void 0;
}
var pathset = pathsets[index3];
roots.index = index3;
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (Boolean(hasValue)) {
hasValues = true;
if (isObject(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (isObject(json)) {
delete json.json;
}
}
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, messageParent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_json];
parent = parents[_cache];
messageParent = parents[_message];
} else {
json = isKeyset && nodes[_json] || parents[_json];
parent = nodes[_cache];
messageParent = nodes[_message];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[_message] = message;
nodes[_cache] = node = mergeNode(roots, parent, node, messageParent, message, key, requested);
if (isReference) {
parents[_cache] = parent;
parents[_message] = messageParent;
return;
}
var length = requested.length;
var offset = roots.offset;
parents[_json] = json;
if (isBranch) {
parents[_cache] = node;
parents[_message] = message;
if ((length > offset) && isKeyset && Boolean(json)) {
nodes[_json] = json[keyset] || (json[keyset] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else {
json = parents[_json];
if (Boolean(json)) {
json[keyset] = clone(roots, node, type, node && node.value);
}
}
roots.hasValue = true;
}
}
},{"103":103,"107":107,"110":110,"112":112,"115":115,"117":117,"118":118,"131":131,"44":44,"79":79,"84":84,"94":94}],66:[function(require,module,exports){
module.exports = setJsonGraphAsJsonGraph;
var $ref = require(126);
var __version = require(44);
var clone = require(85);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(131);
var isObject = require(103);
var getValidKey = require(94);
var mergeNode = require(107);
var setNodeIfMissingPath = require(118);
var setSuccessfulPaths = require(115);
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
var _message = positions.message;
var _jsong = positions.jsong;
function setJsonGraphAsJsonGraph(model, envelopes, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = [];
roots.offset = 0;
roots.bound = [];
roots = options(roots, model, errorSelector, comparator);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[_cache] = roots.root;
roots[_jsong] = parents[_jsong] = nodes[_jsong] = json.jsonGraph || (json.jsonGraph = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsonGraph || envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[_message] = jsong;
nodes[_message] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if (hasValue) {
json.jsonGraph = roots[_jsong];
} else {
delete json.jsonGraph;
delete json.paths;
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, messageParent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_jsong];
parent = parents[_cache];
messageParent = parents[_message];
} else {
json = nodes[_jsong];
parent = nodes[_cache];
messageParent = nodes[_message];
}
var jsonkey = key;
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[_message] = message;
nodes[_cache] = node = mergeNode(roots, parent, node, messageParent, message, key, requested);
var type = isObject(node) && node.$type || void 0;
if (isReference) {
parents[_cache] = parent;
parents[_message] = messageParent;
parents[_jsong] = json;
if (type === $ref) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[_jsong] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (isBranch) {
parents[_cache] = node;
parents[_message] = message;
parents[_jsong] = json;
if (type === $ref) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[_jsong] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
promote(roots.lru, node);
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null && !roots.hasValue && getValidKey(optimized) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[_jsong];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
},{"103":103,"107":107,"110":110,"112":112,"115":115,"118":118,"126":126,"131":131,"44":44,"48":48,"79":79,"85":85,"94":94}],67:[function(require,module,exports){
module.exports = setJsonGraphAsJsonSparse;
var $ref = require(126);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(131);
var isObject = require(103);
var getValidKey = require(94);
var mergeNode = require(107);
var setNodeIfMissingPath = require(118);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _message = positions.message;
var _json = positions.json;
function setJsonGraphAsJsonSparse(model, envelopes, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, errorSelector, comparator);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = [];
var json = values[0];
var hasValue;
roots[_cache] = roots.root;
roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsonGraph || envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[_message] = jsong;
nodes[_message] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
hasValue = roots.hasValue;
if (hasValue) {
json.json = roots[_json];
} else {
delete json.json;
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, messageParent, json, jsonkey;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
jsonkey = getValidKey(requested);
json = parents[_json];
parent = parents[_cache];
messageParent = parents[_message];
} else {
jsonkey = key;
json = nodes[_json];
parent = nodes[_cache];
messageParent = nodes[_message];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[_message] = message;
nodes[_cache] = node = mergeNode(roots, parent, node, messageParent, message, key, requested);
if (isReference) {
parents[_cache] = parent;
parents[_message] = messageParent;
return;
}
parents[_json] = json;
if (isBranch) {
var length = requested.length;
var offset = roots.offset;
var type = isObject(node) && node.$type || void 0;
parents[_cache] = node;
parents[_message] = message;
if ((length > offset) && (!type || type === $ref)) {
nodes[_json] = json[jsonkey] || (json[jsonkey] = {});
}
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null && !roots.hasValue && getValidKey(optimized) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[_json];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[_json];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
},{"103":103,"107":107,"110":110,"112":112,"115":115,"117":117,"118":118,"126":126,"131":131,"44":44,"79":79,"84":84,"94":94}],68:[function(require,module,exports){
module.exports = setJsonGraphAsJsonValues;
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var arraySlice = require(83);
var options = require(110);
var walkPathSet = require(131);
var isObject = require(103);
var getValidKey = require(94);
var mergeNode = require(107);
var setNodeIfMissingPath = require(118);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _message = positions.message;
function setJsonGraphAsJsonValues(model, envelopes, onNext, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = [];
roots.offset = model._path.length;
roots.bound = [];
roots = options(roots, model, errorSelector, comparator);
var index = -1;
var count = envelopes.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = [];
roots[_cache] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var envelope = envelopes[index];
var pathsets = envelope.paths;
var jsong = envelope.jsonGraph || envelope.jsong || envelope.values || envelope.value;
var index2 = -1;
var count2 = pathsets.length;
roots[_message] = jsong;
nodes[_message] = jsong;
while (++index2 < count2) {
var pathset = pathsets[index2];
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset) {
var key = keyArg;
var parent, messageParent;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
parent = parents[_cache];
messageParent = parents[_message];
} else {
parent = nodes[_cache];
messageParent = nodes[_message];
}
var node = parent[key];
var message = messageParent && messageParent[key];
nodes[_message] = message;
nodes[_cache] = node = mergeNode(roots, parent, node, messageParent, message, key, requested);
if (isReference) {
parents[_cache] = parent;
parents[_message] = messageParent;
return;
}
if (isBranch) {
parents[_cache] = node;
parents[_message] = message;
}
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset, isKeyset) {
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
roots.onNext({
path: arraySlice(requested, roots.offset),
value: clone(roots, node, type, node && node.value)
});
}
}
},{"103":103,"107":107,"110":110,"112":112,"115":115,"117":117,"118":118,"131":131,"44":44,"79":79,"83":83,"84":84,"94":94}],69:[function(require,module,exports){
module.exports = setJsonSparseAsJsonDense;
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathMap = require(130);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _json = positions.json;
function setJsonSparseAsJsonDense(model, pathmaps, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var keysStack = [];
var json, hasValue, hasValues;
roots[_cache] = roots.root;
while (++index < count) {
json = values && values[index];
if (isObject(json)) {
roots.json = roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
} else {
roots.json = roots[_json] = parents[_json] = nodes[_json] = void 0;
}
var pathmap = pathmaps[index].json;
roots.index = index;
walkPathMap(onNode, onEdge, pathmap, keysStack, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (Boolean(hasValue)) {
hasValues = true;
if (isObject(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (isObject(json)) {
delete json.json;
}
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_json];
parent = parents[_cache];
} else {
json = isKeyset && nodes[_json] || parents[_json];
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
parents[_json] = json;
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = nodes[_cache] = node;
if (isKeyset && Boolean(json)) {
nodes[_json] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = pathmap;
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[_cache] = node;
}
function onEdge(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else {
json = parents[_json];
if (Boolean(json)) {
json[keyset] = clone(roots, node, type, node && node.value);
}
}
roots.hasValue = true;
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"117":117,"121":121,"123":123,"124":124,"125":125,"130":130,"44":44,"79":79,"84":84,"90":90,"94":94,"95":95}],70:[function(require,module,exports){
module.exports = setJsonSparseAsJsonGraph;
var $ref = require(126);
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(85);
var arrayClone = require(79);
var options = require(110);
var walkPathMap = require(129);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setSuccessfulPaths = require(115);
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
var _jsong = positions.jsong;
function setJsonSparseAsJsonGraph(model, pathmaps, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var keysStack = [];
var json = values[0];
var hasValue;
roots[_cache] = roots.root;
roots[_jsong] = parents[_jsong] = nodes[_jsong] = json.jsonGraph || (json.jsonGraph = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pathmap = pathmaps[index].json;
walkPathMap(onNode, onEdge, pathmap, keysStack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if (hasValue) {
json.jsonGraph = roots[_jsong];
} else {
delete json.jsonGraph;
delete json.paths;
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_jsong];
parent = parents[_cache];
} else {
json = nodes[_jsong];
parent = nodes[_cache];
}
var jsonkey = key;
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
parents[_jsong] = json;
if (type === $ref) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[_jsong] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
type = node.$type;
parents[_cache] = nodes[_cache] = node;
parents[_jsong] = json;
if (type === $ref) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[_jsong] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = pathmap;
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
nodes[_cache] = node;
}
function onEdge(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
promote(roots.lru, node);
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null && !roots.hasValue && getValidKey(optimized) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[_jsong];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"121":121,"123":123,"124":124,"125":125,"126":126,"129":129,"44":44,"48":48,"79":79,"85":85,"90":90,"94":94,"95":95}],71:[function(require,module,exports){
module.exports = setJsonSparseAsJsonSparse;
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathMap = require(130);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _json = positions.json;
function setJsonSparseAsJsonSparse(model, pathmaps, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var keysStack = [];
var json = values[0];
var hasValue;
roots[_cache] = roots.root;
roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
while (++index < count) {
var pathmap = pathmaps[index].json;
walkPathMap(onNode, onEdge, pathmap, keysStack, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if (hasValue) {
json.json = roots[_json];
} else {
delete json.json;
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json, jsonkey;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
jsonkey = getValidKey(requested);
json = parents[_json];
parent = parents[_cache];
} else {
jsonkey = key;
json = nodes[_json];
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
parents[_json] = json;
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = nodes[_cache] = node;
nodes[_json] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = pathmap;
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[_cache] = node;
}
function onEdge(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null && !roots.hasValue && getValidKey(optimized) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[_json];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[_json];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"117":117,"121":121,"123":123,"124":124,"125":125,"130":130,"44":44,"79":79,"84":84,"90":90,"94":94,"95":95}],72:[function(require,module,exports){
module.exports = setPathMapAsJsonValues;
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathMap = require(130);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
function setPathMapAsJsonValues(model, pathmaps, onNext, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathmaps.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var keysStack = [];
roots[_cache] = roots.root;
roots.onNext = onNext;
while (++index < count) {
var pathmap = pathmaps[index].json;
walkPathMap(onNode, onEdge, pathmap, keysStack, 0, roots, parents, nodes, requested, optimized);
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathmap, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
parent = parents[_cache];
} else {
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = nodes[_cache] = node;
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = pathmap;
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
}
nodes[_cache] = node;
}
function onEdge(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
roots.onNext({
path: arrayClone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"117":117,"121":121,"123":123,"124":124,"125":125,"130":130,"44":44,"79":79,"84":84,"90":90,"94":94,"95":95}],73:[function(require,module,exports){
module.exports = setJsonValuesAsJsonDense;
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(132);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var invalidateNode = require(98);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfMissingPath = require(118);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _json = positions.json;
function setJsonValuesAsJsonDense(model, pathvalues, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var json, hasValue, hasValues;
roots[_cache] = roots.root;
while (++index < count) {
json = values && values[index];
if (isObject(json)) {
roots.json = roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
} else {
roots.json = roots[_json] = parents[_json] = nodes[_json] = void 0;
}
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
roots.index = index;
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
hasValue = roots.hasValue;
if (Boolean(hasValue)) {
hasValues = true;
if (isObject(json)) {
json.json = roots.json;
}
delete roots.json;
delete roots.hasValue;
} else if (isObject(json)) {
delete json.json;
}
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValues,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_json];
parent = parents[_cache];
} else {
json = isKeyset && nodes[_json] || parents[_json];
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
parents[_json] = json;
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
if (isKeyset && Boolean(json)) {
nodes[_json] = json[keyset] || (json[keyset] = {});
}
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = roots.value;
if (message === void 0 && roots.noDataSource) {
invalidateNode(parent, node, key, roots.lru);
updateGraph(parent, size, roots.version, roots.lru);
node = void 0;
} else {
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
}
}
nodes[_cache] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null) {
roots.json = clone(roots, node, type, node && node.value);
} else {
json = parents[_json];
if (Boolean(json)) {
json[keyset] = clone(roots, node, type, node && node.value);
}
}
roots.hasValue = true;
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"117":117,"118":118,"121":121,"123":123,"124":124,"125":125,"132":132,"44":44,"79":79,"84":84,"90":90,"94":94,"95":95,"98":98}],74:[function(require,module,exports){
module.exports = setJsonValuesAsJsonGraph;
var $ref = require(126);
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(85);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(131);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var invalidateNode = require(98);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfMissingPath = require(118);
var setSuccessfulPaths = require(115);
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
var _jsong = positions.jsong;
function setJsonValuesAsJsonGraph(model, pathvalues, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var json = values[0];
var hasValue;
roots[_cache] = roots.root;
roots[_jsong] = parents[_jsong] = nodes[_jsong] = json.jsonGraph || (json.jsonGraph = {});
roots.requestedPaths = json.paths || (json.paths = roots.requestedPaths);
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if (hasValue) {
json.jsonGraph = roots[_jsong];
} else {
delete json.jsonGraph;
delete json.paths;
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
json = parents[_jsong];
parent = parents[_cache];
} else {
json = nodes[_jsong];
parent = nodes[_cache];
}
var jsonkey = key;
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
parents[_jsong] = json;
if (type === $ref) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[_jsong] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
type = node.$type;
parents[_cache] = parent;
nodes[_cache] = node;
parents[_jsong] = json;
if (type === $ref) {
json[jsonkey] = clone(roots, node, type, node.value);
roots.hasValue = true;
} else {
nodes[_jsong] = json[jsonkey] || (json[jsonkey] = {});
}
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = roots.value;
if (message === void 0 && roots.noDataSource) {
invalidateNode(parent, node, key, roots.lru);
updateGraph(parent, size, roots.version, roots.lru);
node = void 0;
} else {
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
json[jsonkey] = clone(roots, node, type, node && node.value);
roots.hasValue = true;
}
}
nodes[_cache] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
promote(roots.lru, node);
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null && !roots.hasValue && getValidKey(optimized) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[_jsong];
json.$type = node.$type;
json.value = node.value;
}
roots.hasValue = true;
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"118":118,"121":121,"123":123,"124":124,"125":125,"126":126,"131":131,"44":44,"48":48,"79":79,"85":85,"90":90,"94":94,"95":95,"98":98}],75:[function(require,module,exports){
module.exports = setJsonValuesAsJsonSparse;
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(132);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var invalidateNode = require(98);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfMissingPath = require(118);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
var _json = positions.json;
function setJsonValuesAsJsonSparse(model, pathvalues, values, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
var roots = options([], model, errorSelector, comparator);
var index = -1;
var count = pathvalues.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requested = [];
var optimized = arrayClone(roots.bound);
var json = values[0];
var hasValue;
roots[_cache] = roots.root;
roots[_json] = parents[_json] = nodes[_json] = json.json || (json.json = {});
while (++index < count) {
var pv = pathvalues[index];
var pathset = pv.path;
roots.value = pv.value;
walkPathSet(onNode, onEdge, pathset, 0, roots, parents, nodes, requested, optimized);
}
hasValue = roots.hasValue;
if (hasValue) {
json.json = roots[_json];
} else {
delete json.json;
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: values,
errors: roots.errors,
hasValue: hasValue,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent, json, jsonkey;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
jsonkey = getValidKey(requested);
json = parents[_json];
parent = parents[_cache];
} else {
jsonkey = key;
json = nodes[_json];
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
parents[_json] = json;
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
nodes[_json] = json[jsonkey] || (json[jsonkey] = {});
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = roots.value;
if (message === void 0 && roots.noDataSource) {
invalidateNode(parent, node, key, roots.lru);
updateGraph(parent, size, roots.version, roots.lru);
node = void 0;
} else {
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
}
}
nodes[_cache] = node;
}
function onEdge(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var json;
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
if (keyset == null && !roots.hasValue && getValidKey(optimized) == null) {
node = clone(roots, node, type, node && node.value);
json = roots[_json];
json.$type = node.$type;
json.value = node.value;
} else {
json = parents[_json];
json[key] = clone(roots, node, type, node && node.value);
}
roots.hasValue = true;
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"117":117,"118":118,"121":121,"123":123,"124":124,"125":125,"132":132,"44":44,"79":79,"84":84,"90":90,"94":94,"95":95,"98":98}],76:[function(require,module,exports){
module.exports = setJsonValuesAsJsonValues;
var $error = require(125);
var $atom = require(124);
var __version = require(44);
var clone = require(84);
var arrayClone = require(79);
var options = require(110);
var walkPathSet = require(132);
var isObject = require(103);
var getValidKey = require(94);
var createBranch = require(90);
var wrapNode = require(123);
var invalidateNode = require(98);
var replaceNode = require(114);
var graphNode = require(95);
var updateGraph = require(121);
var setNodeIfMissingPath = require(118);
var setNodeIfError = require(117);
var setSuccessfulPaths = require(115);
var positions = require(112);
var _cache = positions.cache;
/**
* TODO: CR More comments.
* Sets a list of PathValues into the cache and calls the onNext for each value.
* @private
*/
function setJsonValuesAsJsonValues(model, pathvalues, onNext, errorSelector, comparator) {
var modelRoot = model._root;
var modelCache = modelRoot.cache;
var initialVersion = modelCache[__version];
// TODO: CR Rename options to setup set state
var roots = options([], model, errorSelector, comparator);
var pathsIndex = -1;
var pathsCount = pathvalues.length;
var nodes = roots.nodes;
var parents = arrayClone(nodes);
var requestedPath = [];
var optimizedPath = arrayClone(roots.bound);
// TODO: CR Rename node array indicies
roots[_cache] = roots.root;
roots.onNext = onNext;
while (++pathsIndex < pathsCount) {
var pv = pathvalues[pathsIndex];
var pathset = pv.path;
roots.value = pv.value;
walkPathSet(onNode, onValueType, pathset, 0, roots, parents, nodes, requestedPath, optimizedPath);
}
var newVersion = modelCache[__version];
var rootChangeHandler = modelRoot.onChange;
if (rootChangeHandler && initialVersion !== newVersion) {
rootChangeHandler();
}
return {
values: null,
errors: roots.errors,
requestedPaths: roots.requestedPaths,
optimizedPaths: roots.optimizedPaths,
requestedMissingPaths: roots.requestedMissingPaths,
optimizedMissingPaths: roots.optimizedMissingPaths
};
}
// TODO: CR
// - comment parents and nodes initial state
// - comment parents and nodes mutation
function onNode(pathset, roots, parents, nodes, requested, optimized, isReference, isBranch, keyArg, keyset, isKeyset) {
var key = keyArg;
var parent;
if (key == null) {
key = getValidKey(optimized);
if (key == null) {
return;
}
parent = parents[_cache];
} else {
parent = nodes[_cache];
}
var node = parent[key],
type;
if (isReference) {
type = isObject(node) && node.$type || void 0;
type = type && isBranch && "." || type;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
if (isBranch) {
type = isObject(node) && node.$type || void 0;
node = createBranch(roots, parent, node, type, key);
parents[_cache] = parent;
nodes[_cache] = node;
return;
}
var selector = roots.errorSelector;
var comparator = roots.comparator;
var root = roots[_cache];
var size = isObject(node) && node.$size || 0;
var message = roots.value;
if (message === void 0 && roots.noDataSource) {
invalidateNode(parent, node, key, roots.lru);
updateGraph(parent, size, roots.version, roots.lru);
node = void 0;
} else {
type = isObject(message) && message.$type || void 0;
message = wrapNode(message, type, Boolean(type) ? message.value : message);
type = type || $atom;
if (type === $error && Boolean(selector)) {
message = selector(requested, message);
}
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
node = replaceNode(parent, node, message, key, roots.lru);
node = graphNode(root, parent, node, key, roots.version);
updateGraph(parent, size - node.$size, roots.version, roots.lru);
}
}
nodes[_cache] = node;
}
// TODO: CR describe onValueType's job
function onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset) {
var node = nodes[_cache];
var type = isObject(node) && node.$type || (node = void 0);
var isMissingPath = setNodeIfMissingPath(roots, node, type, pathset, depth, requested, optimized);
if (isMissingPath) {
return;
}
var isError = setNodeIfError(roots, node, type, requested);
if (isError) {
return;
}
if (roots.isDistinct === true) {
// TODO: CR Explain what's happening here.
roots.isDistinct = false;
setSuccessfulPaths(roots, requested, optimized);
roots.onNext({
path: arrayClone(requested),
value: clone(roots, node, type, node && node.value)
});
}
}
},{"103":103,"110":110,"112":112,"114":114,"115":115,"117":117,"118":118,"121":121,"123":123,"124":124,"125":125,"132":132,"44":44,"79":79,"84":84,"90":90,"94":94,"95":95,"98":98}],77:[function(require,module,exports){
var $error = require(125);
var pathSyntax = require(149);
var getType = require(93);
var isObject = require(103);
var isPathValue = require(104);
var setJsonValuesAsJsonDense = require(73);
module.exports = function setValueSync(pathArg, valueArg, errorSelectorArg, comparatorArg) {
var path = pathSyntax.fromPath(pathArg);
var value = valueArg;
var errorSelector = errorSelectorArg;
var comparator = comparatorArg;
if (isPathValue(path)) {
comparator = errorSelector;
errorSelector = value;
value = path;
} else {
value = {
path: path,
value: value
};
}
if (isPathValue(value) === false) {
throw new Error("Model#setValueSync must be called with an Array path.");
}
if (typeof errorSelector !== "function") {
errorSelector = this._root._errorSelector;
}
if (typeof comparator !== "function") {
comparator = this._root._comparator;
}
if (this.syncCheck("setValueSync")) {
var json = {};
var boxed = this._boxed;
var treatErrorsAsValues = this._treatErrorsAsValues;
this._boxed = true;
this._treatErrorsAsValues = true;
setJsonValuesAsJsonDense(this, [value], [json], errorSelector, comparator);
this._boxed = boxed;
this._treatErrorsAsValues = treatErrorsAsValues;
json = json.json;
if (isObject(json) === false) {
return json;
} else if (treatErrorsAsValues || getType(json) !== $error) {
if (boxed) {
return json;
} else {
return json.value;
}
} else if (boxed) {
throw json;
} else {
throw json.value;
}
}
};
},{"103":103,"104":104,"125":125,"149":149,"73":73,"93":93}],78:[function(require,module,exports){
module.exports = function arrayAppend(array, value) {
var i = -1;
var n = array.length;
var array2 = new Array(n + 1);
while (++i < n) {
array2[i] = array[i];
}
array2[i] = value;
return array2;
};
},{}],79:[function(require,module,exports){
module.exports = function arrayClone(array) {
if (!array) {
return array;
}
var i = -1;
var n = array.length;
var array2 = new Array(n);
while (++i < n) {
array2[i] = array[i];
}
return array2;
};
},{}],80:[function(require,module,exports){
module.exports = function arrayConcat(array, other) {
if (!array) {
return other;
}
var i = -1,
j = -1;
var n = array.length;
var m = other.length;
var array2 = new Array(n + m);
while (++i < n) {
array2[i] = array[i];
}
while (++j < m) {
array2[i++] = other[j];
}
return array2;
};
},{}],81:[function(require,module,exports){
module.exports = function arrayFlatMap(array, selector) {
var index = -1;
var i = -1;
var n = array.length;
var array2 = new Array(n);
while (++i < n) {
var array3 = selector(array[i], i, array);
var j = -1;
var k = array3.length;
while (++j < k) {
array2[++index] = array3[j];
}
}
return array2;
};
},{}],82:[function(require,module,exports){
module.exports = function arrayMap(array, selector) {
var i = -1;
var n = array.length;
var array2 = new Array(n);
while (++i < n) {
array2[i] = selector(array[i], i, array);
}
return array2;
};
},{}],83:[function(require,module,exports){
module.exports = function arraySlice(array, indexArg) {
var index = indexArg || 0;
var i = -1;
var n = Math.max(array.length - index, 0);
var array2 = new Array(n);
while (++i < n) {
array2[i] = array[i + index];
}
return array2;
};
},{}],84:[function(require,module,exports){
var $atom = require(124);
var clone = require(89);
module.exports = function cloneJsonDense(roots, node, type, value) {
if (node == null || value === void 0) {
return {
$type: $atom
};
}
if (roots.boxed) {
return Boolean(type) && clone(node) || node;
}
return value;
};
},{"124":124,"89":89}],85:[function(require,module,exports){
var $atom = require(124);
var clone = require(89);
var isPrimitive = require(105);
module.exports = function cloneJsonGraph(roots, node, type, value) {
if (node == null || value === void 0) {
return {
$type: $atom
};
}
if (roots.boxed === true) {
return Boolean(type) && clone(node) || node;
}
if (!type || (type === $atom && isPrimitive(value))) {
return value;
}
return clone(node);
};
},{"105":105,"124":124,"89":89}],86:[function(require,module,exports){
var cloneRequestedPath = require(88);
var cloneOptimizedPath = require(87);
module.exports = function cloneMissingPathSets(roots, pathset, depth, requested, optimized) {
roots.requestedMissingPaths.push(cloneRequestedPath(roots.bound, requested, pathset, depth, roots.index));
roots.optimizedMissingPaths.push(cloneOptimizedPath(optimized, pathset, depth));
};
},{"87":87,"88":88}],87:[function(require,module,exports){
module.exports = function cloneOptimizedPath(optimized, pathset, depth) {
var x;
var i = -1;
var j = depth - 1;
var n = optimized.length;
var m = pathset.length;
var array2 = [];
while (++i < n) {
array2[i] = optimized[i];
}
while (++j < m) {
x = pathset[j];
if (x != null) {
array2[i++] = x;
}
}
return array2;
};
},{}],88:[function(require,module,exports){
var isObject = require(103);
module.exports = function cloneRequestedPath(bound, requested, pathset, depth, index) {
var x;
var i = -1;
var j = -1;
var l = 0;
var m = requested.length;
var n = bound.length;
var array2 = [];
while (++i < n) {
array2[i] = bound[i];
}
while (++j < m) {
x = requested[j];
if (x != null) {
if (isObject(pathset[l++])) {
array2[i++] = [x];
} else {
array2[i++] = x;
}
}
}
m = n + l + pathset.length - depth;
while (i < m) {
array2[i++] = pathset[l++];
}
if (index != null) {
array2.pathSetIndex = index;
}
return array2;
};
},{"103":103}],89:[function(require,module,exports){
var isObject = require(103);
var prefix = require(38);
module.exports = function clone(value) {
var dest = value,
src = dest,
i = -1,
n, keys, key;
if (isObject(dest)) {
dest = {};
keys = Object.keys(src);
n = keys.length;
while (++i < n) {
key = keys[i];
if (key[0] !== prefix) {
dest[key] = src[key];
}
}
}
return dest;
};
},{"103":103,"38":38}],90:[function(require,module,exports){
var $ref = require(126);
var $expired = "expired";
var replaceNode = require(114);
var graphNode = require(95);
var updateBackRefs = require(120);
var isPrimitive = require(105);
var isExpired = require(99);
// TODO: comment about what happens if node is a branch vs leaf.
module.exports = function createBranch(roots, parent, nodeArg, typeArg, key) {
var node = nodeArg;
var type = typeArg;
if (Boolean(type) && isExpired(roots, node)) {
type = $expired;
}
if ((Boolean(type) && type !== $ref) || isPrimitive(node)) {
node = replaceNode(parent, node, {}, key, roots.lru);
node = graphNode(roots[0], parent, node, key, void 0);
node = updateBackRefs(node, roots.version);
}
return node;
};
},{"105":105,"114":114,"120":120,"126":126,"95":95,"99":99}],91:[function(require,module,exports){
var __ref = require(41);
var __context = require(31);
var __refIndex = require(40);
var __refsLength = require(42);
module.exports = function deleteBackRefs(node) {
var ref, i = -1,
n = node[__refsLength] || 0;
while (++i < n) {
ref = node[__ref + i];
if (ref != null) {
ref[__context] = ref[__refIndex] = node[__ref + i] = void 0;
}
}
node[__refsLength] = void 0;
};
},{"31":31,"40":40,"41":41,"42":42}],92:[function(require,module,exports){
var isObject = require(103);
module.exports = function getSize(node) {
return isObject(node) && node.$size || 0;
};
},{"103":103}],93:[function(require,module,exports){
var isObject = require(103);
module.exports = function getType(node, anyType) {
var type = isObject(node) && node.$type || void 0;
if (anyType && type) {
return "branch";
}
return type;
};
},{"103":103}],94:[function(require,module,exports){
module.exports = function getValidKey(path) {
var key, index = path.length - 1;
do {
key = path[index];
if (key != null) {
return key;
}
} while (--index > -1);
return null;
};
},{}],95:[function(require,module,exports){
var __key = require(34);
var __parent = require(37);
var __version = require(44);
module.exports = function graphNode(root, parent, node, key, version) {
node[__parent] = parent;
node[__key] = key;
node[__version] = version;
return node;
};
},{"34":34,"37":37,"44":44}],96:[function(require,module,exports){
module.exports = function identity(x) {
return x;
};
},{}],97:[function(require,module,exports){
var version = 1;
module.exports = function incrementVersion() {
return version++;
};
},{}],98:[function(require,module,exports){
var isObject = require(103);
var removeNode = require(113);
var prefix = require(38);
module.exports = function invalidateNode(parent, node, key, lru) {
if (removeNode(parent, node, key, lru)) {
var type = isObject(node) && node.$type || void 0;
if (type == null) {
var keys = Object.keys(node);
for (var i = -1, n = keys.length; ++i < n;) {
var key2 = keys[i];
if (key2[0] !== prefix && key2[0] !== "$") {
invalidateNode(node, node[key2], key2, lru);
}
}
}
return true;
}
return false;
};
},{"103":103,"113":113,"38":38}],99:[function(require,module,exports){
var $expiresNow = require(128);
var $expiresNever = require(127);
var __invalidated = require(33);
var now = require(109);
var splice = require(49);
module.exports = function isExpired(roots, node) {
var expires = node.$expires;
if ((expires != null) && (
expires !== $expiresNever) && (
expires === $expiresNow || expires < now())) {
if (!node[__invalidated]) {
node[__invalidated] = true;
roots.expired.push(node);
splice(roots.lru, node);
}
return true;
}
return false;
};
},{"109":109,"127":127,"128":128,"33":33,"49":49}],100:[function(require,module,exports){
var functionTypeof = "function";
module.exports = function isFunction(func) {
return Boolean(func) && typeof func === functionTypeof;
};
},{}],101:[function(require,module,exports){
var isObject = require(103);
module.exports = function isJsonGraphEnvelope(envelope) {
return isObject(envelope) && ("json" in envelope);
};
},{"103":103}],102:[function(require,module,exports){
var isArray = Array.isArray;
var isObject = require(103);
module.exports = function isJsonGraphEnvelope(envelope) {
return isObject(envelope) && isArray(envelope.paths) && (
isObject(envelope.jsonGraph) ||
isObject(envelope.jsong) ||
isObject(envelope.json) ||
isObject(envelope.values) ||
isObject(envelope.value)
);
};
},{"103":103}],103:[function(require,module,exports){
var objTypeof = "object";
module.exports = function isObject(value) {
return value !== null && typeof value === objTypeof;
};
},{}],104:[function(require,module,exports){
var isArray = Array.isArray;
var isObject = require(103);
module.exports = function isPathValue(pathValue) {
return isObject(pathValue) && (
isArray(pathValue.path) || (
typeof pathValue.path === "string"
));
};
},{"103":103}],105:[function(require,module,exports){
var objTypeof = "object";
module.exports = function isPrimitive(value) {
return value == null || typeof value !== objTypeof;
};
},{}],106:[function(require,module,exports){
var __offset = require(36);
var isArray = Array.isArray;
var isObject = require(103);
module.exports = function keyToKeyset(keyArg, iskeyset) {
var key = keyArg;
if (iskeyset) {
if (isArray(key)) {
key = key[key[__offset]];
return keyToKeyset(key, isObject(key));
} else {
return key[__offset];
}
}
return key;
};
},{"103":103,"36":36}],107:[function(require,module,exports){
var __parent = require(37);
var $ref = require(126);
var isObject = require(103);
var isExpired = require(99);
var promote = require(48);
var wrapNode = require(123);
var graphNode = require(95);
var replaceNode = require(114);
var updateGraph = require(121);
var invalidateNode = require(98);
/* eslint-disable eqeqeq */
module.exports = function mergeNode(roots, parent, nodeArg, messageParent, messageArg, key, requested) {
var node = nodeArg;
var message = messageArg;
var type, messageType, nodeIsObject, messageIsObject;
// If the cache and message are the same, we can probably return early:
// - If they're both null, return null.
// - If they're both branches, return the branch.
// - If they're both edges, continue below.
if (node == message) {
if (node == null) {
return null;
} else if ((nodeIsObject = isObject(node))) {
type = node.$type;
if (type == null) {
if (node[__parent] == null) {
return graphNode(roots[0], parent, node, key, void 0);
}
return node;
}
}
} else if ((nodeIsObject = isObject(node))) {
type = node.$type;
}
var value, messageValue;
if (type == $ref) {
if (message == null) {
// If the cache is an expired reference, but the message
// is empty, remove the cache value and return undefined
// so we build a missing path.
if (isExpired(roots, node)) {
invalidateNode(parent, node, key, roots.lru);
return void 0;
}
// If the cache has a reference and the message is empty,
// leave the cache alone and follow the reference.
return node;
} else if ((messageIsObject = isObject(message))) {
messageType = message.$type;
// If the cache and the message are both references,
// check if we need to replace the cache reference.
if (messageType == $ref) {
if (node === message) {
// If the cache and message are the same reference,
// we performed a whole-branch merge of one of the
// grandparents. If we've previously graphed this
// reference, break early.
if (node[__parent] != null) {
return node;
}
}
// If the message doesn't expire immediately and is newer than the
// cache (or either cache or message don't have timestamps), attempt
// to use the message value.
// Note: Number and `undefined` compared LT/GT to `undefined` is `false`.
else if ((
isExpired(roots, message) === false) && ((
message.$timestamp < node.$timestamp) === false)) {
// Compare the cache and message references.
// - If they're the same, break early so we don't insert.
// - If they're different, replace the cache reference.
value = node.value;
messageValue = message.value;
var count = value.length;
// If the reference lengths are equal, check their keys for equality.
if (count === messageValue.length) {
while (--count > -1) {
// If any of their keys are different, replace the reference
// in the cache with the reference in the message.
if (value[count] !== messageValue[count]) {
break;
}
}
// If all their keys are equal, leave the cache value alone.
if (count === -1) {
return node;
}
}
}
}
}
} else {
if ((messageIsObject = isObject(message))) {
messageType = message.$type;
}
if (nodeIsObject && !type) {
// Otherwise if the cache is a branch and the message is either
// null or also a branch, continue with the cache branch.
if (message == null || (messageIsObject && !messageType)) {
return node;
}
}
}
// If the message is an expired edge, report it back out so we don't build a missing path, but
// don't insert it into the cache. If a value exists in the cache that didn't come from a
// whole-branch grandparent merge, remove the cache value.
if (Boolean(messageType) && Boolean(message[__parent]) && isExpired(roots, message)) {
if (nodeIsObject && node != message) {
invalidateNode(parent, node, key, roots.lru);
}
return message;
}
// If the cache is a value, but the message is a branch, merge the branch over the value.
else if (Boolean(type) && messageIsObject && !messageType) {
node = replaceNode(parent, node, message, key, roots.lru);
return graphNode(roots[0], parent, node, key, void 0);
}
// If the message is a value, insert it into the cache.
else if (!messageIsObject || Boolean(messageType)) {
var offset = 0;
// If we've arrived at this message value, but didn't perform a whole-branch merge
// on one of its ancestors, replace the cache node with the message value.
if (node != message) {
messageValue = messageValue || (Boolean(messageType) ? message.value : message);
message = wrapNode(message, messageType, messageValue);
var comparator = roots.comparator;
var isDistinct = roots.isDistinct = true;
if (Boolean(comparator)) {
isDistinct = roots.isDistinct = !comparator(requested, node, message);
}
if (isDistinct) {
var size = nodeIsObject && node.$size || 0;
var messageSize = message.$size;
offset = size - messageSize;
node = replaceNode(parent, node, message, key, roots.lru);
updateGraph(parent, offset, roots.version, roots.lru);
node = graphNode(roots[0], parent, node, key, roots.version);
}
}
// If the cache and the message are the same value, we branch-merged one of its
// ancestors. Give the message a $size and $type, attach its graph pointers, and
// update the cache sizes and versions.
else if (nodeIsObject && node[__parent] == null) {
roots.isDistinct = true;
node = parent[key] = wrapNode(node, type, node.value);
offset = -node.$size;
updateGraph(parent, offset, roots.version, roots.lru);
node = graphNode(roots[0], parent, node, key, roots.version);
}
// Otherwise, cache and message are the same primitive value. Wrap in a atom and insert.
else {
roots.isDistinct = true;
node = parent[key] = wrapNode(node, type, node);
offset = -node.$size;
updateGraph(parent, offset, roots.version, roots.lru);
node = graphNode(roots[0], parent, node, key, roots.version);
}
// If the node is already expired, return undefined to build a missing path.
// if(isExpired(roots, node)) {
// return undefined;
// }
// Promote the message edge in the LRU.
promote(roots.lru, node);
}
// If we get here, the cache is empty and the message is a branch.
// Merge the whole branch over.
else if (node == null) {
node = parent[key] = graphNode(roots[0], parent, message, key, void 0);
}
return node;
};
/* eslint-enable */
},{"103":103,"114":114,"121":121,"123":123,"126":126,"37":37,"48":48,"95":95,"98":98,"99":99}],108:[function(require,module,exports){
module.exports = function noop() {};
},{}],109:[function(require,module,exports){
module.exports = Date.now;
},{}],110:[function(require,module,exports){
var incVersion = require(97);
var getBoundValue = require(14);
/**
* TODO: more options state tracking comments.
*/
module.exports = function getInitialState(options, model, errorSelector, comparator) {
var bound = options.bound || (options.bound = model._path || []);
var root = options.root || (options.root = model._root.cache);
var nodes = options.nodes || (options.nodes = []);
var lru = options.lru || (options.lru = model._root);
options.expired = options.expired || lru.expired;
options.errors = options.errors || [];
options.requestedPaths = options.requestedPaths || [];
options.optimizedPaths = options.optimizedPaths || [];
options.requestedMissingPaths = options.requestedMissingPaths || [];
options.optimizedMissingPaths = options.optimizedMissingPaths || [];
options.boxed = model._boxed || false;
options.materialized = model._materialized;
options.errorsAsValues = model._treatErrorsAsValues || false;
options.noDataSource = model._source == null;
options.version = model._version = incVersion();
options.offset = options.offset || 0;
options.errorSelector = errorSelector || model._errorSelector;
options.comparator = comparator;
if (bound.length) {
nodes[0] = getBoundValue(model, bound).value;
} else {
nodes[0] = root;
}
return options;
};
},{"14":14,"97":97}],111:[function(require,module,exports){
var __offset = require(36);
var isArray = Array.isArray;
var isObject = require(103);
module.exports = function permuteKeyset(key) {
if (isArray(key)) {
if (key.length === 0) {
return false;
}
if (key[__offset] === void 0) {
return permuteKeyset(key[key[__offset] = 0]) || true;
} else if (permuteKeyset(key[key[__offset]])) {
return true;
} else if (++key[__offset] >= key.length) {
key[__offset] = void 0;
return false;
} else {
return true;
}
} else if (isObject(key)) {
if (key[__offset] === void 0) {
key[__offset] = (key.from || (key.from = 0)) - 1;
if (key.to === void 0) {
if (key.length === void 0) {
throw new Error("Range keysets must specify at least one index to retrieve.");
} else if (key.length === 0) {
return false;
}
key.to = key.from + (key.length || 1) - 1;
}
}
if (++key[__offset] > key.to) {
key[__offset] = key.from - 1;
return false;
}
return true;
}
return false;
};
},{"103":103,"36":36}],112:[function(require,module,exports){
module.exports = {
cache: 0,
message: 1,
jsong: 2,
json: 3
};
},{}],113:[function(require,module,exports){
var $ref = require(126);
var __parent = require(37);
var unlink = require(119);
var deleteBackRefs = require(91);
var splice = require(49);
var isObject = require(103);
module.exports = function removeNode(parent, node, key, lru) {
if (isObject(node)) {
var type = node.$type;
if (Boolean(type)) {
if (type === $ref) {
unlink(node);
}
splice(lru, node);
}
deleteBackRefs(node);
parent[key] = node[__parent] = void 0;
return true;
}
return false;
};
},{"103":103,"119":119,"126":126,"37":37,"49":49,"91":91}],114:[function(require,module,exports){
var transferBackRefs = require(116);
var invalidateNode = require(98);
module.exports = function replaceNode(parent, node, replacement, key, lru) {
if (node != null && node !== replacement && typeof node === "object") {
transferBackRefs(node, replacement);
invalidateNode(parent, node, key, lru);
}
parent[key] = replacement;
return replacement;
};
},{"116":116,"98":98}],115:[function(require,module,exports){
var arraySlice = require(83);
var arrayClone = require(79);
module.exports = function cloneSuccessPaths(roots, requested, optimized) {
roots.requestedPaths.push(arraySlice(requested, roots.offset));
roots.optimizedPaths.push(arrayClone(optimized));
};
},{"79":79,"83":83}],116:[function(require,module,exports){
var __ref = require(41);
var __context = require(31);
var __refsLength = require(42);
module.exports = function transferBackReferences(node, dest) {
var nodeRefsLength = node[__refsLength] || 0,
destRefsLength = dest[__refsLength] || 0,
i = -1,
ref;
while (++i < nodeRefsLength) {
ref = node[__ref + i];
if (ref !== void 0) {
ref[__context] = dest;
dest[__ref + (destRefsLength + i)] = ref;
node[__ref + i] = void 0;
}
}
dest[__refsLength] = nodeRefsLength + destRefsLength;
node[__refsLength] = ref = void 0;
};
},{"31":31,"41":41,"42":42}],117:[function(require,module,exports){
var $error = require(125);
var promote = require(48);
var arrayClone = require(79);
var clone = require(89);
module.exports = function treatNodeAsError(roots, node, type, path) {
if (node == null) {
return false;
}
promote(roots.lru, node);
if (type !== $error || roots.errorsAsValues) {
return false;
}
roots.errors.push({
path: arrayClone(path),
value: roots.boxed && clone(node) || node.value
});
return true;
};
},{"125":125,"48":48,"79":79,"89":89}],118:[function(require,module,exports){
var $atom = require(124);
var cloneMisses = require(86);
var isExpired = require(99);
module.exports = function treatNodeAsMissingPathSet(roots, node, type, pathset, depth, requested, optimized) {
var dematerialized = !roots.materialized;
if (node == null && dematerialized) {
cloneMisses(roots, pathset, depth, requested, optimized);
return true;
} else if (Boolean(type)) {
if (type === $atom && node.value === void 0 && dematerialized && !roots.boxed) {
// Don't clone the missing paths because we found a value, but don't want to report it.
// TODO: CR Explain weirdness further.
return true;
} else if (isExpired(roots, node)) {
cloneMisses(roots, pathset, depth, requested, optimized);
return true;
}
}
return false;
};
},{"124":124,"86":86,"99":99}],119:[function(require,module,exports){
var __ref = require(41);
var __context = require(31);
var __refIndex = require(40);
var __refsLength = require(42);
module.exports = function unlinkRef(ref) {
var destination = ref[__context];
if (destination) {
var i = (ref[__refIndex] || 0) - 1,
n = (destination[__refsLength] || 0) - 1;
while (++i <= n) {
destination[__ref + i] = destination[__ref + (i + 1)];
}
destination[__refsLength] = n;
ref[__refIndex] = ref[__context] = destination = void 0;
}
};
},{"31":31,"40":40,"41":41,"42":42}],120:[function(require,module,exports){
var __ref = require(41);
var __parent = require(37);
var __version = require(44);
var __refsLength = require(42);
module.exports = function updateBackRefs(node, version) {
if (node && node[__version] !== version) {
node[__version] = version;
updateBackRefs(node[__parent], version);
var i = -1,
n = node[__refsLength] || 0;
while (++i < n) {
updateBackRefs(node[__ref + i], version);
}
}
return node;
};
},{"37":37,"41":41,"42":42,"44":44}],121:[function(require,module,exports){
var __key = require(34);
var __version = require(44);
var __parent = require(37);
var removeNode = require(113);
var updateBackRefs = require(120);
module.exports = function updateGraph(nodeArg, offset, version, lru) {
var node = nodeArg;
var child = nodeArg;
var size;
while (child) {
node = child[__parent];
size = child.$size = (child.$size || 0) - offset;
if (size <= 0 && node != null) {
removeNode(node, child, child[__key], lru);
} else if (child[__version] !== version) {
updateBackRefs(child, version);
}
child = node;
}
};
},{"113":113,"120":120,"34":34,"37":37,"44":44}],122:[function(require,module,exports){
var isArray = Array.isArray;
var isPathValue = require(104);
var isJsonGraphEnvelope = require(102);
var isJsonEnvelope = require(101);
var pathSyntax = require(149);
/**
*
* @param {Object} allowedInput - allowedInput is a map of input styles
* that are allowed
* @private
*/
module.exports = function validateInput(args, allowedInput, method) {
for (var i = 0, len = args.length; i < len; ++i) {
var arg = args[i];
var valid = false;
// Path
if (isArray(arg) && allowedInput.path) {
valid = true;
}
// Path Syntax
else if (typeof arg === "string" && allowedInput.pathSyntax) {
valid = true;
}
// Path Value
else if (isPathValue(arg) && allowedInput.pathValue) {
arg.path = pathSyntax.fromPath(arg.path);
valid = true;
}
// jsonGraph {jsonGraph: { ... }, paths: [ ... ]}
else if (isJsonGraphEnvelope(arg) && allowedInput.jsonGraph) {
valid = true;
}
// json env {json: {...}}
else if (isJsonEnvelope(arg) && allowedInput.json) {
valid = true;
}
// selector functions
else if (typeof arg === "function" &&
i + 1 === len &&
allowedInput.selector) {
valid = true;
}
if (!valid) {
return new Error("Unrecognized argument " + (typeof arg) + " [" + String(arg) + "] " + "to Model#" + method + "");
}
}
return true;
};
},{"101":101,"102":102,"104":104,"149":149}],123:[function(require,module,exports){
var $atom = require(124);
var now = require(109);
var clone = require(89);
var isArray = Array.isArray;
var isObject = require(103);
// TODO: CR Wraps a node for insertion.
// TODO: CR Define default atom size values.
module.exports = function wrapNode(node, typeArg, value) {
var type = typeArg;
var dest = node,
size = 0;
if (Boolean(type)) {
dest = clone(node);
size = dest.$size;
// }
// if(type == $ref) {
// dest = clone(node);
// size = 50 + (value.length || 1);
// } else if(isObject(node) && (type || (type = node.$type))) {
// dest = clone(node);
// size = dest.$size;
} else {
dest = {
value: value
};
type = $atom;
}
if (size <= 0 || size == null) {
switch (typeof value) {
case "object":
size = isArray(value) && (50 + value.length) || 51;
break;
case "string":
size = 50 + value.length;
break;
default:
size = 51;
break;
}
}
var expires = isObject(node) && node.$expires || void 0;
if (typeof expires === "number" && expires < 0) {
dest.$expires = now() + (expires * -1);
}
dest.$type = type;
dest.$size = size;
return dest;
};
},{"103":103,"109":109,"124":124,"89":89}],124:[function(require,module,exports){
module.exports = "atom";
},{}],125:[function(require,module,exports){
module.exports = "error";
},{}],126:[function(require,module,exports){
module.exports = "ref";
},{}],127:[function(require,module,exports){
module.exports = 1;
},{}],128:[function(require,module,exports){
module.exports = 0;
},{}],129:[function(require,module,exports){
module.exports = walkPathMap;
var prefix = require(38);
var $ref = require(126);
var walkReference = require(133);
var arrayClone = require(79);
var arrayAppend = require(78);
var isExpired = require(99);
var isPrimitive = require(105);
var isObject = require(103);
var isArray = Array.isArray;
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
var _message = positions.message;
var _jsong = positions.jsong;
function walkPathMap(onNode, onValueType, pathmap, keysStack, depth, roots, parents, nodes, requested, optimizedArg, key, keyset, isKeyset) {
var optimized = optimizedArg;
var node = nodes[_cache];
if (isPrimitive(pathmap) || isPrimitive(node)) {
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while (type === $ref) {
if (isExpired(roots, node)) {
nodes[_cache] = void 0;
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[_cache] = parents[_cache] = roots[_cache];
nodes[_jsong] = parents[_jsong] = roots[_jsong];
nodes[_message] = parents[_message] = roots[_message];
walkReference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[_cache];
if (node == null) {
optimized = arrayClone(reference);
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else {
if (isObject(node)) {
type = node.$type;
}
if ((Boolean(type) && type !== $ref) || isPrimitive(node)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, false, null, keyset, false);
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, arrayAppend(requested, null), optimized, key, keyset);
}
}
}
if (type != null) {
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keysStack[depth] = Object.keys(pathmap);
// Force in the arrays hidden field length.
if (isArray(pathmap)) {
keys[keys.length] = "length";
}
if (keys.length === 0) {
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var isOuterKeyset = keys.length > 1;
for (var i = -1, n = keys.length; ++i < n;) {
var innerKey = keys[i];
if ((innerKey[0] === prefix) || (innerKey[0] === "$")) {
continue;
}
var innerKeyset = isOuterKeyset ? innerKey : keyset;
var nodes2 = arrayClone(nodes);
var parents2 = arrayClone(parents);
var pathmap2 = pathmap[innerKey];
var requested2, optimized2;
var childKey = false;
var isBranch = isObject(pathmap2) && !pathmap2.$type; // && !isArray(pathmap2);
if (isBranch) {
for (childKey in pathmap2) {
if ((childKey[0] === prefix) || (childKey[0] === "$")) {
continue;
}
childKey = pathmap2.hasOwnProperty(childKey);
break;
}
isBranch = childKey === true;
}
requested2 = arrayAppend(requested, innerKey);
optimized2 = arrayAppend(optimized, innerKey);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, false, isBranch, innerKey, innerKeyset, isOuterKeyset);
if (isBranch) {
walkPathMap(onNode, onValueType,
pathmap2, keysStack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
innerKey, innerKeyset, isOuterKeyset
);
} else {
onValueType(pathmap2, keysStack, depth + 1, roots, parents2, nodes2, requested2, optimized2, innerKey, innerKeyset);
}
}
}
},{"103":103,"105":105,"112":112,"126":126,"133":133,"38":38,"48":48,"78":78,"79":79,"99":99}],130:[function(require,module,exports){
module.exports = walkPathMap;
var prefix = require(38);
var __context = require(31);
var $ref = require(126);
var walkReference = require(133);
var arrayClone = require(79);
var arrayAppend = require(78);
var isExpired = require(99);
var isPrimitive = require(105);
var isObject = require(103);
var isArray = Array.isArray;
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
function walkPathMap(onNode, onValueType, pathmap, keysStack, depth, roots, parents, nodes, requested, optimizedArg, key, keyset, isKeyset) {
var optimized = optimizedArg;
var node = nodes[_cache];
if (isPrimitive(pathmap) || isPrimitive(node)) {
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while (type === $ref) {
if (isExpired(roots, node)) {
nodes[_cache] = void 0;
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if (node != null) {
type = node.$type;
optimized = arrayClone(reference);
nodes[_cache] = node;
} else {
nodes[_cache] = parents[_cache] = roots[_cache];
walkReference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[_cache];
if (node == null) {
optimized = arrayClone(reference);
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else {
if (isObject(node)) {
type = node.$type;
}
if ((Boolean(type) && type !== $ref) || isPrimitive(node)) {
onNode(pathmap, roots, parents, nodes, requested, optimized, false, null, keyset, false);
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, arrayAppend(requested, null), optimized, key, keyset);
}
}
}
}
if (type != null) {
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var keys = keysStack[depth] = Object.keys(pathmap);
// Force in the arrays hidden field length.
if (isArray(pathmap)) {
keys[keys.length] = "length";
}
if (keys.length === 0) {
return onValueType(pathmap, keysStack, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var isOuterKeyset = keys.length > 1;
for (var i = -1, n = keys.length; ++i < n;) {
var innerKey = keys[i];
if ((innerKey[0] === prefix) || (innerKey[0] === "$")) {
continue;
}
var innerKeyset = isOuterKeyset ? innerKey : keyset;
var nodes2 = arrayClone(nodes);
var parents2 = arrayClone(parents);
var pathmap2 = pathmap[innerKey];
var requested2, optimized2;
var childKey = false;
var isBranch = isObject(pathmap2) && !pathmap2.$type; // && !isArray(pathmap2);
if (isBranch) {
for (childKey in pathmap2) {
if ((childKey[0] === prefix) || (childKey[0] === "$")) {
continue;
}
childKey = pathmap2.hasOwnProperty(childKey);
break;
}
isBranch = childKey === true;
}
if (innerKey === "null") {
requested2 = arrayAppend(requested, null);
optimized2 = arrayClone(optimized);
innerKey = key;
innerKeyset = keyset;
pathmap2 = pathmap;
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, false, isBranch, null, innerKeyset, false);
} else {
requested2 = arrayAppend(requested, innerKey);
optimized2 = arrayAppend(optimized, innerKey);
onNode(pathmap2, roots, parents2, nodes2, requested2, optimized2, false, isBranch, innerKey, innerKeyset, isOuterKeyset);
}
if (isBranch) {
walkPathMap(onNode, onValueType,
pathmap2, keysStack, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
innerKey, innerKeyset, isOuterKeyset
);
} else {
onValueType(pathmap2, keysStack, depth + 1, roots, parents2, nodes2, requested2, optimized2, innerKey, innerKeyset);
}
}
}
},{"103":103,"105":105,"112":112,"126":126,"133":133,"31":31,"38":38,"48":48,"78":78,"79":79,"99":99}],131:[function(require,module,exports){
module.exports = walkPathSet;
var $ref = require(126);
var walkReference = require(133);
var arrayClone = require(79);
var arrayAppend = require(78);
var isExpired = require(99);
var isPrimitive = require(105);
var isObject = require(103);
var keysetToKey = require(106);
var permuteKeyset = require(111);
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
var _message = positions.message;
var _jsong = positions.jsong;
function walkPathSet(onNode, onValueType, pathset, depth, roots, parents, nodes, requested, optimizedArg, key, keyset, isKeyset) {
var optimized = optimizedArg;
var node = nodes[_cache];
if (depth >= pathset.length || isPrimitive(node)) {
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while (type === $ref) {
if (isExpired(roots, node)) {
nodes[_cache] = void 0;
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
nodes[_cache] = parents[_cache] = roots[_cache];
nodes[_jsong] = parents[_jsong] = roots[_jsong];
nodes[_message] = parents[_message] = roots[_message];
walkReference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[_cache];
if (node == null) {
optimized = arrayClone(reference);
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else {
if (isObject(node)) {
type = node.$type;
}
if ((Boolean(type) && type !== $ref) || isPrimitive(node)) {
onNode(pathset, roots, parents, nodes, requested, optimized, false, false, null, keyset, false);
return onValueType(pathset, depth, roots, parents, nodes, arrayAppend(requested, null), optimized, key, keyset);
}
}
}
if (type != null) {
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outerKey = pathset[depth];
var isOuterKeyset = isObject(outerKey);
var isBranch = depth < pathset.length - 1;
var runOnce = false;
while (isOuterKeyset && permuteKeyset(outerKey) || (!runOnce)) {
runOnce = true;
var innerKey, innerKeyset;
if (isOuterKeyset === true) {
innerKey = keysetToKey(outerKey, true);
innerKeyset = innerKey;
} else {
innerKey = outerKey;
innerKeyset = keyset;
}
var nodes2 = arrayClone(nodes);
var parents2 = arrayClone(parents);
var requested2, optimized2;
if (innerKey == null) {
requested2 = arrayAppend(requested, null);
optimized2 = arrayClone(optimized);
// optimized2 = optimized;
innerKey = key;
innerKeyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, false, isBranch, null, innerKeyset, false);
} else {
requested2 = arrayAppend(requested, innerKey);
optimized2 = arrayAppend(optimized, innerKey);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, false, isBranch, innerKey, innerKeyset, isOuterKeyset);
}
walkPathSet(onNode, onValueType,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
innerKey, innerKeyset, isOuterKeyset
);
}
}
},{"103":103,"105":105,"106":106,"111":111,"112":112,"126":126,"133":133,"48":48,"78":78,"79":79,"99":99}],132:[function(require,module,exports){
module.exports = walkPathSet;
var __context = require(31);
var $ref = require(126);
var walkReference = require(133);
var arrayClone = require(79);
var arrayAppend = require(78);
var isExpired = require(99);
var isPrimitive = require(105);
var isObject = require(103);
var keysetToKey = require(106);
var permuteKeyset = require(111);
var promote = require(48);
var positions = require(112);
var _cache = positions.cache;
function walkPathSet(onNode, onValueType, pathset, depth, roots, parents, nodes, requested, optimizedArg, key, keyset, isKeyset) {
var optimized = optimizedArg;
var node = nodes[_cache];
if (depth >= pathset.length || isPrimitive(node)) {
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var type = node.$type;
while (type === $ref) {
if (isExpired(roots, node)) {
nodes[_cache] = void 0;
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
promote(roots.lru, node);
var container = node;
var reference = node.value;
node = node[__context];
if (node != null) {
type = node.$type;
optimized = arrayClone(reference);
nodes[_cache] = node;
} else {
nodes[_cache] = parents[_cache] = roots[_cache];
walkReference(onNode, container, reference, roots, parents, nodes, requested, optimized);
node = nodes[_cache];
if (node == null) {
optimized = arrayClone(reference);
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
} else {
if (isObject(node)) {
type = node.$type;
}
if ((Boolean(type) && type !== $ref) || isPrimitive(node)) {
onNode(pathset, roots, parents, nodes, requested, optimized, false, false, null, keyset, false);
return onValueType(pathset, depth, roots, parents, nodes, arrayAppend(requested, null), optimized, key, keyset);
}
}
}
}
if (type != null) {
return onValueType(pathset, depth, roots, parents, nodes, requested, optimized, key, keyset);
}
var outerKey = pathset[depth];
var isOuterKeyset = isObject(outerKey);
var isBranch = depth < pathset.length - 1;
var runOnce = false;
while (isOuterKeyset && permuteKeyset(outerKey) || (!runOnce)) {
runOnce = true;
var innerKey, innerKeyset;
if (isOuterKeyset === true) {
innerKey = keysetToKey(outerKey, true);
innerKeyset = innerKey;
} else {
innerKey = outerKey;
innerKeyset = keyset;
}
var nodes2 = arrayClone(nodes);
var parents2 = arrayClone(parents);
var requested2, optimized2;
if (innerKey == null) {
requested2 = arrayAppend(requested, null);
optimized2 = arrayClone(optimized);
// optimized2 = optimized;
innerKey = key;
innerKeyset = keyset;
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, false, isBranch, null, innerKeyset, false);
} else {
requested2 = arrayAppend(requested, innerKey);
optimized2 = arrayAppend(optimized, innerKey);
onNode(pathset, roots, parents2, nodes2, requested2, optimized2, false, isBranch, innerKey, innerKeyset, isOuterKeyset);
}
walkPathSet(onNode, onValueType,
pathset, depth + 1,
roots, parents2, nodes2,
requested2, optimized2,
innerKey, innerKeyset, isOuterKeyset
);
}
}
},{"103":103,"105":105,"106":106,"111":111,"112":112,"126":126,"133":133,"31":31,"48":48,"78":78,"79":79,"99":99}],133:[function(require,module,exports){
module.exports = walkReference;
var __ref = require(41);
var __context = require(31);
var __refIndex = require(40);
var __refsLength = require(42);
var isObject = require(103);
var isPrimitive = require(105);
var positions = require(112);
var _cache = positions.cache;
function walkReference(onNode, container, reference, roots, parents, nodes, requested, optimized) {
optimized.length = 0;
var index = -1;
var count = reference.length;
var node, key, keyset;
while (++index < count) {
node = nodes[_cache];
if (node == null) {
return nodes;
} else if (isPrimitive(node) || node.$type) {
onNode(reference, roots, parents, nodes, requested, optimized, true, false, keyset, null, false);
return nodes;
}
do {
key = reference[index];
if (key != null) {
keyset = key;
optimized.push(key);
onNode(reference, roots, parents, nodes, requested, optimized, true, index < count - 1, key, null, false);
break;
}
} while (++index < count);
}
node = nodes[_cache];
if (isObject(node) && container[__context] !== node) {
var backrefs = node[__refsLength] || 0;
node[__refsLength] = backrefs + 1;
node[__ref + backrefs] = container;
container[__context] = node;
container[__refIndex] = backrefs;
}
return nodes;
}
},{"103":103,"105":105,"112":112,"31":31,"40":40,"41":41,"42":42}],134:[function(require,module,exports){
"use strict";
// rawAsap provides everything we need except exception management.
var rawAsap = require(135);
// RawTasks are recycled to reduce GC churn.
var freeTasks = [];
// We queue errors to ensure they are thrown in right order (FIFO).
// Array-as-queue is good enough here, since we are just dealing with exceptions.
var pendingErrors = [];
var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError);
function throwFirstError() {
if (pendingErrors.length) {
throw pendingErrors.shift();
}
}
/**
* Calls a task as soon as possible after returning, in its own event, with priority
* over other events like animation, reflow, and repaint. An error thrown from an
* event will not interrupt, nor even substantially slow down the processing of
* other events, but will be rather postponed to a lower priority event.
* @param {{call}} task A callable object, typically a function that takes no
* arguments.
*/
module.exports = asap;
function asap(task) {
var rawTask;
if (freeTasks.length) {
rawTask = freeTasks.pop();
} else {
rawTask = new RawTask();
}
rawTask.task = task;
rawAsap(rawTask);
}
// We wrap tasks with recyclable task objects. A task object implements
// `call`, just like a function.
function RawTask() {
this.task = null;
}
// The sole purpose of wrapping the task is to catch the exception and recycle
// the task object after its single use.
RawTask.prototype.call = function () {
try {
this.task.call();
} catch (error) {
if (asap.onerror) {
// This hook exists purely for testing purposes.
// Its name will be periodically randomized to break any code that
// depends on its existence.
asap.onerror(error);
} else {
// In a web browser, exceptions are not fatal. However, to avoid
// slowing down the queue of pending tasks, we rethrow the error in a
// lower priority turn.
pendingErrors.push(error);
requestErrorThrow();
}
} finally {
this.task = null;
freeTasks[freeTasks.length] = this;
}
};
},{"135":135}],135:[function(require,module,exports){
(function (global){
"use strict";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including IO, animation, reflow, and redraw
// events in browsers.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Equivalent to push, but avoids a function call.
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// `requestFlush` is an implementation-specific method that attempts to kick
// off a `flush` event as quickly as possible. `flush` will attempt to exhaust
// the event queue before yielding to the browser's own event loop.
var requestFlush;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory exhaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
// `requestFlush` is implemented using a strategy based on data collected from
// every available SauceLabs Selenium web driver worker at time of writing.
// https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593
// Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that
// have WebKitMutationObserver but not un-prefixed MutationObserver.
// Must use `global` instead of `window` to work in both frames and web
// workers. `global` is a provision of Browserify, Mr, Mrs, or Mop.
var BrowserMutationObserver = global.MutationObserver || global.WebKitMutationObserver;
// MutationObservers are desirable because they have high priority and work
// reliably everywhere they are implemented.
// They are implemented in all modern browsers.
//
// - Android 4-4.3
// - Chrome 26-34
// - Firefox 14-29
// - Internet Explorer 11
// - iPad Safari 6-7.1
// - iPhone Safari 7-7.1
// - Safari 6-7
if (typeof BrowserMutationObserver === "function") {
requestFlush = makeRequestCallFromMutationObserver(flush);
// MessageChannels are desirable because they give direct access to the HTML
// task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera
// 11-12, and in web workers in many engines.
// Although message channels yield to any queued rendering and IO tasks, they
// would be better than imposing the 4ms delay of timers.
// However, they do not work reliably in Internet Explorer or Safari.
// Internet Explorer 10 is the only browser that has setImmediate but does
// not have MutationObservers.
// Although setImmediate yields to the browser's renderer, it would be
// preferrable to falling back to setTimeout since it does not have
// the minimum 4ms penalty.
// Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and
// Desktop to a lesser extent) that renders both setImmediate and
// MessageChannel useless for the purposes of ASAP.
// https://github.com/kriskowal/q/issues/396
// Timers are implemented universally.
// We fall back to timers in workers in most engines, and in foreground
// contexts in the following browsers.
// However, note that even this simple case requires nuances to operate in a
// broad spectrum of browsers.
//
// - Firefox 3-13
// - Internet Explorer 6-9
// - iPad Safari 4.3
// - Lynx 2.8.7
} else {
requestFlush = makeRequestCallFromTimer(flush);
}
// `requestFlush` requests that the high priority event queue be flushed as
// soon as possible.
// This is useful to prevent an error thrown in a task from stalling the event
// queue if the exception handled by Node.js’s
// `process.on("uncaughtException")` or by a domain.
rawAsap.requestFlush = requestFlush;
// To request a high priority event, we induce a mutation observer by toggling
// the text of a text node between "1" and "-1".
function makeRequestCallFromMutationObserver(callback) {
var toggle = 1;
var observer = new BrowserMutationObserver(callback);
var node = document.createTextNode("");
observer.observe(node, {characterData: true});
return function requestCall() {
toggle = -toggle;
node.data = toggle;
};
}
// The message channel technique was discovered by Malte Ubl and was the
// original foundation for this library.
// http://www.nonblocking.io/2011/06/windownexttick.html
// Safari 6.0.5 (at least) intermittently fails to create message ports on a
// page's first load. Thankfully, this version of Safari supports
// MutationObservers, so we don't need to fall back in that case.
// function makeRequestCallFromMessageChannel(callback) {
// var channel = new MessageChannel();
// channel.port1.onmessage = callback;
// return function requestCall() {
// channel.port2.postMessage(0);
// };
// }
// For reasons explained above, we are also unable to use `setImmediate`
// under any circumstances.
// Even if we were, there is another bug in Internet Explorer 10.
// It is not sufficient to assign `setImmediate` to `requestFlush` because
// `setImmediate` must be called *by name* and therefore must be wrapped in a
// closure.
// Never forget.
// function makeRequestCallFromSetImmediate(callback) {
// return function requestCall() {
// setImmediate(callback);
// };
// }
// Safari 6.0 has a problem where timers will get lost while the user is
// scrolling. This problem does not impact ASAP because Safari 6.0 supports
// mutation observers, so that implementation is used instead.
// However, if we ever elect to use timers in Safari, the prevalent work-around
// is to add a scroll event listener that calls for a flush.
// `setTimeout` does not call the passed callback if the delay is less than
// approximately 7 in web workers in Firefox 8 through 18, and sometimes not
// even then.
function makeRequestCallFromTimer(callback) {
return function requestCall() {
// We dispatch a timeout with a specified delay of 0 for engines that
// can reliably accommodate that request. This will usually be snapped
// to a 4 milisecond delay, but once we're flushing, there's no delay
// between events.
var timeoutHandle = setTimeout(handleTimer, 0);
// However, since this timer gets frequently dropped in Firefox
// workers, we enlist an interval handle that will try to fire
// an event 20 times per second until it succeeds.
var intervalHandle = setInterval(handleTimer, 50);
function handleTimer() {
// Whichever timer succeeds will cancel both timers and
// execute the callback.
clearTimeout(timeoutHandle);
clearInterval(intervalHandle);
callback();
}
};
}
// This is for `asap.js` only.
// Its name will be periodically randomized to break any code that depends on
// its existence.
rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer;
// ASAP was originally a nextTick shim included in Q. This was factored out
// into this ASAP package. It was later adapted to RSVP which made further
// amendments. These decisions, particularly to marginalize MessageChannel and
// to capture the MutationObserver implementation in a closure, were integrated
// back into ASAP proper.
// https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],136:[function(require,module,exports){
(function (process){
"use strict";
var domain; // The domain module is executed on demand
var hasSetImmediate = typeof setImmediate === "function";
// Use the fastest means possible to execute a task in its own turn, with
// priority over other events including network IO events in Node.js.
//
// An exception thrown by a task will permanently interrupt the processing of
// subsequent tasks. The higher level `asap` function ensures that if an
// exception is thrown by a task, that the task queue will continue flushing as
// soon as possible, but if you use `rawAsap` directly, you are responsible to
// either ensure that no exceptions are thrown from your task, or to manually
// call `rawAsap.requestFlush` if an exception is thrown.
module.exports = rawAsap;
function rawAsap(task) {
if (!queue.length) {
requestFlush();
flushing = true;
}
// Avoids a function call
queue[queue.length] = task;
}
var queue = [];
// Once a flush has been requested, no further calls to `requestFlush` are
// necessary until the next `flush` completes.
var flushing = false;
// The position of the next task to execute in the task queue. This is
// preserved between calls to `flush` so that it can be resumed if
// a task throws an exception.
var index = 0;
// If a task schedules additional tasks recursively, the task queue can grow
// unbounded. To prevent memory excaustion, the task queue will periodically
// truncate already-completed tasks.
var capacity = 1024;
// The flush function processes all tasks that have been scheduled with
// `rawAsap` unless and until one of those tasks throws an exception.
// If a task throws an exception, `flush` ensures that its state will remain
// consistent and will resume where it left off when called again.
// However, `flush` does not make any arrangements to be called again if an
// exception is thrown.
function flush() {
while (index < queue.length) {
var currentIndex = index;
// Advance the index before calling the task. This ensures that we will
// begin flushing on the next task the task throws an error.
index = index + 1;
queue[currentIndex].call();
// Prevent leaking memory for long chains of recursive calls to `asap`.
// If we call `asap` within tasks scheduled by `asap`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
queue.length = 0;
index = 0;
flushing = false;
}
rawAsap.requestFlush = requestFlush;
function requestFlush() {
// Ensure flushing is not bound to any domain.
// It is not sufficient to exit the domain, because domains exist on a stack.
// To execute code outside of any domain, the following dance is necessary.
var parentDomain = process.domain;
if (parentDomain) {
if (!domain) {
// Lazy execute the domain module.
// Only employed if the user elects to use domains.
domain = require(137);
}
domain.active = process.domain = null;
}
// `setImmediate` is slower that `process.nextTick`, but `process.nextTick`
// cannot handle recursion.
// `requestFlush` will only be called recursively from `asap.js`, to resume
// flushing after an error is thrown into a domain.
// Conveniently, `setImmediate` was introduced in the same version
// `process.nextTick` started throwing recursion errors.
if (flushing && hasSetImmediate) {
setImmediate(flush);
} else {
process.nextTick(flush);
}
if (parentDomain) {
domain.active = process.domain = parentDomain;
}
}
}).call(this,require(139))
},{"137":137,"139":139}],137:[function(require,module,exports){
/*global define:false require:false */
module.exports = (function(){
// Import Events
var events = require(138)
// Export Domain
var domain = {}
domain.createDomain = domain.create = function(){
var d = new events.EventEmitter()
function emitError(e) {
d.emit('error', e)
}
d.add = function(emitter){
emitter.on('error', emitError)
}
d.remove = function(emitter){
emitter.removeListener('error', emitError)
}
d.bind = function(fn){
return function(){
var args = Array.prototype.slice.call(arguments)
try {
fn.apply(null, args)
}
catch (err){
emitError(err)
}
}
}
d.intercept = function(fn){
return function(err){
if ( err ) {
emitError(err)
}
else {
var args = Array.prototype.slice.call(arguments, 1)
try {
fn.apply(null, args)
}
catch (err){
emitError(err)
}
}
}
}
d.run = function(fn){
try {
fn()
}
catch (err) {
emitError(err)
}
return this
};
d.dispose = function(){
this.removeAllListeners()
return this
};
d.enter = d.exit = function(){
return this
}
return d
};
return domain
}).call(this)
},{"138":138}],138:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
handler.apply(this, args);
}
} else if (isObject(handler)) {
len = arguments.length;
args = new Array(len - 1);
for (i = 1; i < len; i++)
args[i - 1] = arguments[i];
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
var m;
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.listenerCount = function(emitter, type) {
var ret;
if (!emitter._events || !emitter._events[type])
ret = 0;
else if (isFunction(emitter._events[type]))
ret = 1;
else
ret = emitter._events[type].length;
return ret;
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],139:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
currentQueue[queueIndex].run();
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],140:[function(require,module,exports){
'use strict';
var request = require(144);
var buildQueryObject = require(141);
var isArray = Array.isArray;
function simpleExtend(obj, obj2) {
var prop;
for (prop in obj2) {
obj[prop] = obj2[prop];
}
return obj;
}
function XMLHttpSource(jsongUrl, config) {
this._jsongUrl = jsongUrl;
if (typeof config === 'number') {
var newConfig = {
timeout: config
};
config = newConfig;
}
this._config = simpleExtend({
timeout: 15000,
headers: {}
}, config || {});
}
XMLHttpSource.prototype = {
// because javascript
constructor: XMLHttpSource,
/**
* buildQueryObject helper
*/
buildQueryObject: buildQueryObject,
/**
* @inheritDoc DataSource#get
*/
get: function httpSourceGet(pathSet) {
var method = 'GET';
var queryObject = this.buildQueryObject(this._jsongUrl, method, {
paths: pathSet,
method: 'get'
});
var config = simpleExtend(queryObject, this._config);
// pass context for onBeforeRequest callback
var context = this;
return request(method, config, context);
},
/**
* @inheritDoc DataSource#set
*/
set: function httpSourceSet(jsongEnv) {
var method = 'POST';
var queryObject = this.buildQueryObject(this._jsongUrl, method, {
jsonGraph: jsongEnv,
method: 'set'
});
var config = simpleExtend(queryObject, this._config);
config.headers["Content-Type"] = "application/x-www-form-urlencoded";
// pass context for onBeforeRequest callback
var context = this;
return request(method, config, context);
},
/**
* @inheritDoc DataSource#call
*/
call: function httpSourceCall(callPath, args, pathSuffix, paths) {
// arguments defaults
args = args || [];
pathSuffix = pathSuffix || [];
paths = paths || [];
var method = 'POST';
var queryData = [];
queryData.push('method=call');
queryData.push('callPath=' + encodeURIComponent(JSON.stringify(callPath)));
queryData.push('arguments=' + encodeURIComponent(JSON.stringify(args)));
queryData.push('pathSuffixes=' + encodeURIComponent(JSON.stringify(pathSuffix)));
queryData.push('paths=' + encodeURIComponent(JSON.stringify(paths)));
var queryObject = this.buildQueryObject(this._jsongUrl, method, queryData.join('&'));
var config = simpleExtend(queryObject, this._config);
config.headers["Content-Type"] = "application/x-www-form-urlencoded";
// pass context for onBeforeRequest callback
var context = this;
return request(method, config, context);
}
};
// ES6 modules
XMLHttpSource.XMLHttpSource = XMLHttpSource;
XMLHttpSource['default'] = XMLHttpSource;
// commonjs
module.exports = XMLHttpSource;
},{"141":141,"144":144}],141:[function(require,module,exports){
'use strict';
module.exports = function buildQueryObject(url, method, queryData) {
var qData = [];
var keys;
var data = {url: url};
var isQueryParamUrl = url.indexOf('?') !== -1;
var startUrl = (isQueryParamUrl) ? '&' : '?';
if (typeof queryData === 'string') {
qData.push(queryData);
} else {
keys = Object.keys(queryData);
keys.forEach(function (k) {
var value = (typeof queryData[k] === 'object') ? JSON.stringify(queryData[k]) : queryData[k];
qData.push(k + '=' + value);
});
}
if (method === 'GET') {
data.url += startUrl + qData.join('&');
} else {
data.data = qData.join('&');
}
return data;
};
},{}],142:[function(require,module,exports){
(function (global){
'use strict';
// Get CORS support even for older IE
module.exports = function getCORSRequest() {
var xhr = new global.XMLHttpRequest();
if ('withCredentials' in xhr) {
return xhr;
} else if (!!global.XDomainRequest) {
return new XDomainRequest();
} else {
throw new Error('CORS is not supported by your browser');
}
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],143:[function(require,module,exports){
(function (global){
'use strict';
module.exports = function getXMLHttpRequest() {
var progId,
progIds,
i;
if (global.XMLHttpRequest) {
return new global.XMLHttpRequest();
} else {
try {
progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
for (i = 0; i < 3; i++) {
try {
progId = progIds[i];
if (new global.ActiveXObject(progId)) {
break;
}
} catch(e) { }
}
return new global.ActiveXObject(progId);
} catch (e) {
throw new Error('XMLHttpRequest is not supported by your browser');
}
}
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],144:[function(require,module,exports){
'use strict';
var getXMLHttpRequest = require(143);
var getCORSRequest = require(142);
var hasOwnProp = Object.prototype.hasOwnProperty;
function Observable() {}
Observable.create = function(subscribe) {
var o = new Observable();
o.subscribe = function(observer) {
var s = subscribe(observer);
if (typeof s === 'function') {
return {
dispose: s
};
}
else {
return s;
}
}
return o;
}
function request(method, options, context) {
return Observable.create(function requestObserver(observer) {
var config = {
method: method || 'GET',
crossDomain: false,
async: true,
headers: {},
responseType: 'json'
};
var xhr,
isDone,
headers,
header,
prop;
for (prop in options) {
if (hasOwnProp.call(options, prop)) {
config[prop] = options[prop];
}
}
// Add request with Headers
if (!config.crossDomain && !config.headers['X-Requested-With']) {
config.headers['X-Requested-With'] = 'XMLHttpRequest';
}
// allow the user to mutate the config open
if (context.onBeforeRequest != null) {
context.onBeforeRequest(config);
}
// create xhr
try {
xhr = config.crossDomain ? getCORSRequest() : getXMLHttpRequest();
} catch (err) {
observer.onError(err);
}
try {
// Takes the url and opens the connection
if (config.user) {
xhr.open(config.method, config.url, config.async, config.user, config.password);
} else {
xhr.open(config.method, config.url, config.async);
}
// Sets timeout information
xhr.timeout = config.timeout;
// Anything but explicit false results in true.
xhr.withCredentials = config.withCredentials !== false;
// Fills the request headers
headers = config.headers;
for (header in headers) {
if (hasOwnProp.call(headers, header)) {
xhr.setRequestHeader(header, headers[header]);
}
}
if (config.responseType) {
try {
xhr.responseType = config.responseType;
} catch (e) {
// WebKit added support for the json responseType value on 09/03/2013
// https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
// known to throw when setting the value "json" as the response type. Other older
// browsers implementing the responseType
//
// The json response type can be ignored if not supported, because JSON payloads are
// parsed on the client-side regardless.
if (responseType !== 'json') {
throw e;
}
}
}
xhr.onreadystatechange = function onreadystatechange(e) {
// Complete
if (xhr.readyState === 4) {
if (!isDone) {
isDone = true;
onXhrLoad(observer, xhr, e);
}
}
};
// Timeout
xhr.ontimeout = function ontimeout(e) {
if (!isDone) {
isDone = true;
onXhrError(observer, xhr, 'timeout error', e);
}
};
// Send Request
xhr.send(config.data);
} catch (e) {
observer.onError(e);
}
// Dispose
return function dispose() {
// Doesn't work in IE9
if (!isDone && xhr.readyState !== 4) {
isDone = true;
xhr.abort();
}
};//Dispose
});
}
/*
* General handling of ultimate failure (after appropriate retries)
*/
function _handleXhrError(observer, textStatus, errorThrown) {
// IE9: cross-domain request may be considered errors
if (!errorThrown) {
errorThrown = new Error(textStatus);
}
observer.onError(errorThrown);
}
function onXhrLoad(observer, xhr, e) {
var responseData,
responseObject,
responseType;
// If there's no observer, the request has been (or is being) cancelled.
if (xhr && observer) {
responseType = xhr.responseType;
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
responseData = ('response' in xhr) ? xhr.response : xhr.responseText;
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
var status = (xhr.status === 1223) ? 204 : xhr.status;
if (status >= 200 && status <= 399) {
try {
if (responseType !== 'json') {
responseData = JSON.parse(responseData || '');
}
if (typeof responseData === 'string') {
responseData = JSON.parse(responseData || '');
}
} catch (e) {
_handleXhrError(observer, 'invalid json', e);
}
observer.onNext(responseData);
observer.onCompleted();
return;
} else if (status === 401 || status === 403 || status === 407) {
return _handleXhrError(observer, responseData);
} else if (status === 410) {
// TODO: Retry ?
return _handleXhrError(observer, responseData);
} else if (status === 408 || status === 504) {
// TODO: Retry ?
return _handleXhrError(observer, responseData);
} else {
return _handleXhrError(observer, responseData || ('Response code ' + status));
}//if
}//if
}//onXhrLoad
function onXhrError(observer, xhr, status, e) {
_handleXhrError(observer, status || xhr.statusText || 'request error', e);
}
module.exports = request;
},{"142":142,"143":143}],145:[function(require,module,exports){
var pathSyntax = require(149);
function sentinel(type, value, props) {
var copy = Object.create(null);
if (props != null) {
for(var key in props) {
copy[key] = props[key];
}
copy["$type"] = type;
copy.value = value;
return copy;
}
else {
return { $type: type, value: value };
}
}
module.exports = {
ref: function ref(path, props) {
return sentinel("ref", pathSyntax.fromPath(path), props);
},
atom: function atom(value, props) {
return sentinel("atom", value, props);
},
undefined: function() {
return sentinel("atom");
},
error: function error(errorValue, props) {
return sentinel("error", errorValue, props);
},
pathValue: function pathValue(path, value) {
return { path: pathSyntax.fromPath(path), value: value };
},
pathInvalidation: function pathInvalidation(path) {
return { path: pathSyntax.fromPath(path), invalidated: true };
}
};
},{"149":149}],146:[function(require,module,exports){
module.exports = {
integers: 'integers',
ranges: 'ranges',
keys: 'keys'
};
},{}],147:[function(require,module,exports){
var TokenTypes = {
token: 'token',
dotSeparator: '.',
commaSeparator: ',',
openingBracket: '[',
closingBracket: ']',
openingBrace: '{',
closingBrace: '}',
escape: '\\',
space: ' ',
colon: ':',
quote: 'quote',
unknown: 'unknown'
};
module.exports = TokenTypes;
},{}],148:[function(require,module,exports){
module.exports = {
indexer: {
nested: 'Indexers cannot be nested.',
needQuotes: 'unquoted indexers must be numeric.',
empty: 'cannot have empty indexers.',
leadingDot: 'Indexers cannot have leading dots.',
leadingComma: 'Indexers cannot have leading comma.',
requiresComma: 'Indexers require commas between indexer args.',
routedTokens: 'Only one token can be used per indexer when specifying routed tokens.'
},
range: {
precedingNaN: 'ranges must be preceded by numbers.',
suceedingNaN: 'ranges must be suceeded by numbers.'
},
routed: {
invalid: 'Invalid routed token. only integers|ranges|keys are supported.'
},
quote: {
empty: 'cannot have empty quoted keys.',
illegalEscape: 'Invalid escape character. Only quotes are escapable.'
},
unexpectedToken: 'Unexpected token.',
invalidIdentifier: 'Invalid Identifier.',
invalidPath: 'Please provide a valid path.',
throwError: function(err, tokenizer, token) {
if (token) {
throw err + ' -- ' + tokenizer.parseString + ' with next token: ' + token;
}
throw err + ' -- ' + tokenizer.parseString;
}
};
},{}],149:[function(require,module,exports){
var Tokenizer = require(155);
var head = require(150);
var RoutedTokens = require(146);
var parser = function parser(string, extendedRules) {
return head(new Tokenizer(string, extendedRules));
};
module.exports = parser;
// Constructs the paths from paths / pathValues that have strings.
// If it does not have a string, just moves the value into the return
// results.
parser.fromPathsOrPathValues = function(paths, ext) {
if (!paths) {
return [];
}
var out = [];
for (i = 0, len = paths.length; i < len; i++) {
// Is the path a string
if (typeof paths[i] === 'string') {
out[i] = parser(paths[i], ext);
}
// is the path a path value with a string value.
else if (typeof paths[i].path === 'string') {
out[i] = {
path: parser(paths[i].path, ext), value: paths[i].value
};
}
// just copy it over.
else {
out[i] = paths[i];
}
}
return out;
};
// If the argument is a string, this with convert, else just return
// the path provided.
parser.fromPath = function(path, ext) {
if (!path) {
return [];
}
if (typeof path === 'string') {
return parser(path, ext);
}
return path;
};
// Potential routed tokens.
parser.RoutedTokens = RoutedTokens;
},{"146":146,"150":150,"155":155}],150:[function(require,module,exports){
var TokenTypes = require(147);
var E = require(148);
var indexer = require(151);
/**
* The top level of the parse tree. This returns the generated path
* from the tokenizer.
*/
module.exports = function head(tokenizer) {
var token = tokenizer.next();
var state = {};
var out = [];
while (!token.done) {
switch (token.type) {
case TokenTypes.token:
var first = +token.token[0];
if (!isNaN(first)) {
E.throwError(E.invalidIdentifier, tokenizer);
}
out[out.length] = token.token;
break;
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (out.length === 0) {
E.throwError(E.unexpectedToken, tokenizer);
}
break;
// Spaces do nothing.
case TokenTypes.space:
// NOTE: Spaces at the top level are allowed.
// titlesById .summary is a valid path.
break;
// Its time to decend the parse tree.
case TokenTypes.openingBracket:
indexer(tokenizer, token, state, out);
break;
default:
E.throwError(E.unexpectedToken, tokenizer);
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (out.length === 0) {
E.throwError(E.invalidPath, tokenizer);
}
return out;
};
},{"147":147,"148":148,"151":151}],151:[function(require,module,exports){
var TokenTypes = require(147);
var E = require(148);
var idxE = E.indexer;
var range = require(153);
var quote = require(152);
var routed = require(154);
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function indexer(tokenizer, openingToken, state, out) {
var token = tokenizer.next();
var done = false;
var allowedMaxLength = 1;
var routedIndexer = false;
// State variables
state.indexer = [];
while (!token.done) {
switch (token.type) {
case TokenTypes.token:
case TokenTypes.quote:
// ensures that token adders are properly delimited.
if (state.indexer.length === allowedMaxLength) {
E.throwError(idxE.requiresComma, tokenizer);
}
break;
}
switch (token.type) {
// Extended syntax case
case TokenTypes.openingBrace:
routedIndexer = true;
routed(tokenizer, token, state, out);
break;
case TokenTypes.token:
var t = +token.token;
if (isNaN(t)) {
E.throwError(idxE.needQuotes, tokenizer);
}
state.indexer[state.indexer.length] = t;
break;
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (!state.indexer.length) {
E.throwError(idxE.leadingDot, tokenizer);
}
range(tokenizer, token, state, out);
break;
// Spaces do nothing.
case TokenTypes.space:
break;
case TokenTypes.closingBracket:
done = true;
break;
// The quotes require their own tree due to what can be in it.
case TokenTypes.quote:
quote(tokenizer, token, state, out);
break;
// Its time to decend the parse tree.
case TokenTypes.openingBracket:
E.throwError(idxE.nested, tokenizer);
break;
case TokenTypes.commaSeparator:
++allowedMaxLength;
break;
default:
E.throwError(E.unexpectedToken, tokenizer);
break;
}
// If done, leave loop
if (done) {
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (state.indexer.length === 0) {
E.throwError(idxE.empty, tokenizer);
}
if (state.indexer.length > 1 && routedIndexer) {
E.throwError(idxE.routedTokens, tokenizer);
}
// Remember, if an array of 1, keySets will be generated.
if (state.indexer.length === 1) {
state.indexer = state.indexer[0];
}
out[out.length] = state.indexer;
// Clean state.
state.indexer = undefined;
};
},{"147":147,"148":148,"152":152,"153":153,"154":154}],152:[function(require,module,exports){
var TokenTypes = require(147);
var E = require(148);
var quoteE = E.quote;
/**
* quote is all the parse tree in between quotes. This includes the only
* escaping logic.
*
* parse-tree:
* <opening-quote>(.|(<escape><opening-quote>))*<opening-quote>
*/
module.exports = function quote(tokenizer, openingToken, state, out) {
var token = tokenizer.next();
var innerToken = '';
var openingQuote = openingToken.token;
var escaping = false;
var done = false;
while (!token.done) {
switch (token.type) {
case TokenTypes.token:
case TokenTypes.space:
case TokenTypes.dotSeparator:
case TokenTypes.commaSeparator:
case TokenTypes.openingBracket:
case TokenTypes.closingBracket:
case TokenTypes.openingBrace:
case TokenTypes.closingBrace:
if (escaping) {
E.throwError(quoteE.illegalEscape, tokenizer);
}
innerToken += token.token;
break;
case TokenTypes.quote:
// the simple case. We are escaping
if (escaping) {
innerToken += token.token;
escaping = false;
}
// its not a quote that is the opening quote
else if (token.token !== openingQuote) {
innerToken += token.token;
}
// last thing left. Its a quote that is the opening quote
// therefore we must produce the inner token of the indexer.
else {
done = true;
}
break;
case TokenTypes.escape:
escaping = true;
break;
default:
E.throwError(E.unexpectedToken, tokenizer);
}
// If done, leave loop
if (done) {
break;
}
// Keep cycling through the tokenizer.
token = tokenizer.next();
}
if (innerToken.length === 0) {
E.throwError(quoteE.empty, tokenizer);
}
state.indexer[state.indexer.length] = innerToken;
};
},{"147":147,"148":148}],153:[function(require,module,exports){
var Tokenizer = require(155);
var TokenTypes = require(147);
var E = require(148);
/**
* The indexer is all the logic that happens in between
* the '[', opening bracket, and ']' closing bracket.
*/
module.exports = function range(tokenizer, openingToken, state, out) {
var token = tokenizer.peek();
var dotCount = 1;
var done = false;
var inclusive = true;
// Grab the last token off the stack. Must be an integer.
var idx = state.indexer.length - 1;
var from = Tokenizer.toNumber(state.indexer[idx]);
var to;
if (isNaN(from)) {
E.throwError(E.range.precedingNaN, tokenizer);
}
// Why is number checking so difficult in javascript.
while (!done && !token.done) {
switch (token.type) {
// dotSeparators at the top level have no meaning
case TokenTypes.dotSeparator:
if (dotCount === 3) {
E.throwError(E.unexpectedToken, tokenizer);
}
++dotCount;
if (dotCount === 3) {
inclusive = false;
}
break;
case TokenTypes.token:
// move the tokenizer forward and save to.
to = Tokenizer.toNumber(tokenizer.next().token);
// throw potential error.
if (isNaN(to)) {
E.throwError(E.range.suceedingNaN, tokenizer);
}
done = true;
break;
default:
done = true;
break;
}
// Keep cycling through the tokenizer. But ranges have to peek
// before they go to the next token since there is no 'terminating'
// character.
if (!done) {
tokenizer.next();
// go to the next token without consuming.
token = tokenizer.peek();
}
// break and remove state information.
else {
break;
}
}
state.indexer[idx] = {from: from, to: inclusive ? to : to - 1};
};
},{"147":147,"148":148,"155":155}],154:[function(require,module,exports){
var TokenTypes = require(147);
var RoutedTokens = require(146);
var E = require(148);
var routedE = E.routed;
/**
* The routing logic.
*
* parse-tree:
* <opening-brace><routed-token>(:<token>)<closing-brace>
*/
module.exports = function routed(tokenizer, openingToken, state, out) {
var routeToken = tokenizer.next();
var named = false;
var name = '';
// ensure the routed token is a valid ident.
switch (routeToken.token) {
case RoutedTokens.integers:
case RoutedTokens.ranges:
case RoutedTokens.keys:
//valid
break;
default:
E.throwError(routedE.invalid, tokenizer);
break;
}
// Now its time for colon or ending brace.
var next = tokenizer.next();
// we are parsing a named identifier.
if (next.type === TokenTypes.colon) {
named = true;
// Get the token name.
next = tokenizer.next();
if (next.type !== TokenTypes.token) {
E.throwError(routedE.invalid, tokenizer);
}
name = next.token;
// move to the closing brace.
next = tokenizer.next();
}
// must close with a brace.
if (next.type === TokenTypes.closingBrace) {
var outputToken = {
type: routeToken.token,
named: named,
name: name
};
state.indexer[state.indexer.length] = outputToken;
}
// closing brace expected
else {
E.throwError(routedE.invalid, tokenizer);
}
};
},{"146":146,"147":147,"148":148}],155:[function(require,module,exports){
var TokenTypes = require(147);
var DOT_SEPARATOR = '.';
var COMMA_SEPARATOR = ',';
var OPENING_BRACKET = '[';
var CLOSING_BRACKET = ']';
var OPENING_BRACE = '{';
var CLOSING_BRACE = '}';
var COLON = ':';
var ESCAPE = '\\';
var DOUBLE_OUOTES = '"';
var SINGE_OUOTES = "'";
var SPACE = " ";
var SPECIAL_CHARACTERS = '\\\'"[]., ';
var EXT_SPECIAL_CHARACTERS = '\\{}\'"[]., :';
var Tokenizer = module.exports = function(string, ext) {
this._string = string;
this._idx = -1;
this._extended = ext;
this.parseString = '';
};
Tokenizer.prototype = {
/**
* grabs the next token either from the peek operation or generates the
* next token.
*/
next: function() {
var nextToken = this._nextToken ?
this._nextToken : getNext(this._string, this._idx, this._extended);
this._idx = nextToken.idx;
this._nextToken = false;
this.parseString += nextToken.token.token;
return nextToken.token;
},
/**
* will peak but not increment the tokenizer
*/
peek: function() {
var nextToken = this._nextToken ?
this._nextToken : getNext(this._string, this._idx, this._extended);
this._nextToken = nextToken;
return nextToken.token;
}
};
Tokenizer.toNumber = function toNumber(x) {
if (!isNaN(+x)) {
return +x;
}
return NaN;
};
function toOutput(token, type, done) {
return {
token: token,
done: done,
type: type
};
}
function getNext(string, idx, ext) {
var output = false;
var token = '';
var specialChars = ext ?
EXT_SPECIAL_CHARACTERS : SPECIAL_CHARACTERS;
do {
done = idx + 1 >= string.length;
if (done) {
break;
}
// we have to peek at the next token
var character = string[idx + 1];
if (character !== undefined &&
specialChars.indexOf(character) === -1) {
token += character;
++idx;
continue;
}
// The token to delimiting character transition.
else if (token.length) {
break;
}
++idx;
var type;
switch (character) {
case DOT_SEPARATOR:
type = TokenTypes.dotSeparator;
break;
case COMMA_SEPARATOR:
type = TokenTypes.commaSeparator;
break;
case OPENING_BRACKET:
type = TokenTypes.openingBracket;
break;
case CLOSING_BRACKET:
type = TokenTypes.closingBracket;
break;
case OPENING_BRACE:
type = TokenTypes.openingBrace;
break;
case CLOSING_BRACE:
type = TokenTypes.closingBrace;
break;
case SPACE:
type = TokenTypes.space;
break;
case DOUBLE_OUOTES:
case SINGE_OUOTES:
type = TokenTypes.quote;
break;
case ESCAPE:
type = TokenTypes.escape;
break;
case COLON:
type = TokenTypes.colon;
break;
default:
type = TokenTypes.unknown;
break;
}
output = toOutput(character, type, false);
break;
} while (!done);
if (!output && token.length) {
output = toOutput(token, TokenTypes.token, false);
}
if (!output) {
output = {done: true};
}
return {
token: output,
idx: idx
};
}
},{"147":147}],156:[function(require,module,exports){
var toPaths = require(159);
var toTree = require(160);
module.exports = function collapse(paths) {
var collapseMap = paths.
reduce(function(acc, path) {
var len = path.length;
if (!acc[len]) {
acc[len] = [];
}
acc[len].push(path);
return acc;
}, {});
Object.
keys(collapseMap).
forEach(function(collapseKey) {
collapseMap[collapseKey] = toTree(collapseMap[collapseKey]);
});
return toPaths(collapseMap);
};
},{"159":159,"160":160}],157:[function(require,module,exports){
module.exports = {
iterateKeySet: require(158),
toTree: require(160),
toTreeWithUnion: require(161),
toPaths: require(159),
collapse: require(156)
};
},{"156":156,"158":158,"159":159,"160":160,"161":161}],158:[function(require,module,exports){
var isArray = Array.isArray;
/**
* Takes in a keySet and a note attempts to iterate over it.
* If the value is a primitive, the key will be returned and the note will
* be marked done
* If the value is an object, then each value of the range will be returned
* and when finished the note will be marked done.
* If the value is an array, each value will be iterated over, if any of the
* inner values are ranges, those will be iterated over. When fully done,
* the note will be marked done.
*
* @param {Object|Array|String|Number} keySet -
* @param {Object} note - The non filled note
* @returns {String|Number|undefined} - The current iteration value.
* If undefined, then the keySet is empty
* @public
*/
module.exports = function iterateKeySet(keySet, note) {
if (note.isArray === undefined) {
initializeNote(keySet, note);
}
// Array iteration
if (note.isArray) {
var nextValue;
// Cycle through the array and pluck out the next value.
do {
if (note.loaded && note.rangeOffset > note.to) {
++note.arrayOffset;
note.loaded = false;
}
var idx = note.arrayOffset, length = keySet.length;
if (idx >= length) {
note.done = true;
break;
}
var el = keySet[note.arrayOffset];
var type = typeof el;
// Inner range iteration.
if (type === 'object') {
if (!note.loaded) {
initializeRange(el, note);
}
// Empty to/from
if (note.empty) {
continue;
}
nextValue = note.rangeOffset++;
}
// Primitive iteration in array.
else {
++note.arrayOffset;
nextValue = el;
}
} while (nextValue === undefined);
return nextValue;
}
// Range iteration
else if (note.isObject) {
if (!note.loaded) {
initializeRange(keySet, note);
}
if (note.rangeOffset > note.to) {
note.done = true;
return undefined;
}
return note.rangeOffset++;
}
// Primitive value
else {
note.done = true;
return keySet;
}
};
function initializeRange(key, memo) {
var from = memo.from = key.from || 0;
var to = memo.to = key.to ||
(typeof key.length === 'number' &&
memo.from + key.length - 1 || 0);
memo.rangeOffset = memo.from;
memo.loaded = true;
if (from > to) {
memo.empty = true;
}
}
function initializeNote(key, note) {
note.done = false;
var isObject = note.isObject = !!(key && typeof key === 'object');
note.isArray = isObject && isArray(key);
note.arrayOffset = 0;
}
},{}],159:[function(require,module,exports){
var isArray = Array.isArray;
var typeOfObject = "object";
/* jshint forin: false */
module.exports = function toPaths(lengths) {
var pathmap;
var allPaths = [];
var allPathsLength = 0;
for (var length in lengths) {
if (isNumber(length) && isObject(pathmap = lengths[length])) {
var paths = collapsePathMap(pathmap, 0, parseInt(length, 10)).sets;
var pathsIndex = -1;
var pathsCount = paths.length;
while (++pathsIndex < pathsCount) {
allPaths[allPathsLength++] = collapsePathSetIndexes(paths[pathsIndex]);
}
}
}
return allPaths;
};
function isObject(value) {
return value !== null && typeof value === typeOfObject;
}
function collapsePathMap(pathmap, depth, length) {
var key;
var code = getHashCode(String(depth));
var subs = Object.create(null);
var codes = [];
var codesIndex = -1;
var codesCount = 0;
var pathsets = [];
var pathsetsCount = 0;
var subPath, subCode,
subKeys, subKeysIndex, subKeysCount,
subSets, subSetsIndex, subSetsCount,
pathset, pathsetIndex, pathsetCount,
firstSubKey, pathsetClone;
subKeys = [];
subKeysIndex = -1;
if (depth < length - 1) {
subKeysCount = getSortedKeys(pathmap, subKeys);
while (++subKeysIndex < subKeysCount) {
key = subKeys[subKeysIndex];
subPath = collapsePathMap(pathmap[key], depth + 1, length);
subCode = subPath.code;
if(subs[subCode]) {
subPath = subs[subCode];
} else {
codes[codesCount++] = subCode;
subPath = subs[subCode] = {
keys: [],
sets: subPath.sets
};
}
code = getHashCode(code + key + subCode);
isNumber(key) &&
subPath.keys.push(parseInt(key, 10)) ||
subPath.keys.push(key);
}
while(++codesIndex < codesCount) {
key = codes[codesIndex];
subPath = subs[key];
subKeys = subPath.keys;
subKeysCount = subKeys.length;
if (subKeysCount > 0) {
subSets = subPath.sets;
subSetsIndex = -1;
subSetsCount = subSets.length;
firstSubKey = subKeys[0];
while (++subSetsIndex < subSetsCount) {
pathset = subSets[subSetsIndex];
pathsetIndex = -1;
pathsetCount = pathset.length;
pathsetClone = new Array(pathsetCount + 1);
pathsetClone[0] = subKeysCount > 1 && subKeys || firstSubKey;
while (++pathsetIndex < pathsetCount) {
pathsetClone[pathsetIndex + 1] = pathset[pathsetIndex];
}
pathsets[pathsetsCount++] = pathsetClone;
}
}
}
} else {
subKeysCount = getSortedKeys(pathmap, subKeys);
if (subKeysCount > 1) {
pathsets[pathsetsCount++] = [subKeys];
} else {
pathsets[pathsetsCount++] = subKeys;
}
while (++subKeysIndex < subKeysCount) {
code = getHashCode(code + subKeys[subKeysIndex]);
}
}
return {
code: code,
sets: pathsets
};
}
function collapsePathSetIndexes(pathset) {
var keysetIndex = -1;
var keysetCount = pathset.length;
while (++keysetIndex < keysetCount) {
var keyset = pathset[keysetIndex];
if (isArray(keyset)) {
pathset[keysetIndex] = collapseIndex(keyset);
}
}
return pathset;
}
/**
* Collapse range indexers, e.g. when there is a continuous
* range in an array, turn it into an object instead:
*
* [1,2,3,4,5,6] => {"from":1, "to":6}
*
* @private
*/
function collapseIndex(keyset) {
// Do we need to dedupe an indexer keyset if they're duplicate consecutive integers?
// var hash = {};
var keyIndex = -1;
var keyCount = keyset.length - 1;
var isSparseRange = keyCount > 0;
while (++keyIndex <= keyCount) {
var key = keyset[keyIndex];
if (!isNumber(key) /* || hash[key] === true*/ ) {
isSparseRange = false;
break;
}
// hash[key] = true;
// Cast number indexes to integers.
keyset[keyIndex] = parseInt(key, 10);
}
if (isSparseRange === true) {
keyset.sort(sortListAscending);
var from = keyset[0];
var to = keyset[keyCount];
// If we re-introduce deduped integer indexers, change this comparson to "===".
if (to - from <= keyCount) {
return {
from: from,
to: to
};
}
}
return keyset;
}
function sortListAscending(a, b) {
return a - b;
}
/* jshint forin: false */
function getSortedKeys(map, keys, sort) {
var len = 0;
for (var key in map) {
keys[len++] = key;
}
if (len > 1) {
keys.sort(sort);
}
return len;
}
function getHashCode(key) {
var code = 5381;
var index = -1;
var count = key.length;
while (++index < count) {
code = (code << 5) + code + key.charCodeAt(index);
}
return String(code);
}
/**
* Return true if argument is a number or can be cast to a number
* @private
*/
function isNumber(val) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
// adding 1 corrects loss of precision from parseFloat (#15100)
return !isArray(val) && (val - parseFloat(val) + 1) >= 0;
}
},{}],160:[function(require,module,exports){
var iterateKeySet = require(158);
var isArray = Array.isArray;
/**
* @param {Array} paths -
* @returns {Object} -
*/
module.exports = function toTree(paths) {
return paths.reduce(function(acc, path) {
innerToTree(acc, path, 0);
return acc;
}, {});
};
function innerToTree(seed, path, depth) {
var keySet = path[depth];
var iteratorNote = {};
var key;
var nextDepth = depth + 1;
key = iterateKeySet(keySet, iteratorNote);
do {
var next = seed[key];
if (!next) {
if (nextDepth === path.length) {
seed[key] = null;
} else {
next = seed[key] = {};
}
}
if (nextDepth < path.length) {
innerToTree(next, path, nextDepth);
}
if (!iteratorNote.done) {
key = iterateKeySet(keySet, iteratorNote);
}
} while (!iteratorNote.done);
}
},{"158":158}],161:[function(require,module,exports){
},{}],162:[function(require,module,exports){
'use strict';
module.exports = require(167)
},{"167":167}],163:[function(require,module,exports){
'use strict';
var asap = require(136)
function noop() {};
// States:
//
// 0 - pending
// 1 - fulfilled with _value
// 2 - rejected with _value
// 3 - adopted the state of another promise, _value
//
// once the state is no longer pending (0) it is immutable
// All `_` prefixed properties will be reduced to `_{random number}`
// at build time to obfuscate them and discourage their use.
// We don't use symbols or Object.defineProperty to fully hide them
// because the performance isn't good enough.
// to avoid using try/catch inside critical functions, we
// extract them to here.
var LAST_ERROR = null;
var IS_ERROR = {};
function getThen(obj) {
try {
return obj.then;
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
function tryCallOne(fn, a) {
try {
return fn(a);
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
function tryCallTwo(fn, a, b) {
try {
fn(a, b);
} catch (ex) {
LAST_ERROR = ex;
return IS_ERROR;
}
}
module.exports = Promise;
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
this._71 = 0;
this._18 = null;
this._61 = [];
if (fn === noop) return;
doResolve(fn, this);
}
Promise.prototype._10 = function (onFulfilled, onRejected) {
var self = this;
return new this.constructor(function (resolve, reject) {
var res = new Promise(noop);
res.then(resolve, reject);
self._24(new Handler(onFulfilled, onRejected, res));
});
};
Promise.prototype.then = function(onFulfilled, onRejected) {
if (this.constructor !== Promise) return this._10(onFulfilled, onRejected);
var res = new Promise(noop);
this._24(new Handler(onFulfilled, onRejected, res));
return res;
};
Promise.prototype._24 = function(deferred) {
if (this._71 === 3) {
this._18._24(deferred);
return;
}
if (this._71 === 0) {
this._61.push(deferred);
return;
}
var state = this._71;
var value = this._18;
asap(function() {
var cb = state === 1 ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state === 1 ? deferred.promise._82(value) : deferred.promise._67(value))
return
}
var ret = tryCallOne(cb, value);
if (ret === IS_ERROR) {
deferred.promise._67(LAST_ERROR)
} else {
deferred.promise._82(ret)
}
});
};
Promise.prototype._82 = function(newValue) {
//Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === this) {
return this._67(new TypeError('A promise cannot be resolved with itself.'))
}
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = getThen(newValue);
if (then === IS_ERROR) {
return this._67(LAST_ERROR);
}
if (
then === this.then &&
newValue instanceof Promise &&
newValue._24 === this._24
) {
this._71 = 3;
this._18 = newValue;
for (var i = 0; i < this._61.length; i++) {
newValue._24(this._61[i]);
}
return;
} else if (typeof then === 'function') {
doResolve(then.bind(newValue), this)
return
}
}
this._71 = 1
this._18 = newValue
this._94()
}
Promise.prototype._67 = function (newValue) {
this._71 = 2
this._18 = newValue
this._94()
}
Promise.prototype._94 = function () {
for (var i = 0; i < this._61.length; i++)
this._24(this._61[i])
this._61 = null
}
function Handler(onFulfilled, onRejected, promise){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, promise) {
var done = false;
var res = tryCallTwo(fn, function (value) {
if (done) return
done = true
promise._82(value)
}, function (reason) {
if (done) return
done = true
promise._67(reason)
})
if (!done && res === IS_ERROR) {
done = true
promise._67(LAST_ERROR)
}
}
},{"136":136}],164:[function(require,module,exports){
'use strict';
var Promise = require(163)
module.exports = Promise
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
setTimeout(function () {
throw err
}, 0)
})
}
},{"163":163}],165:[function(require,module,exports){
'use strict';
//This file contains the ES6 extensions to the core Promises/A+ API
var Promise = require(163)
var asap = require(136)
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Promise.prototype
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.all = function (arr) {
var args = Array.prototype.slice.call(arr)
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"136":136,"163":163}],166:[function(require,module,exports){
'use strict';
var Promise = require(163)
module.exports = Promise
Promise.prototype['finally'] = function (f) {
return this.then(function (value) {
return Promise.resolve(f()).then(function () {
return value
})
}, function (err) {
return Promise.resolve(f()).then(function () {
throw err
})
})
}
},{"163":163}],167:[function(require,module,exports){
'use strict';
module.exports = require(163)
require(164)
require(166)
require(165)
require(168)
},{"163":163,"164":164,"165":165,"166":166,"168":168}],168:[function(require,module,exports){
'use strict';
//This file contains then/promise specific extensions that are only useful for node.js interop
var Promise = require(163)
var asap = require(134)
module.exports = Promise
/* Static Functions */
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
var res = fn.apply(self, args)
if (res && (typeof res === 'object' || typeof res === 'function') && typeof res.then === 'function') {
resolve(res)
}
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
var ctx = this
try {
return fn.apply(this, arguments).nodeify(callback, ctx)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback.call(ctx, ex)
})
}
}
}
}
Promise.prototype.nodeify = function (callback, ctx) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback.call(ctx, null, value)
})
}, function (err) {
asap(function () {
callback.call(ctx, err)
})
})
}
},{"134":134,"163":163}],169:[function(require,module,exports){
(function (global){
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx'], function (Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require(171));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
// References
var Observable = Rx.Observable,
observableProto = Observable.prototype,
CompositeDisposable = Rx.CompositeDisposable,
AnonymousObservable = Rx.AnonymousObservable,
disposableEmpty = Rx.Disposable.empty,
isEqual = Rx.internals.isEqual,
helpers = Rx.helpers,
not = helpers.not,
defaultComparer = helpers.defaultComparer,
identity = helpers.identity,
defaultSubComparer = helpers.defaultSubComparer,
isFunction = helpers.isFunction,
isPromise = helpers.isPromise,
isArrayLike = helpers.isArrayLike,
isIterable = helpers.isIterable,
inherits = Rx.internals.inherits,
observableFromPromise = Observable.fromPromise,
observableFrom = Observable.from,
bindCallback = Rx.internals.bindCallback,
EmptyError = Rx.EmptyError,
ObservableBase = Rx.ObservableBase,
ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError;
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (o) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
o.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
o.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, function (e) { o.onError(e); }, function () {
o.onNext(list);
o.onCompleted();
});
}, source);
}
function firstOnly(x) {
if (x.length === 0) { throw new EmptyError(); }
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @deprecated Use #reduce instead
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var hasSeed = false, accumulator, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
return o.onError(e);
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new EmptyError());
o.onCompleted();
}
);
}, source);
};
var ReduceObservable = (function(__super__) {
inherits(ReduceObservable, __super__);
function ReduceObservable(source, acc, hasSeed, seed) {
this.source = source;
this.acc = acc;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ReduceObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new InnerObserver(observer,this));
};
function InnerObserver(o, parent) {
this.o = o;
this.acc = parent.acc;
this.hasSeed = parent.hasSeed;
this.seed = parent.seed;
this.hasAccumulation = false;
this.result = null;
this.hasValue = false;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
!this.hasValue && (this.hasValue = true);
if (this.hasAccumulation) {
this.result = tryCatch(this.acc)(this.result, x);
} else {
this.result = this.hasSeed ? tryCatch(this.acc)(this.seed, x) : x;
this.hasAccumulation = true;
}
if (this.result === errorObj) { this.o.onError(this.result.e); }
};
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.hasValue && this.o.onNext(this.result);
!this.hasValue && this.hasSeed && this.o.onNext(this.seed);
!this.hasValue && !this.hasSeed && this.o.onError(new EmptyError());
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; };
InnerObserver.prototype.fail = function(e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return ReduceObservable;
}(ObservableBase));
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var hasSeed = false;
if (arguments.length === 2) {
hasSeed = true;
var seed = arguments[1];
}
return new ReduceObservable(this, accumulator, hasSeed, seed);
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var source = this;
return predicate ?
source.filter(predicate, thisArg).some() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, function (e) { observer.onError(e); }, function () {
observer.onNext(false);
observer.onCompleted();
});
}, source);
};
/** @deprecated use #some instead */
observableProto.any = function () {
//deprecate('any', 'some');
return this.some.apply(this, arguments);
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not);
};
/** @deprecated use #every instead */
observableProto.all = function () {
//deprecate('all', 'every');
return this.every.apply(this, arguments);
};
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
o.onNext(true);
o.onCompleted();
}
},
function (e) { o.onError(e); },
function () {
o.onNext(false);
o.onCompleted();
});
}, this);
};
/**
* @deprecated use #includes instead.
*/
observableProto.contains = function (searchElement, fromIndex) {
//deprecate('contains', 'includes');
observableProto.includes(searchElement, fromIndex);
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.filter(predicate, thisArg).count() :
this.reduce(function (count) { return count + 1; }, 0);
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
o.onNext(i);
o.onCompleted();
}
i++;
},
function (e) { o.onError(e); },
function () {
o.onNext(-1);
o.onCompleted();
});
}, source);
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.reduce(function (prev, curr) { return prev + curr; }, 0);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).average() :
this.reduce(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, {sum: 0, count: 0 }).map(function (s) {
if (s.count === 0) { throw new EmptyError(); }
return s.sum / s.count;
});
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
o.onError(e);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
o.onError(exception);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
}, first);
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (o) {
var i = index;
return source.subscribe(function (x) {
if (i-- === 0) {
o.onNext(x);
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new ArgumentOutOfRangeError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
o.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) {
o.onNext(x);
o.onCompleted();
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new EmptyError());
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = callback(x, i, source);
} catch (e) {
o.onError(e);
return;
}
if (shouldRun) {
o.onNext(yieldIndex ? i : x);
o.onCompleted();
} else {
i++;
}
}, function (e) { o.onError(e); }, function () {
o.onNext(yieldIndex ? -1 : undefined);
o.onCompleted();
});
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var s = new root.Set();
return source.subscribe(
function (x) { s.add(x); },
function (e) { o.onError(e); },
function () {
o.onNext(s);
o.onCompleted();
});
}, source);
};
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
o.onError(e);
return;
}
}
m.set(key, element);
},
function (e) { o.onError(e); },
function () {
o.onNext(m);
o.onCompleted();
});
}, source);
};
return Rx;
}));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"171":171}],170:[function(require,module,exports){
(function (global){
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx'], function (Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require(171));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
var Observable = Rx.Observable,
observableProto = Observable.prototype,
AnonymousObservable = Rx.AnonymousObservable,
Subject = Rx.Subject,
AsyncSubject = Rx.AsyncSubject,
Observer = Rx.Observer,
ScheduledObserver = Rx.internals.ScheduledObserver,
disposableCreate = Rx.Disposable.create,
disposableEmpty = Rx.Disposable.empty,
CompositeDisposable = Rx.CompositeDisposable,
currentThreadScheduler = Rx.Scheduler.currentThread,
isFunction = Rx.helpers.isFunction,
inherits = Rx.internals.inherits,
addProperties = Rx.internals.addProperties,
checkDisposed = Rx.Disposable.checkDisposed;
// Utilities
function cloneArray(arr) {
var len = arr.length, a = new Array(len);
for(var i = 0; i < len; i++) { a[i] = arr[i]; }
return a;
}
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param windowSize [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, windowSize, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, windowSize, scheduler) {
return this.replay(null, bufferSize, windowSize, scheduler).refCount();
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Gets the current value or throws an exception.
* Value is frozen after onCompleted is called.
* After onError is called always throws the specified exception.
* An exception is always thrown after dispose is called.
* @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext.
*/
getValue: function () {
checkDisposed(this);
if (this.hasError) {
throw this.error;
}
return this.value;
},
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
var maxSafeInteger = Math.pow(2, 53) - 1;
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize;
this.windowSize = windowSize == null ? maxSafeInteger : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence
* can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`)
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source.
*/
observableProto.singleInstance = function() {
var source = this, hasObservable = false, observable;
function getObservable() {
if (!hasObservable) {
hasObservable = true;
observable = source.finally(function() { hasObservable = false; }).publish().refCount();
}
return observable;
};
return new AnonymousObservable(function(o) {
return getObservable().subscribe(o);
});
};
return Rx;
}));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"171":171}],171:[function(require,module,exports){
(function (process,global){
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.subscribe !== 'function' && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
var EmptyError = Rx.EmptyError = function() {
this.message = 'Sequence contains no elements.';
Error.call(this);
};
EmptyError.prototype = Error.prototype;
var ObjectDisposedError = Rx.ObjectDisposedError = function() {
this.message = 'Object has been disposed';
Error.call(this);
};
ObjectDisposedError.prototype = Error.prototype;
var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () {
this.message = 'Argument out of range';
Error.call(this);
};
ArgumentOutOfRangeError.prototype = Error.prototype;
var NotSupportedError = Rx.NotSupportedError = function (message) {
this.message = message || 'This operation is not supported';
Error.call(this);
};
NotSupportedError.prototype = Error.prototype;
var NotImplementedError = Rx.NotImplementedError = function (message) {
this.message = message || 'This operation is not implemented';
Error.call(this);
};
NotImplementedError.prototype = Error.prototype;
var notImplemented = Rx.helpers.notImplemented = function () {
throw new NotImplementedError();
};
var notSupported = Rx.helpers.notSupported = function () {
throw new NotSupportedError();
};
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
return tryCatchTarget.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
if (!isFunction(fn)) { throw new TypeError('fn must be a function'); }
tryCatchTarget = fn;
return tryCatcher;
}
function thrower(e) {
throw e;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [], i, len;
if (Array.isArray(arguments[0])) {
args = arguments[0];
len = args.length;
} else {
len = arguments.length;
args = new Array(len);
for(i = 0; i < len; i++) { args[i] = arguments[i]; }
}
for(i = 0; i < len; i++) {
if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); }
}
this.disposables = args;
this.isDisposed = false;
this.length = args.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var len = this.disposables.length, currentDisposables = new Array(len);
for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; }
this.disposables = [];
this.length = 0;
for (i = 0; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Provides a set of static methods for creating Disposables.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
/**
* Validates whether the given object is a disposable
* @param {Object} Object to test whether it has a dispose method
* @returns {Boolean} true if a disposable object, else false.
*/
var isDisposable = Disposable.isDisposable = function (d) {
return d && isFunction(d.dispose);
};
var checkDisposed = Disposable.checkDisposed = function (disposable) {
if (disposable.isDisposed) { throw new ObjectDisposedError(); }
};
// Single assignment
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SingleAssignmentDisposable.prototype.getDisposable = function () {
return this.current;
};
SingleAssignmentDisposable.prototype.setDisposable = function (value) {
if (this.current) { throw new Error('Disposable has already been assigned'); }
var shouldDispose = this.isDisposed;
!shouldDispose && (this.current = value);
shouldDispose && value && value.dispose();
};
SingleAssignmentDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
// Multiple assignment disposable
var SerialDisposable = Rx.SerialDisposable = function () {
this.isDisposed = false;
this.current = null;
};
SerialDisposable.prototype.getDisposable = function () {
return this.current;
};
SerialDisposable.prototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
SerialDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
/** Determines whether the given object is a scheduler */
Scheduler.isScheduler = function (s) {
return s instanceof Scheduler;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize, isScheduler = Scheduler.isScheduler;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2) {
var isAdded = false, isDone = false,
d = scheduler.scheduleWithState(state2, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
}
recursiveAction(state);
return group;
}
function invokeRecDate(scheduler, pair, method) {
var state = pair[0], action = pair[1], group = new CompositeDisposable();
function recursiveAction(state1) {
action(state1, function (state2, dueTime1) {
var isAdded = false, isDone = false,
d = scheduler[method](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState([state, action], invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute([state, action], dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); }
period = normalizeTime(period);
var s = state, id = root.setInterval(function () { s = action(s); }, period);
return disposableCreate(function () { root.clearInterval(id); });
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false.
* @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling.
*/
schedulerProto.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () {
function tick(command, recurse) {
recurse(0, this._period);
try {
this._state = this._action(this._state);
} catch (e) {
this._cancel.dispose();
throw e;
}
}
function SchedulePeriodicRecursive(scheduler, state, period, action) {
this._scheduler = scheduler;
this._state = state;
this._period = period;
this._action = action;
}
SchedulePeriodicRecursive.prototype.start = function () {
var d = new SingleAssignmentDisposable();
this._cancel = d;
d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this)));
return d;
};
return SchedulePeriodicRecursive;
}());
/** Gets a scheduler that schedules work immediately on the current thread. */
var immediateScheduler = Scheduler.immediate = (function () {
function scheduleNow(state, action) { return action(this, state); }
return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline () {
while (queue.length > 0) {
var item = queue.dequeue();
!item.isCancelled() && item.invoke();
}
}
function scheduleNow(state, action) {
var si = new ScheduledItem(this, state, action, this.now());
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
var result = tryCatch(runTrampoline)();
queue = null;
if (result === errorObj) { return thrower(result.e); }
} else {
queue.enqueue(si);
}
return si.disposable;
}
var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported);
currentScheduler.scheduleRequired = function () { return !queue; };
return currentScheduler;
}());
var scheduleMethod, clearMethod;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else if (!!root.WScript) {
localSetTimeout = function (fn, time) {
root.WScript.Sleep(time);
fn();
};
} else {
throw new NotSupportedError();
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false;
clearMethod = function (handle) {
delete tasksByHandle[handle];
};
function runTask(handle) {
if (currentlyRunning) {
localSetTimeout(function () { runTask(handle) }, 0);
} else {
var task = tasksByHandle[handle];
if (task) {
currentlyRunning = true;
var result = tryCatch(task)();
clearMethod(handle);
currentlyRunning = false;
if (result === errorObj) { return thrower(result.e); }
}
}
}
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false, oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (isFunction(setImmediate)) {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
setImmediate(function () { runTask(id); });
return id;
};
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
process.nextTick(function () { runTask(id); });
return id;
};
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random();
function onGlobalPostMessage(event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
runTask(event.data.substring(MSG_PREFIX.length));
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else if (root.attachEvent) {
root.attachEvent('onmessage', onGlobalPostMessage);
} else {
root.onmessage = onGlobalPostMessage;
}
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
return id;
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel();
channel.port1.onmessage = function (e) { runTask(e.data); };
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
channel.port2.postMessage(id);
return id;
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
var id = nextHandle++;
tasksByHandle[id] = action;
scriptElement.onreadystatechange = function () {
runTask(id);
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
return id;
};
} else {
scheduleMethod = function (action) {
var id = nextHandle++;
tasksByHandle[id] = action;
localSetTimeout(function () {
runTask(id);
}, 0);
return id;
};
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = Scheduler['default'] = (function () {
function scheduleNow(state, action) {
var scheduler = this, disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
!disposable.isDisposed && disposable.setDisposable(action(scheduler, state));
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this, dt = Scheduler.normalize(dueTime), disposable = new SingleAssignmentDisposable();
if (dt === 0) { return scheduler.scheduleWithState(state, action); }
var id = localSetTimeout(function () {
!disposable.isDisposed && disposable.setDisposable(action(scheduler, state));
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, value, exception, accept, acceptObservable, toString) {
this.kind = kind;
this.value = value;
this.exception = exception;
this._accept = accept;
this._acceptObservable = acceptObservable;
this.toString = toString;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var self = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithState(self, function (_, notification) {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept(onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString() { return 'OnNext(' + this.value + ')'; }
return function (value) {
return new Notification('N', value, null, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
return new Notification('E', null, e, _accept, _acceptObservable, toString);
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
return new Notification('C', null, null, _accept, _acceptObservable, toString);
};
}());
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
// Must be implemented by other observers
AbstractObserver.prototype.next = notImplemented;
AbstractObserver.prototype.error = notImplemented;
AbstractObserver.prototype.completed = notImplemented;
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (__super__) {
inherits(CheckedObserver, __super__);
function CheckedObserver(observer) {
__super__.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
var res = tryCatch(this._observer.onNext).call(this._observer, value);
this._state = 0;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onError = function (err) {
this.checkAccess();
var res = tryCatch(this._observer.onError).call(this._observer, err);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.onCompleted = function () {
this.checkAccess();
var res = tryCatch(this._observer.onCompleted).call(this._observer);
this._state = 2;
res === errorObj && thrower(res.e);
};
CheckedObserverPrototype.checkAccess = function () {
if (this._state === 1) { throw new Error('Re-entrancy detected'); }
if (this._state === 2) { throw new Error('Observer completed'); }
if (this._state === 0) { this._state = 1; }
};
return CheckedObserver;
}(Observer));
var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) {
inherits(ScheduledObserver, __super__);
function ScheduledObserver(scheduler, observer) {
__super__.call(this);
this.scheduler = scheduler;
this.observer = observer;
this.isAcquired = false;
this.hasFaulted = false;
this.queue = [];
this.disposable = new SerialDisposable();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], self = state[1];
var sub = tryCatch(self.subscribeCore).call(self, ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = notImplemented;
return ObservableBase;
}(Observable));
var Enumerable = Rx.internals.Enumerable = function () { };
var ConcatEnumerableObservable = (function(__super__) {
inherits(ConcatEnumerableObservable, __super__);
function ConcatEnumerableObservable(sources) {
this.sources = sources;
__super__.call(this);
}
ConcatEnumerableObservable.prototype.subscribeCore = function (o) {
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](), function (e, self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(new InnerObserver(o, self, e)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
function InnerObserver(o, s, e) {
this.o = o;
this.s = s;
this.e = e;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.o.onNext(x); } };
InnerObserver.prototype.onError = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.s(this.e);
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; };
InnerObserver.prototype.fail = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
return true;
}
return false;
};
return ConcatEnumerableObservable;
}(ObservableBase));
Enumerable.prototype.concat = function () {
return new ConcatEnumerableObservable(this);
};
var CatchErrorObservable = (function(__super__) {
inherits(CatchErrorObservable, __super__);
function CatchErrorObservable(sources) {
this.sources = sources;
__super__.call(this);
}
CatchErrorObservable.prototype.subscribeCore = function (o) {
var e = this.sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
return lastException !== null ? o.onError(lastException) : o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
return CatchErrorObservable;
}(ObservableBase));
Enumerable.prototype.catchError = function () {
return new CatchErrorObservable(this);
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem = tryCatch(e.next).call(e);
if (currentItem === errorObj) { return o.onError(currentItem.e); }
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var RepeatEnumerable = (function (__super__) {
inherits(RepeatEnumerable, __super__);
function RepeatEnumerable(v, c) {
this.v = v;
this.c = c == null ? -1 : c;
}
RepeatEnumerable.prototype[$iterator$] = function () {
return new RepeatEnumerator(this);
};
function RepeatEnumerator(p) {
this.v = p.v;
this.l = p.c;
}
RepeatEnumerator.prototype.next = function () {
if (this.l === 0) { return doneEnumerator; }
if (this.l > 0) { this.l--; }
return { done: false, value: this.v };
};
return RepeatEnumerable;
}(Enumerable));
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
return new RepeatEnumerable(value, repeatCount);
};
var OfEnumerable = (function(__super__) {
inherits(OfEnumerable, __super__);
function OfEnumerable(s, fn, thisArg) {
this.s = s;
this.fn = fn ? bindCallback(fn, thisArg, 3) : null;
}
OfEnumerable.prototype[$iterator$] = function () {
return new OfEnumerator(this);
};
function OfEnumerator(p) {
this.i = -1;
this.s = p.s;
this.l = this.s.length;
this.fn = p.fn;
}
OfEnumerator.prototype.next = function () {
return ++this.i < this.l ?
{ done: false, value: !this.fn ? this.s[this.i] : this.fn(this.s[this.i], this.i, this.s) } :
doneEnumerator;
};
return OfEnumerable;
}(Enumerable));
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
return new OfEnumerable(source, selector, thisArg);
};
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
var FromPromiseObservable = (function(__super__) {
inherits(FromPromiseObservable, __super__);
function FromPromiseObservable(p) {
this.p = p;
__super__.call(this);
}
FromPromiseObservable.prototype.subscribeCore = function(o) {
this.p.then(function (data) {
o.onNext(data);
o.onCompleted();
}, function (err) { o.onError(err); });
return disposableEmpty;
};
return FromPromiseObservable;
}(ObservableBase));
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new FromPromiseObservable(promise);
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
var ToArrayObservable = (function(__super__) {
inherits(ToArrayObservable, __super__);
function ToArrayObservable(source) {
this.source = source;
__super__.call(this);
}
ToArrayObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.a = [];
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.o.onNext(this.a);
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; }
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return ToArrayObservable;
}(ObservableBase));
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
return new ToArrayObservable(this);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
var EmptyObservable = (function(__super__) {
inherits(EmptyObservable, __super__);
function EmptyObservable(scheduler) {
this.scheduler = scheduler;
__super__.call(this);
}
EmptyObservable.prototype.subscribeCore = function (observer) {
var sink = new EmptySink(observer, this);
return sink.run();
};
function EmptySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
state.onCompleted();
}
EmptySink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState(this.observer, scheduleItem);
};
return EmptyObservable;
}(ObservableBase));
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new EmptyObservable(scheduler);
};
var FromObservable = (function(__super__) {
inherits(FromObservable, __super__);
function FromObservable(iterable, mapper, scheduler) {
this.iterable = iterable;
this.mapper = mapper;
this.scheduler = scheduler;
__super__.call(this);
}
FromObservable.prototype.subscribeCore = function (observer) {
var sink = new FromSink(observer, this);
return sink.run();
};
return FromObservable;
}(ObservableBase));
var FromSink = (function () {
function FromSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromSink.prototype.run = function () {
var list = Object(this.parent.iterable),
it = getIterable(list),
observer = this.observer,
mapper = this.parent.mapper;
function loopRecursive(i, recurse) {
try {
var next = it.next();
} catch (e) {
return observer.onError(e);
}
if (next.done) {
return observer.onCompleted();
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
return observer.onError(e);
}
}
observer.onNext(result);
recurse(i + 1);
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return FromSink;
}());
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator;
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator;
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromObservable(iterable, mapper, scheduler);
}
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
FromArraySink.prototype.run = function () {
var observer = this.observer, args = this.parent.args, len = args.length;
function loopRecursive(i, recurse) {
if (i < len) {
observer.onNext(args[i]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (o) {
var first = true;
return scheduler.scheduleRecursiveWithState(initialState, function (state, self) {
var hasResult, result;
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
hasResult && (result = resultSelector(state));
} catch (e) {
return o.onError(e);
}
if (hasResult) {
o.onNext(result);
self(state);
} else {
o.onCompleted();
}
});
});
};
var NeverObservable = (function(__super__) {
inherits(NeverObservable, __super__);
function NeverObservable() {
__super__.call(this);
}
NeverObservable.prototype.subscribeCore = function (observer) {
return disposableEmpty;
};
return NeverObservable;
}(ObservableBase));
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new NeverObservable();
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new FromArrayObservable(array, scheduler);
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return new FromArrayObservable(args, currentThreadScheduler);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length, args = new Array(len - 1);
for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; }
return new FromArrayObservable(args, scheduler);
};
var PairsObservable = (function(__super__) {
inherits(PairsObservable, __super__);
function PairsObservable(obj, scheduler) {
this.obj = obj;
this.keys = Object.keys(obj);
this.scheduler = scheduler;
__super__.call(this);
}
PairsObservable.prototype.subscribeCore = function (observer) {
var sink = new PairsSink(observer, this);
return sink.run();
};
return PairsObservable;
}(ObservableBase));
function PairsSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
PairsSink.prototype.run = function () {
var observer = this.observer, obj = this.parent.obj, keys = this.parent.keys, len = keys.length;
function loopRecursive(i, recurse) {
if (i < len) {
var key = keys[i];
observer.onNext([key, obj[key]]);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new PairsObservable(obj, scheduler);
};
var RangeObservable = (function(__super__) {
inherits(RangeObservable, __super__);
function RangeObservable(start, count, scheduler) {
this.start = start;
this.rangeCount = count;
this.scheduler = scheduler;
__super__.call(this);
}
RangeObservable.prototype.subscribeCore = function (observer) {
var sink = new RangeSink(observer, this);
return sink.run();
};
return RangeObservable;
}(ObservableBase));
var RangeSink = (function () {
function RangeSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RangeSink.prototype.run = function () {
var start = this.parent.start, count = this.parent.rangeCount, observer = this.observer;
function loopRecursive(i, recurse) {
if (i < count) {
observer.onNext(start + i);
recurse(i + 1);
} else {
observer.onCompleted();
}
}
return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive);
};
return RangeSink;
}());
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RangeObservable(start, count, scheduler);
};
var RepeatObservable = (function(__super__) {
inherits(RepeatObservable, __super__);
function RepeatObservable(value, repeatCount, scheduler) {
this.value = value;
this.repeatCount = repeatCount == null ? -1 : repeatCount;
this.scheduler = scheduler;
__super__.call(this);
}
RepeatObservable.prototype.subscribeCore = function (observer) {
var sink = new RepeatSink(observer, this);
return sink.run();
};
return RepeatObservable;
}(ObservableBase));
function RepeatSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
RepeatSink.prototype.run = function () {
var observer = this.observer, value = this.parent.value;
function loopRecursive(i, recurse) {
if (i === -1 || i > 0) {
observer.onNext(value);
i > 0 && i--;
}
if (i === 0) { return observer.onCompleted(); }
recurse(i);
}
return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount, loopRecursive);
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new RepeatObservable(value, repeatCount, scheduler);
};
var JustObservable = (function(__super__) {
inherits(JustObservable, __super__);
function JustObservable(value, scheduler) {
this.value = value;
this.scheduler = scheduler;
__super__.call(this);
}
JustObservable.prototype.subscribeCore = function (observer) {
var sink = new JustSink(observer, this);
return sink.run();
};
function JustSink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function scheduleItem(s, state) {
var value = state[0], observer = state[1];
observer.onNext(value);
observer.onCompleted();
}
JustSink.prototype.run = function () {
return this.parent.scheduler.scheduleWithState([this.parent.value, this.observer], scheduleItem);
};
return JustObservable;
}(ObservableBase));
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just' or browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new JustObservable(value, scheduler);
};
var ThrowObservable = (function(__super__) {
inherits(ThrowObservable, __super__);
function ThrowObservable(error, scheduler) {
this.error = error;
this.scheduler = scheduler;
__super__.call(this);
}
ThrowObservable.prototype.subscribeCore = function (o) {
var sink = new ThrowSink(o, this);
return sink.run();
};
function ThrowSink(o, p) {
this.o = o;
this.p = p;
}
function scheduleItem(s, state) {
var e = state[0], o = state[1];
o.onError(e);
}
ThrowSink.prototype.run = function () {
return this.p.scheduler.scheduleWithState([this.p.error, this.o], scheduleItem);
};
return ThrowObservable;
}(ObservableBase));
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = Observable.throwException = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new ThrowObservable(error, scheduler);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
choice === leftChoice && observer.onNext(left);
}, function (err) {
choiceL();
choice === leftChoice && observer.onError(err);
}, function () {
choiceL();
choice === leftChoice && observer.onCompleted();
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
choice === rightChoice && observer.onNext(right);
}, function (err) {
choiceR();
choice === rightChoice && observer.onError(err);
}, function () {
choiceR();
choice === rightChoice && observer.onCompleted();
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (o) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) {
try {
var result = handler(e);
} catch (ex) {
return o.onError(ex);
}
isPromise(result) && (result = observableFromPromise(result));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(o));
}, function (x) { o.onCompleted(x); }));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop();
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (o) {
var n = args.length,
falseFactory = function () { return false; },
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
var res = resultSelector.apply(null, values);
} catch (e) {
return o.onError(e);
}
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}
function done (i) {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { o.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
var ConcatObservable = (function(__super__) {
inherits(ConcatObservable, __super__);
function ConcatObservable(sources) {
this.sources = sources;
__super__.call(this);
}
ConcatObservable.prototype.subscribeCore = function(o) {
var sink = new ConcatSink(this.sources, o);
return sink.run();
};
function ConcatSink(sources, o) {
this.sources = sources;
this.o = o;
}
ConcatSink.prototype.run = function () {
var isDisposed, subscription = new SerialDisposable(), sources = this.sources, length = sources.length, o = this.o;
var cancelable = immediateScheduler.scheduleRecursiveWithState(0, function (i, self) {
if (isDisposed) { return; }
if (i === length) {
return o.onCompleted();
}
// Check if promise
var currentValue = sources[i];
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function (x) { o.onNext(x); },
function (e) { o.onError(e); },
function () { self(i + 1); }
));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
};
return ConcatObservable;
}(ObservableBase));
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
args = new Array(arguments.length);
for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; }
}
return new ConcatObservable(args);
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
var MergeObservable = (function (__super__) {
inherits(MergeObservable, __super__);
function MergeObservable(source, maxConcurrent) {
this.source = source;
this.maxConcurrent = maxConcurrent;
__super__.call(this);
}
MergeObservable.prototype.subscribeCore = function(observer) {
var g = new CompositeDisposable();
g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g)));
return g;
};
return MergeObservable;
}(ObservableBase));
var MergeObserver = (function () {
function MergeObserver(o, max, g) {
this.o = o;
this.max = max;
this.g = g;
this.done = false;
this.q = [];
this.activeCount = 0;
this.isStopped = false;
}
MergeObserver.prototype.handleSubscribe = function (xs) {
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(xs) && (xs = observableFromPromise(xs));
sad.setDisposable(xs.subscribe(new InnerObserver(this, sad)));
};
MergeObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
if(this.activeCount < this.max) {
this.activeCount++;
this.handleSubscribe(innerSource);
} else {
this.q.push(innerSource);
}
};
MergeObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.done = true;
this.activeCount === 0 && this.o.onCompleted();
}
};
MergeObserver.prototype.dispose = function() { this.isStopped = true; };
MergeObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, sad) {
this.parent = parent;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
var parent = this.parent;
parent.g.remove(this.sad);
if (parent.q.length > 0) {
parent.handleSubscribe(parent.q.shift());
} else {
parent.activeCount--;
parent.done && parent.activeCount === 0 && parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeObserver;
}());
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
return typeof maxConcurrentOrOther !== 'number' ?
observableMerge(this, maxConcurrentOrOther) :
new MergeObservable(this, maxConcurrentOrOther);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
var CompositeError = Rx.CompositeError = function(errors) {
this.name = "NotImplementedError";
this.innerErrors = errors;
this.message = 'This contains multiple errors. Check the innerErrors';
Error.call(this);
}
CompositeError.prototype = Error.prototype;
/**
* Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to
* receive all successfully emitted items from all of the source Observables without being interrupted by
* an error notification from one of them.
*
* This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an
* error via the Observer's onError, mergeDelayError will refrain from propagating that
* error notification until all of the merged Observables have finished emitting items.
* @param {Array | Arguments} args Arguments or an array to merge.
* @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable
*/
Observable.mergeDelayError = function() {
var args;
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
var len = arguments.length;
args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
}
var source = observableOf(null, args);
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
m = new SingleAssignmentDisposable(),
isStopped = false,
errors = [];
function setCompletion() {
if (errors.length === 0) {
o.onCompleted();
} else if (errors.length === 1) {
o.onError(errors[0]);
} else {
o.onError(new CompositeError(errors));
}
}
group.add(m);
m.setDisposable(source.subscribe(
function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) { o.onNext(x); },
function (e) {
errors.push(e);
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
},
function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && setCompletion();
}));
},
function (e) {
errors.push(e);
isStopped = true;
group.length === 1 && setCompletion();
},
function () {
isStopped = true;
group.length === 1 && setCompletion();
}));
return group;
});
};
var MergeAllObservable = (function (__super__) {
inherits(MergeAllObservable, __super__);
function MergeAllObservable(source) {
this.source = source;
__super__.call(this);
}
MergeAllObservable.prototype.subscribeCore = function (observer) {
var g = new CompositeDisposable(), m = new SingleAssignmentDisposable();
g.add(m);
m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g)));
return g;
};
function MergeAllObserver(o, g) {
this.o = o;
this.g = g;
this.isStopped = false;
this.done = false;
}
MergeAllObserver.prototype.onNext = function(innerSource) {
if(this.isStopped) { return; }
var sad = new SingleAssignmentDisposable();
this.g.add(sad);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad)));
};
MergeAllObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
MergeAllObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.done = true;
this.g.length === 1 && this.o.onCompleted();
}
};
MergeAllObserver.prototype.dispose = function() { this.isStopped = true; };
MergeAllObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, g, sad) {
this.parent = parent;
this.g = g;
this.sad = sad;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } };
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
var parent = this.parent;
this.isStopped = true;
parent.g.remove(this.sad);
parent.done && parent.g.length === 1 && parent.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return MergeAllObservable;
}(ObservableBase));
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = observableProto.mergeObservable = function () {
return new MergeAllObservable(this);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
var SwitchObservable = (function(__super__) {
inherits(SwitchObservable, __super__);
function SwitchObservable(source) {
this.source = source;
__super__.call(this);
}
SwitchObservable.prototype.subscribeCore = function (o) {
var inner = new SerialDisposable(), s = this.source.subscribe(new SwitchObserver(o, inner));
return new CompositeDisposable(s, inner);
};
function SwitchObserver(o, inner) {
this.o = o;
this.inner = inner;
this.stopped = false;
this.latest = 0;
this.hasLatest = false;
this.isStopped = false;
}
SwitchObserver.prototype.onNext = function (innerSource) {
if (this.isStopped) { return; }
var d = new SingleAssignmentDisposable(), id = ++this.latest;
this.hasLatest = true;
this.inner.setDisposable(d);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(new InnerObserver(this, id)));
};
SwitchObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
}
};
SwitchObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.stopped = true;
!this.hasLatest && this.o.onCompleted();
}
};
SwitchObserver.prototype.dispose = function () { this.isStopped = true; };
SwitchObserver.prototype.fail = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
function InnerObserver(parent, id) {
this.parent = parent;
this.id = id;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
this.parent.latest === this.id && this.parent.o.onNext(x);
};
InnerObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.parent.latest === this.id && this.parent.o.onError(e);
}
};
InnerObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
if (this.parent.latest === this.id) {
this.parent.hasLatest = false;
this.parent.isStopped && this.parent.o.onCompleted();
}
}
};
InnerObserver.prototype.dispose = function () { this.isStopped = true; }
InnerObserver.prototype.fail = function (e) {
if(!this.isStopped) {
this.isStopped = true;
this.parent.o.onError(e);
return true;
}
return false;
};
return SwitchObservable;
}(ObservableBase));
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
return new SwitchObservable(this);
};
var TakeUntilObservable = (function(__super__) {
inherits(TakeUntilObservable, __super__);
function TakeUntilObservable(source, other) {
this.source = source;
this.other = isPromise(other) ? observableFromPromise(other) : other;
__super__.call(this);
}
TakeUntilObservable.prototype.subscribeCore = function(o) {
return new CompositeDisposable(
this.source.subscribe(o),
this.other.subscribe(new InnerObserver(o))
);
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
this.o.onCompleted();
};
InnerObserver.prototype.onError = function (err) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
!this.isStopped && (this.isStopped = true);
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return TakeUntilObservable;
}(ObservableBase));
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
return new TakeUntilObservable(this, other);
};
function falseFactory() { return false; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
var len = arguments.length, args = new Array(len)
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var resultSelector = args.pop(), source = this;
Array.isArray(args[0]) && (args = args[0]);
return new AnonymousObservable(function (observer) {
var n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, function (e) { observer.onError(e); }, noop));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var allValues = [x].concat(values);
if (!hasValueAll) { return; }
var res = tryCatch(resultSelector).apply(null, allValues);
if (res === errorObj) { return observer.onError(res.e); }
observer.onNext(res);
}, function (e) { observer.onError(e); }, function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (o) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], res = tryCatch(resultSelector)(left, right);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
} else {
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); }
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (o) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
if (queues.every(function (x) { return x.length > 0; })) {
var queuedValues = queues.map(function (x) { return x.shift(); }),
res = tryCatch(resultSelector).apply(parent, queuedValues);
if (res === errorObj) { return o.onError(res.e); }
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
var first = args.shift();
return first.zip.apply(first, args);
};
function falseFactory() { return false; }
function arrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources;
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
var len = arguments.length;
sources = new Array(len);
for(var i = 0; i < len; i++) { sources[i] = arguments[i]; }
}
return new AnonymousObservable(function (o) {
var n = sources.length,
queues = arrayInitialize(n, arrayFactory),
isDone = arrayInitialize(n, falseFactory);
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
o.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
return o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
isDone[i] = true;
isDone.every(identity) && o.onCompleted();
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
key = tryCatch(keySelector)(value);
if (key === errorObj) { return o.onError(key.e); }
}
if (hasCurrentKey) {
var comparerEquals = tryCatch(comparer)(currentKey, key);
if (comparerEquals === errorObj) { return o.onError(comparerEquals.e); }
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
var TapObservable = (function(__super__) {
inherits(TapObservable,__super__);
function TapObservable(source, observerOrOnNext, onError, onCompleted) {
this.source = source;
this.t = !observerOrOnNext || isFunction(observerOrOnNext) ?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
__super__.call(this);
}
TapObservable.prototype.subscribeCore = function(o) {
return this.source.subscribe(new InnerObserver(o, this.t));
};
function InnerObserver(o, t) {
this.o = o;
this.t = t;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var res = tryCatch(this.t.onNext).call(this.t, x);
if (res === errorObj) { this.o.onError(res.e); }
this.o.onNext(x);
};
InnerObserver.prototype.onError = function(err) {
if (!this.isStopped) {
this.isStopped = true;
var res = tryCatch(this.t.onError).call(this.t, err);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) {
this.isStopped = true;
var res = tryCatch(this.t.onCompleted).call(this.t);
if (res === errorObj) { return this.o.onError(res.e); }
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return TapObservable;
}(ObservableBase));
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an o.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
return new TapObservable(this, observerOrOnNext, onError, onCompleted);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
var IgnoreElementsObservable = (function(__super__) {
inherits(IgnoreElementsObservable, __super__);
function IgnoreElementsObservable(source) {
this.source = source;
__super__.call(this);
}
IgnoreElementsObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o));
};
function InnerObserver(o) {
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = noop;
InnerObserver.prototype.onError = function (err) {
if(!this.isStopped) {
this.isStopped = true;
this.o.onError(err);
}
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) {
this.isStopped = true;
this.o.onCompleted();
}
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
return IgnoreElementsObservable;
}(ObservableBase));
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
return new IgnoreElementsObservable(this);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
var ScanObservable = (function(__super__) {
inherits(ScanObservable, __super__);
function ScanObservable(source, accumulator, hasSeed, seed) {
this.source = source;
this.accumulator = accumulator;
this.hasSeed = hasSeed;
this.seed = seed;
__super__.call(this);
}
ScanObservable.prototype.subscribeCore = function(observer) {
return this.source.subscribe(new ScanObserver(observer,this));
};
return ScanObservable;
}(ObservableBase));
function ScanObserver(observer, parent) {
this.observer = observer;
this.accumulator = parent.accumulator;
this.hasSeed = parent.hasSeed;
this.seed = parent.seed;
this.hasAccumulation = false;
this.accumulation = null;
this.hasValue = false;
this.isStopped = false;
}
ScanObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
!this.hasValue && (this.hasValue = true);
try {
if (this.hasAccumulation) {
this.accumulation = this.accumulator(this.accumulation, x);
} else {
this.accumulation = this.hasSeed ? this.accumulator(this.seed, x) : x;
this.hasAccumulation = true;
}
} catch (e) {
return this.observer.onError(e);
}
this.observer.onNext(this.accumulation);
};
ScanObserver.prototype.onError = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
}
};
ScanObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
!this.hasValue && this.hasSeed && this.observer.onNext(this.seed);
this.observer.onCompleted();
}
};
ScanObserver.prototype.dispose = function() { this.isStopped = true; };
ScanObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new ScanObservable(this, accumulator, hasSeed, seed);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new ArgumentOutOfRangeError(); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new ArgumentOutOfRangeError(); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
function innerMap(selector, self) {
return function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
return new MapObservable(this.source, innerMap(selector, this), thisArg);
};
MapObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.selector, this));
};
function InnerObserver(o, selector, source) {
this.o = o;
this.selector = selector;
this.source = source;
this.i = 0;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var result = tryCatch(this.selector)(x, this.i++, this.source);
if (result === errorObj) {
return this.o.onError(result.e);
}
this.o.onNext(result);
};
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return MapObservable;
}(ObservableBase));
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selectorFn, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
var SkipObservable = (function(__super__) {
inherits(SkipObservable, __super__);
function SkipObservable(source, count) {
this.source = source;
this.skipCount = count;
__super__.call(this);
}
SkipObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.skipCount));
};
function InnerObserver(o, c) {
this.c = c;
this.r = c;
this.o = o;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function (x) {
if (this.isStopped) { return; }
if (this.r <= 0) {
this.o.onNext(x);
} else {
this.r--;
}
};
InnerObserver.prototype.onError = function(e) {
if (!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function() {
if (!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function(e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return SkipObservable;
}(ObservableBase));
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
return new SkipObservable(this, count);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new ArgumentOutOfRangeError(); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining <= 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (o) {
return this.source.subscribe(new InnerObserver(o, this.predicate, this));
};
function innerPredicate(predicate, self) {
return function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }
}
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
return new FilterObservable(this.source, innerPredicate(predicate, this), thisArg);
};
function InnerObserver(o, predicate, source) {
this.o = o;
this.predicate = predicate;
this.source = source;
this.i = 0;
this.isStopped = false;
}
InnerObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
var shouldYield = tryCatch(this.predicate)(x, this.i++, this.source);
if (shouldYield === errorObj) {
return this.o.onError(shouldYield.e);
}
shouldYield && this.o.onNext(x);
};
InnerObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.o.onError(e); }
};
InnerObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.o.onCompleted(); }
};
InnerObserver.prototype.dispose = function() { this.isStopped = true; };
InnerObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.o.onError(e);
return true;
}
return false;
};
return FilterObservable;
}(ObservableBase));
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(o) {
return {
'@@transducer/init': function() {
return o;
},
'@@transducer/step': function(obs, input) {
return obs.onNext(input);
},
'@@transducer/result': function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(o) {
var xform = transducer(transformForObserver(o));
return source.subscribe(
function(v) {
try {
xform['@@transducer/step'](o, v);
} catch (e) {
o.onError(e);
}
},
function (e) { o.onError(e); },
function() { xform['@@transducer/result'](o); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
return subscriber && isFunction(subscriber.dispose) ? subscriber :
isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty;
}
function setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
var sub = tryCatch(subscribe)(ado);
if (sub === errorObj) {
if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); }
}
ado.setDisposable(fixSubscriber(sub));
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var result = tryCatch(this.observer.onNext).call(this.observer, value);
if (result === errorObj) {
this.dispose();
thrower(result.e);
}
};
AutoDetachObserverPrototype.error = function (err) {
var result = tryCatch(this.observer.onError).call(this.observer, err);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.completed = function () {
var result = tryCatch(this.observer.onCompleted).call(this.observer);
this.dispose();
result === errorObj && thrower(result.e);
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
}).call(this,require(139),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"139":139}]},{},[1])(1)
}); |
/**
* @ngdoc service
* @name umbraco.mocks.mediaHelperService
* @description A helper object used for dealing with media items
**/
function mediaHelper(umbRequestHelper) {
return {
/**
* @ngdoc function
* @name umbraco.services.mediaHelper#getImagePropertyValue
* @methodOf umbraco.services.mediaHelper
* @function
*
* @description
* Returns the file path associated with the media property if there is one
*
* @param {object} options Options object
* @param {object} options.mediaModel The media object to retrieve the image path from
* @param {object} options.imageOnly Optional, if true then will only return a path if the media item is an image
*/
getMediaPropertyValue: function (options) {
return "assets/img/mocks/big-image.jpg";
},
/**
* @ngdoc function
* @name umbraco.services.mediaHelper#getImagePropertyValue
* @methodOf umbraco.services.mediaHelper
* @function
*
* @description
* Returns the actual image path associated with the image property if there is one
*
* @param {object} options Options object
* @param {object} options.imageModel The media object to retrieve the image path from
*/
getImagePropertyValue: function (options) {
return "assets/img/mocks/big-image.jpg";
},
/**
* @ngdoc function
* @name umbraco.services.mediaHelper#getThumbnail
* @methodOf umbraco.services.mediaHelper
* @function
*
* @description
* formats the display model used to display the content to the model used to save the content
*
* @param {object} options Options object
* @param {object} options.imageModel The media object to retrieve the image path from
*/
getThumbnail: function (options) {
if (!options || !options.imageModel) {
throw "The options objet does not contain the required parameters: imageModel";
}
var imagePropVal = this.getImagePropertyValue(options);
if (imagePropVal !== "") {
return this.getThumbnailFromPath(imagePropVal);
}
return "";
},
/**
* @ngdoc function
* @name umbraco.services.mediaHelper#scaleToMaxSize
* @methodOf umbraco.services.mediaHelper
* @function
*
* @description
* Finds the corrct max width and max height, given maximum dimensions and keeping aspect ratios
*
* @param {number} maxSize Maximum width & height
* @param {number} width Current width
* @param {number} height Current height
*/
scaleToMaxSize: function (maxSize, width, height) {
var retval = { width: width, height: height };
var maxWidth = maxSize; // Max width for the image
var maxHeight = maxSize; // Max height for the image
var ratio = 0; // Used for aspect ratio
// Check if the current width is larger than the max
if (width > maxWidth) {
ratio = maxWidth / width; // get ratio for scaling image
retval.width = maxWidth;
retval.height = height * ratio;
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if (height > maxHeight) {
ratio = maxHeight / height; // get ratio for scaling image
retval.height = maxHeight;
retval.width = width * ratio;
width = width * ratio; // Reset width to match scaled image
}
return retval;
},
/**
* @ngdoc function
* @name umbraco.services.mediaHelper#getThumbnailFromPath
* @methodOf umbraco.services.mediaHelper
* @function
*
* @description
* Returns the path to the thumbnail version of a given media library image path
*
* @param {string} imagePath Image path, ex: /media/1234/my-image.jpg
*/
getThumbnailFromPath: function (imagePath) {
return "assets/img/mocks/big-thumb.jpg";
},
/**
* @ngdoc function
* @name umbraco.services.mediaHelper#detectIfImageByExtension
* @methodOf umbraco.services.mediaHelper
* @function
*
* @description
* Returns true/false, indicating if the given path has an allowed image extension
*
* @param {string} imagePath Image path, ex: /media/1234/my-image.jpg
*/
detectIfImageByExtension: function (imagePath) {
var lowered = imagePath.toLowerCase();
var ext = lowered.substr(lowered.lastIndexOf(".") + 1);
return ("," + Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes + ",").indexOf("," + ext + ",") !== -1;
}
};
}
angular.module('umbraco.mocks').factory('mediaHelper', mediaHelper); |
"use strict";!function(n){var o=function(){function n(n){function o(n){this.v=n}var t=n.scanner.TOKENS,r=n.parser,i=r.TOKENS,e=r.State,s=i.Base,u=n.parser.start,a=t.DOMAIN,S=t.LOCALHOST,c=t.NUM,f=t.SLASH,w=t.TLD,O=t.UNDERSCORE;n.inherits(s,o,{type:"mention",isLink:!0,toHref:function(){return"/"+this.toString().substr(1)}});var L=u.jump(t.AT),N=new e,T=new e(o),p=new e,v=new e;L.on(O,N),N.on(O,N),L.on(a,T).on(S,T).on(w,T).on(c,T),N.on(a,T).on(S,T).on(w,T).on(c,T),T.on(a,T).on(S,T).on(w,T).on(c,T).on(O,T),T.on(f,p),p.on(O,v),v.on(O,v),p.on(a,T).on(S,T).on(w,T).on(c,T),v.on(a,T).on(S,T).on(w,T).on(c,T)}return n}();o(n)}(window.linkify); |
/**
* @fileoverview A rule to warn against using arrow functions when they could be
* confused with comparisions
* @author Jxck <https://github.com/Jxck>
*/
"use strict";
const astUtils = require("../ast-utils.js");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a node is a conditional expression.
* @param {ASTNode} node - node to test
* @returns {boolean} `true` if the node is a conditional expression.
*/
function isConditional(node) {
return node && node.type === "ConditionalExpression";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow arrow functions where they could be confused with comparisons",
category: "ECMAScript 6",
recommended: false
},
schema: [{
type: "object",
properties: {
allowParens: {type: "boolean"}
},
additionalProperties: false
}]
},
create(context) {
const config = context.options[0] || {};
const sourceCode = context.getSourceCode();
/**
* Reports if an arrow function contains an ambiguous conditional.
* @param {ASTNode} node - A node to check and report.
* @returns {void}
*/
function checkArrowFunc(node) {
const body = node.body;
if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) {
context.report(node, "Arrow function used ambiguously with a conditional expression.");
}
}
return {
ArrowFunctionExpression: checkArrowFunc
};
}
};
|
import { get } from 'ember-metal/property_get';
import isNone from 'ember-metal/is_none';
/**
Verifies that a value is `null` or an empty string, empty array,
or empty function.
Constrains the rules on `Ember.isNone` by returning true for empty
string and empty arrays.
```javascript
Ember.isEmpty(); // true
Ember.isEmpty(null); // true
Ember.isEmpty(undefined); // true
Ember.isEmpty(''); // true
Ember.isEmpty([]); // true
Ember.isEmpty({}); // false
Ember.isEmpty('Adam Hawkins'); // false
Ember.isEmpty([0,1,2]); // false
```
@method isEmpty
@for Ember
@param {Object} obj Value to test
@return {Boolean}
@public
*/
function isEmpty(obj) {
var none = isNone(obj);
if (none) {
return none;
}
if (typeof obj.size === 'number') {
return !obj.size;
}
var objectType = typeof obj;
if (objectType === 'object') {
var size = get(obj, 'size');
if (typeof size === 'number') {
return !size;
}
}
if (typeof obj.length === 'number' && objectType !== 'function') {
return !obj.length;
}
if (objectType === 'object') {
var length = get(obj, 'length');
if (typeof length === 'number') {
return !length;
}
}
return false;
}
export default isEmpty;
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mobx = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
registerGlobals();
exports._ = {
quickDiff: quickDiff,
resetGlobalState: resetGlobalState
};
exports.extras = {
getDependencyTree: getDependencyTree,
getObserverTree: getObserverTree,
trackTransitions: trackTransitions,
isComputingDerivation: isComputingDerivation,
allowStateChanges: allowStateChanges
};
function autorun(view, scope) {
assertUnwrapped(view, "autorun methods cannot have modifiers");
invariant(typeof view === "function", "autorun expects a function");
invariant(view.length === 0, "autorun expects a function without arguments");
if (scope)
view = view.bind(scope);
var reaction = new Reaction(view.name || "Autorun", function () {
this.track(view);
});
if (isComputingDerivation() || globalState.inTransaction > 0)
globalState.pendingReactions.push(reaction);
else
reaction.runReaction();
return reaction.getDisposer();
}
exports.autorun = autorun;
function when(predicate, effect, scope) {
var disposeImmediately = false;
var disposer = autorun(function () {
if (predicate.call(scope)) {
if (disposer)
disposer();
else
disposeImmediately = true;
effect.call(scope);
}
});
if (disposeImmediately)
disposer();
return disposer;
}
exports.when = when;
function autorunUntil(predicate, effect, scope) {
deprecated("`autorunUntil` is deprecated, please use `when`.");
return when.apply(null, arguments);
}
exports.autorunUntil = autorunUntil;
function autorunAsync(func, delay, scope) {
if (delay === void 0) { delay = 1; }
if (scope)
func = func.bind(scope);
var isScheduled = false;
var r = new Reaction(func.name || "AutorunAsync", function () {
if (!isScheduled) {
isScheduled = true;
setTimeout(function () {
isScheduled = false;
if (!r.isDisposed)
r.track(func);
}, delay);
}
});
r.runReaction();
return r.getDisposer();
}
exports.autorunAsync = autorunAsync;
function computed(targetOrExpr, keyOrScope, baseDescriptor, options) {
if (arguments.length < 3 && typeof targetOrExpr === "function")
return computedExpr(targetOrExpr, keyOrScope);
return computedDecorator.apply(null, arguments);
}
exports.computed = computed;
function computedExpr(expr, scope) {
var _a = getValueModeFromValue(expr, ValueMode.Recursive), mode = _a[0], value = _a[1];
return new ComputedValue(value, scope, mode === ValueMode.Structure, value.name || "ComputedValue");
}
function computedDecorator(target, key, baseDescriptor, options) {
if (arguments.length === 1) {
var options_1 = target;
return function (target, key, baseDescriptor) { return computedDecorator.call(null, target, key, baseDescriptor, options_1); };
}
invariant(baseDescriptor && baseDescriptor.hasOwnProperty("get"), "@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");
assertPropertyConfigurable(target, key);
var descriptor = {};
var getter = baseDescriptor.get;
invariant(typeof target === "object", "The @observable decorator can only be used on objects", key);
invariant(typeof getter === "function", "@observable expects a getter function if used on a property.", key);
invariant(!baseDescriptor.set, "@observable properties cannot have a setter.", key);
invariant(getter.length === 0, "@observable getter functions should not take arguments.", key);
descriptor.configurable = true;
descriptor.enumerable = false;
descriptor.get = function () {
setObservableObjectProperty(asObservableObject(this, undefined, ValueMode.Recursive), key, options && options.asStructure === true ? asStructure(getter) : getter);
return this[key];
};
descriptor.set = throwingComputedValueSetter;
if (!baseDescriptor) {
Object.defineProperty(target, key, descriptor);
}
else {
return descriptor;
}
}
function throwingComputedValueSetter() {
throw new Error("[ComputedValue] It is not allowed to assign new values to computed properties.");
}
function createTransformer(transformer, onCleanup) {
invariant(typeof transformer === "function" && transformer.length === 1, "createTransformer expects a function that accepts one argument");
var objectCache = {};
var Transformer = (function (_super) {
__extends(Transformer, _super);
function Transformer(sourceIdentifier, sourceObject) {
_super.call(this, function () { return transformer(sourceObject); }, null, false, "Transformer-" + transformer.name + "-" + sourceIdentifier);
this.sourceIdentifier = sourceIdentifier;
this.sourceObject = sourceObject;
}
Transformer.prototype.onBecomeUnobserved = function () {
var lastValue = this.value;
_super.prototype.onBecomeUnobserved.call(this);
delete objectCache[this.sourceIdentifier];
if (onCleanup)
onCleanup(lastValue, this.sourceObject);
};
return Transformer;
})(ComputedValue);
return function (object) {
var identifier = getMemoizationId(object);
var reactiveTransformer = objectCache[identifier];
if (reactiveTransformer)
return reactiveTransformer.get();
reactiveTransformer = objectCache[identifier] = new Transformer(identifier, object);
return reactiveTransformer.get();
};
}
exports.createTransformer = createTransformer;
function getMemoizationId(object) {
if (object === null || typeof object !== "object")
throw new Error("[mobx] transform expected some kind of object, got: " + object);
var tid = object.$transformId;
if (tid === undefined) {
tid = getNextId();
Object.defineProperty(object, '$transformId', {
configurable: true,
writable: true,
enumerable: false,
value: tid
});
}
return tid;
}
function expr(expr, scope) {
if (!isComputingDerivation())
console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions.");
return computed(expr, scope).get();
}
exports.expr = expr;
function extendObservable(target) {
var properties = [];
for (var _i = 1; _i < arguments.length; _i++) {
properties[_i - 1] = arguments[_i];
}
invariant(arguments.length >= 2, "extendObservable expected 2 or more arguments");
invariant(typeof target === "object", "extendObservable expects an object as first argument");
invariant(!(target instanceof ObservableMap), "extendObservable should not be used on maps, use map.merge instead");
properties.forEach(function (propSet) {
invariant(typeof propSet === "object", "all arguments of extendObservable should be objects");
extendObservableHelper(target, propSet, ValueMode.Recursive, null);
});
return target;
}
exports.extendObservable = extendObservable;
function extendObservableHelper(target, properties, mode, name) {
var adm = asObservableObject(target, name, mode);
for (var key in properties)
if (properties.hasOwnProperty(key)) {
if (target === properties && !isPropertyConfigurable(target, key))
continue;
setObservableObjectProperty(adm, key, properties[key]);
}
return target;
}
function allowStateChanges(allowStateChanges, func) {
var prev = globalState.allowStateChanges;
globalState.allowStateChanges = allowStateChanges;
var res = func();
globalState.allowStateChanges = prev;
return res;
}
var transitionTracker = null;
function reportTransition(node, state, changed) {
if (changed === void 0) { changed = false; }
if (transitionTracker)
transitionTracker.emit({
id: node.id,
name: node.name + "@" + node.id,
node: node, state: state, changed: changed
});
}
function getDependencyTree(thing) {
return nodeToDependencyTree(thing);
}
function nodeToDependencyTree(node) {
var result = {
id: node.id,
name: node.name + "@" + node.id
};
if (node.observing && node.observing.length)
result.dependencies = unique(node.observing).map(nodeToDependencyTree);
return result;
}
function getObserverTree(thing) {
return nodeToObserverTree(thing);
}
function nodeToObserverTree(node) {
var result = {
id: node.id,
name: node.name + "@" + node.id
};
if (node.observers && node.observers.length)
result.observers = unique(node.observers).map(nodeToObserverTree);
return result;
}
function createConsoleReporter(extensive) {
var lines = [];
var scheduled = false;
return function (line) {
if (extensive || line.changed)
lines.push(line);
if (!scheduled) {
scheduled = true;
setTimeout(function () {
console[console["table"] ? "table" : "dir"](lines);
lines = [];
scheduled = false;
}, 1);
}
};
}
function trackTransitions(extensive, onReport) {
if (extensive === void 0) { extensive = false; }
if (!transitionTracker)
transitionTracker = new SimpleEventEmitter();
var reporter = onReport
? function (line) {
if (extensive || line.changed)
onReport(line);
}
: createConsoleReporter(extensive);
var disposer = transitionTracker.on(reporter);
return once(function () {
disposer();
if (transitionTracker.listeners.length === 0)
transitionTracker = null;
});
}
function isObservable(value, property) {
if (value === null || value === undefined)
return false;
if (property !== undefined) {
if (value instanceof ObservableMap || value instanceof ObservableArray)
throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");
else if (isObservableObject(value)) {
var o = value.$mobx;
return o.values && !!o.values[property];
}
return false;
}
return !!value.$mobx || value instanceof Atom || value instanceof Reaction || value instanceof ComputedValue;
}
exports.isObservable = isObservable;
function observableDecorator(target, key, baseDescriptor) {
invariant(arguments.length >= 2 && arguments.length <= 3, "Illegal decorator config", key);
assertPropertyConfigurable(target, key);
if (baseDescriptor && baseDescriptor.hasOwnProperty("get")) {
deprecated("Using @observable on computed values is deprecated. Use @computed instead.");
return computed.apply(null, arguments);
}
var descriptor = {};
var baseValue = undefined;
if (baseDescriptor) {
if (baseDescriptor.hasOwnProperty("value"))
baseValue = baseDescriptor.value;
else if (baseDescriptor.initializer) {
baseValue = baseDescriptor.initializer();
if (typeof baseValue === "function")
baseValue = asReference(baseValue);
}
}
invariant(typeof target === "object", "The @observable decorator can only be used on objects", key);
descriptor.configurable = true;
descriptor.enumerable = true;
descriptor.get = function () {
var _this = this;
allowStateChanges(true, function () {
setObservableObjectProperty(asObservableObject(_this, undefined, ValueMode.Recursive), key, baseValue);
});
return this[key];
};
descriptor.set = function (value) {
setObservableObjectProperty(asObservableObject(this, undefined, ValueMode.Recursive), key, typeof value === "function" ? asReference(value) : value);
};
if (!baseDescriptor) {
Object.defineProperty(target, key, descriptor);
}
else {
return descriptor;
}
}
function observable(v, keyOrScope) {
if (typeof arguments[1] === "string")
return observableDecorator.apply(null, arguments);
invariant(arguments.length === 1 || arguments.length === 2, "observable expects one or two arguments");
if (isObservable(v))
return v;
var _a = getValueModeFromValue(v, ValueMode.Recursive), mode = _a[0], value = _a[1];
var sourceType = mode === ValueMode.Reference ? ValueType.Reference : getTypeOfValue(value);
switch (sourceType) {
case ValueType.Array:
case ValueType.PlainObject:
return makeChildObservable(value, mode);
case ValueType.Reference:
case ValueType.ComplexObject:
return new ObservableValue(value, mode);
case ValueType.ComplexFunction:
throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");
case ValueType.ViewFunction:
deprecated("Use `computed(expr)` instead of `observable(expr)`");
return computed(v, keyOrScope);
}
invariant(false, "Illegal State");
}
exports.observable = observable;
var ValueType;
(function (ValueType) {
ValueType[ValueType["Reference"] = 0] = "Reference";
ValueType[ValueType["PlainObject"] = 1] = "PlainObject";
ValueType[ValueType["ComplexObject"] = 2] = "ComplexObject";
ValueType[ValueType["Array"] = 3] = "Array";
ValueType[ValueType["ViewFunction"] = 4] = "ViewFunction";
ValueType[ValueType["ComplexFunction"] = 5] = "ComplexFunction";
})(ValueType || (ValueType = {}));
function getTypeOfValue(value) {
if (value === null || value === undefined)
return ValueType.Reference;
if (typeof value === "function")
return value.length ? ValueType.ComplexFunction : ValueType.ViewFunction;
if (Array.isArray(value) || value instanceof ObservableArray)
return ValueType.Array;
if (typeof value === "object")
return isPlainObject(value) ? ValueType.PlainObject : ValueType.ComplexObject;
return ValueType.Reference;
}
function observe(thing, propOrCb, cbOrFire, fireImmediately) {
if (typeof cbOrFire === "function")
return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately);
else
return observeObservable(thing, propOrCb, cbOrFire);
}
exports.observe = observe;
function observeObservable(thing, listener, fireImmediately) {
if (isObservableArray(thing))
return thing.observe(listener);
if (isObservableMap(thing))
return thing.observe(listener);
if (isObservableObject(thing))
return observeObservableObject(thing, listener, fireImmediately);
if (thing instanceof ObservableValue || thing instanceof ComputedValue)
return thing.observe(listener, fireImmediately);
if (isPlainObject(thing))
return observeObservable(observable(thing), listener, fireImmediately);
invariant(false, "first argument of observe should be some observable value or plain object");
}
function observeObservableProperty(thing, property, listener, fireImmediately) {
var propError = "[mobx.observe] the provided observable map has no key with name: " + property;
if (isObservableMap(thing)) {
if (!thing._has(property))
throw new Error(propError);
return observe(thing._data[property], listener);
}
if (isObservableObject(thing)) {
if (!isObservable(thing, property))
throw new Error(propError);
return observe(thing.$mobx.values[property], listener, fireImmediately);
}
if (isPlainObject(thing)) {
extendObservable(thing, {
property: thing[property]
});
return observeObservableProperty(thing, property, listener, fireImmediately);
}
invariant(false, "first argument of observe should be an (observable)object or observableMap if a property name is given");
}
function toJSON(source, detectCycles, __alreadySeen) {
if (detectCycles === void 0) { detectCycles = true; }
if (__alreadySeen === void 0) { __alreadySeen = null; }
function cache(value) {
if (detectCycles)
__alreadySeen.push([source, value]);
return value;
}
if (detectCycles && __alreadySeen === null)
__alreadySeen = [];
if (detectCycles && source !== null && typeof source === "object") {
for (var i = 0, l = __alreadySeen.length; i < l; i++)
if (__alreadySeen[i][0] === source)
return __alreadySeen[i][1];
}
if (!source)
return source;
if (Array.isArray(source) || source instanceof ObservableArray) {
var res = cache([]);
res.push.apply(res, source.map(function (value) { return toJSON(value, detectCycles, __alreadySeen); }));
return res;
}
if (source instanceof ObservableMap) {
var res = cache({});
source.forEach(function (value, key) { return res[key] = toJSON(value, detectCycles, __alreadySeen); });
return res;
}
if (typeof source === "object" && isPlainObject(source)) {
var res = cache({});
for (var key in source)
if (source.hasOwnProperty(key))
res[key] = toJSON(source[key], detectCycles, __alreadySeen);
return res;
}
if (isObservable(source) && source.$mobx instanceof ObservableValue)
return toJSON(source(), detectCycles, __alreadySeen);
return source;
}
exports.toJSON = toJSON;
function propagateAtomReady(atom) {
invariant(atom.isDirty, "atom not dirty");
atom.isDirty = false;
reportTransition(atom, "READY", true);
propagateReadiness(atom, true);
}
var Atom = (function () {
function Atom(name, onBecomeObserved, onBecomeUnobserved) {
if (name === void 0) { name = "Atom"; }
if (onBecomeObserved === void 0) { onBecomeObserved = noop; }
if (onBecomeUnobserved === void 0) { onBecomeUnobserved = noop; }
this.name = name;
this.onBecomeObserved = onBecomeObserved;
this.onBecomeUnobserved = onBecomeUnobserved;
this.id = getNextId();
this.isDirty = false;
this.staleObservers = [];
this.observers = [];
}
Atom.prototype.reportObserved = function () {
reportObserved(this);
};
Atom.prototype.reportChanged = function () {
if (!this.isDirty) {
this.reportStale();
this.reportReady();
}
};
Atom.prototype.reportStale = function () {
if (!this.isDirty) {
this.isDirty = true;
reportTransition(this, "STALE");
propagateStaleness(this);
}
};
Atom.prototype.reportReady = function () {
invariant(this.isDirty, "atom not dirty");
if (globalState.inTransaction > 0)
globalState.changedAtoms.push(this);
else {
propagateAtomReady(this);
runReactions();
}
};
Atom.prototype.toString = function () {
return this.name + "@" + this.id;
};
return Atom;
})();
exports.Atom = Atom;
var ComputedValue = (function () {
function ComputedValue(derivation, scope, compareStructural, name) {
var _this = this;
if (name === void 0) { name = "ComputedValue"; }
this.derivation = derivation;
this.scope = scope;
this.compareStructural = compareStructural;
this.name = name;
this.id = getNextId();
this.isLazy = true;
this.isComputing = false;
this.staleObservers = [];
this.observers = [];
this.observing = [];
this.dependencyChangeCount = 0;
this.dependencyStaleCount = 0;
this.value = undefined;
this.peek = function () {
_this.isComputing = true;
globalState.isComputingComputedValue++;
var prevAllowStateChanges = globalState.allowStateChanges;
globalState.allowStateChanges = false;
var res = derivation.call(scope);
globalState.allowStateChanges = prevAllowStateChanges;
globalState.isComputingComputedValue--;
_this.isComputing = false;
return res;
};
}
ComputedValue.prototype.onBecomeObserved = function () {
};
ComputedValue.prototype.onBecomeUnobserved = function () {
for (var i = 0, l = this.observing.length; i < l; i++)
removeObserver(this.observing[i], this);
this.observing = [];
this.isLazy = true;
this.value = undefined;
};
ComputedValue.prototype.onDependenciesReady = function () {
var changed = this.trackAndCompute();
reportTransition(this, "READY", changed);
return changed;
};
ComputedValue.prototype.get = function () {
invariant(!this.isComputing, "Cycle detected", this.derivation);
reportObserved(this);
if (this.dependencyStaleCount > 0) {
return this.peek();
}
if (this.isLazy) {
if (isComputingDerivation()) {
this.isLazy = false;
this.trackAndCompute();
}
else {
return this.peek();
}
}
return this.value;
};
ComputedValue.prototype.set = function (_) {
throw new Error("[ComputedValue '" + name + "'] It is not possible to assign a new value to a computed value.");
};
ComputedValue.prototype.trackAndCompute = function () {
var oldValue = this.value;
this.value = trackDerivedFunction(this, this.peek);
return valueDidChange(this.compareStructural, this.value, oldValue);
};
ComputedValue.prototype.observe = function (listener, fireImmediately) {
var _this = this;
var firstTime = true;
var prevValue = undefined;
return autorun(function () {
var newValue = _this.get();
if (!firstTime || fireImmediately) {
listener(newValue, prevValue);
}
firstTime = false;
prevValue = newValue;
});
};
ComputedValue.prototype.toString = function () {
return this.name + "@" + this.id + "[" + this.derivation.toString() + "]";
};
return ComputedValue;
})();
function isComputingDerivation() {
return globalState.derivationStack.length > 0;
}
function checkIfStateModificationsAreAllowed() {
invariant(globalState.allowStateChanges, "It is not allowed to change the state when a computed value is being evaluated. Use 'autorun' to create reactive functions with side-effects. Or use 'extras.allowStateChanges(true, block)' to supress this message.");
}
function notifyDependencyStale(derivation) {
if (++derivation.dependencyStaleCount === 1) {
reportTransition(derivation, "STALE");
propagateStaleness(derivation);
}
}
function notifyDependencyReady(derivation, dependencyDidChange) {
invariant(derivation.dependencyStaleCount > 0, "unexpected ready notification");
if (dependencyDidChange)
derivation.dependencyChangeCount += 1;
if (--derivation.dependencyStaleCount === 0) {
if (derivation.dependencyChangeCount > 0) {
derivation.dependencyChangeCount = 0;
reportTransition(derivation, "PENDING");
var changed = derivation.onDependenciesReady();
propagateReadiness(derivation, changed);
}
else {
reportTransition(derivation, "READY", false);
propagateReadiness(derivation, false);
}
}
}
function trackDerivedFunction(derivation, f) {
var prevObserving = derivation.observing;
derivation.observing = [];
globalState.derivationStack.push(derivation);
var result = f();
bindDependencies(derivation, prevObserving);
return result;
}
function bindDependencies(derivation, prevObserving) {
globalState.derivationStack.length -= 1;
var _a = quickDiff(derivation.observing, prevObserving), added = _a[0], removed = _a[1];
for (var i = 0, l = added.length; i < l; i++) {
var dependency = added[i];
invariant(!findCycle(derivation, dependency), "Cycle detected", derivation);
addObserver(added[i], derivation);
}
for (var i = 0, l = removed.length; i < l; i++)
removeObserver(removed[i], derivation);
}
function findCycle(needle, node) {
var obs = node.observing;
if (obs === undefined)
return false;
if (obs.indexOf(node) !== -1)
return true;
for (var l = obs.length, i = 0; i < l; i++)
if (findCycle(needle, obs[i]))
return true;
return false;
}
var MobXGlobals = (function () {
function MobXGlobals() {
this.version = 1;
this.derivationStack = [];
this.mobxGuid = 0;
this.inTransaction = 0;
this.inUntracked = 0;
this.isRunningReactions = false;
this.isComputingComputedValue = 0;
this.changedAtoms = [];
this.pendingReactions = [];
this.allowStateChanges = true;
}
return MobXGlobals;
})();
var globalState = (function () {
var res = new MobXGlobals();
if (global.__mobservableTrackingStack || global.__mobservableViewStack)
throw new Error("[mobx] An incompatible version of mobservable is already loaded.");
if (global.__mobxGlobal && global.__mobxGlobal.version !== res.version)
throw new Error("[mobx] An incompatible version of mobx is already loaded.");
if (global.__mobxGlobal)
return global.__mobxGlobal;
return global.__mobxGlobal = res;
})();
function getNextId() {
return ++globalState.mobxGuid;
}
function registerGlobals() {
}
function resetGlobalState() {
var defaultGlobals = new MobXGlobals();
for (var key in defaultGlobals)
globalState[key] = defaultGlobals[key];
}
function addObserver(observable, node) {
var obs = observable.observers, l = obs.length;
obs[l] = node;
if (l === 0)
observable.onBecomeObserved();
}
function removeObserver(observable, node) {
var obs = observable.observers, idx = obs.indexOf(node);
if (idx !== -1)
obs.splice(idx, 1);
if (obs.length === 0)
observable.onBecomeUnobserved();
}
function reportObserved(observable) {
if (globalState.inUntracked > 0)
return;
var derivationStack = globalState.derivationStack;
var l = derivationStack.length;
if (l > 0) {
var deps = derivationStack[l - 1].observing, depslength = deps.length;
if (deps[depslength - 1] !== observable && deps[depslength - 2] !== observable)
deps[depslength] = observable;
}
}
function propagateStaleness(observable) {
var os = observable.observers.slice();
os.forEach(notifyDependencyStale);
observable.staleObservers = observable.staleObservers.concat(os);
}
function propagateReadiness(observable, valueDidActuallyChange) {
observable.staleObservers.splice(0).forEach(function (o) { return notifyDependencyReady(o, valueDidActuallyChange); });
}
function untracked(action) {
deprecated("This feature is experimental and might be removed in a future minor release. Please report if you use this feature in production: https://github.com/mobxjs/mobx/issues/49");
globalState.inUntracked++;
var res = action();
globalState.inUntracked--;
return res;
}
exports.untracked = untracked;
var Reaction = (function () {
function Reaction(name, onInvalidate) {
if (name === void 0) { name = "Reaction"; }
this.name = name;
this.onInvalidate = onInvalidate;
this.id = getNextId();
this.staleObservers = EMPTY_ARRAY;
this.observers = EMPTY_ARRAY;
this.observing = [];
this.dependencyChangeCount = 0;
this.dependencyStaleCount = 0;
this.isDisposed = false;
this._isScheduled = false;
}
Reaction.prototype.onBecomeObserved = function () {
};
Reaction.prototype.onBecomeUnobserved = function () {
};
Reaction.prototype.onDependenciesReady = function () {
if (!this._isScheduled) {
this._isScheduled = true;
globalState.pendingReactions.push(this);
}
return false;
};
Reaction.prototype.isScheduled = function () {
return this.dependencyStaleCount > 0 || this._isScheduled;
};
Reaction.prototype.runReaction = function () {
if (!this.isDisposed) {
this._isScheduled = false;
this.onInvalidate();
reportTransition(this, "READY", true);
}
};
Reaction.prototype.track = function (fn) {
trackDerivedFunction(this, fn);
};
Reaction.prototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var deps = this.observing.splice(0);
for (var i = 0, l = deps.length; i < l; i++)
removeObserver(deps[i], this);
}
};
Reaction.prototype.getDisposer = function () {
var r = this.dispose.bind(this);
r.$mobx = this;
return r;
};
Reaction.prototype.toString = function () {
return "Reaction[" + this.name + "]";
};
return Reaction;
})();
exports.Reaction = Reaction;
var MAX_REACTION_ITERATIONS = 100;
function runReactions() {
if (globalState.isRunningReactions)
return;
globalState.isRunningReactions = true;
var pr = globalState.pendingReactions;
var iterations = 0;
while (pr.length) {
if (++iterations === MAX_REACTION_ITERATIONS)
throw new Error("Reaction doesn't converge to a stable state. Probably there is a cycle in the reactive function: " + pr[0].toString());
var rs = pr.splice(0);
for (var i = 0, l = rs.length; i < l; i++)
rs[i].runReaction();
}
globalState.isRunningReactions = false;
}
function transaction(action, thisArg) {
globalState.inTransaction += 1;
var res = action.call(thisArg);
if (--globalState.inTransaction === 0) {
var values = globalState.changedAtoms.splice(0);
for (var i = 0, l = values.length; i < l; i++)
propagateAtomReady(values[i]);
runReactions();
}
return res;
}
exports.transaction = transaction;
var ValueMode;
(function (ValueMode) {
ValueMode[ValueMode["Recursive"] = 0] = "Recursive";
ValueMode[ValueMode["Reference"] = 1] = "Reference";
ValueMode[ValueMode["Structure"] = 2] = "Structure";
ValueMode[ValueMode["Flat"] = 3] = "Flat";
})(ValueMode || (ValueMode = {}));
function asReference(value) {
return new AsReference(value);
}
exports.asReference = asReference;
function asStructure(value) {
return new AsStructure(value);
}
exports.asStructure = asStructure;
function asFlat(value) {
return new AsFlat(value);
}
exports.asFlat = asFlat;
var AsReference = (function () {
function AsReference(value) {
this.value = value;
assertUnwrapped(value, "Modifiers are not allowed to be nested");
}
return AsReference;
})();
var AsStructure = (function () {
function AsStructure(value) {
this.value = value;
assertUnwrapped(value, "Modifiers are not allowed to be nested");
}
return AsStructure;
})();
var AsFlat = (function () {
function AsFlat(value) {
this.value = value;
assertUnwrapped(value, "Modifiers are not allowed to be nested");
}
return AsFlat;
})();
function getValueModeFromValue(value, defaultMode) {
if (value instanceof AsReference)
return [ValueMode.Reference, value.value];
if (value instanceof AsStructure)
return [ValueMode.Structure, value.value];
if (value instanceof AsFlat)
return [ValueMode.Flat, value.value];
return [defaultMode, value];
}
function getValueModeFromModifierFunc(func) {
if (func === asReference)
return ValueMode.Reference;
else if (func === asStructure)
return ValueMode.Structure;
else if (func === asFlat)
return ValueMode.Flat;
invariant(func === undefined, "Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: " + func);
return ValueMode.Recursive;
}
function makeChildObservable(value, parentMode, name) {
var childMode;
if (isObservable(value))
return value;
switch (parentMode) {
case ValueMode.Reference:
return value;
case ValueMode.Flat:
assertUnwrapped(value, "Items inside 'asFlat' canont have modifiers");
childMode = ValueMode.Reference;
break;
case ValueMode.Structure:
assertUnwrapped(value, "Items inside 'asStructure' canont have modifiers");
childMode = ValueMode.Structure;
break;
case ValueMode.Recursive:
_a = getValueModeFromValue(value, ValueMode.Recursive), childMode = _a[0], value = _a[1];
break;
default:
invariant(false, "Illegal State");
}
if (Array.isArray(value) && Object.isExtensible(value))
return createObservableArray(value, childMode, name);
if (isPlainObject(value) && Object.isExtensible(value))
return extendObservableHelper(value, value, childMode, name);
return value;
var _a;
}
function assertUnwrapped(value, message) {
if (value instanceof AsReference || value instanceof AsStructure || value instanceof AsFlat)
throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. " + message);
}
var OBSERVABLE_ARRAY_BUFFER_SIZE = 0;
var StubArray = (function () {
function StubArray() {
}
return StubArray;
})();
StubArray.prototype = [];
function getArrayLength(adm) {
adm.atom.reportObserved();
return adm.values.length;
}
function setArrayLength(adm, newLength) {
if (typeof newLength !== "number" || newLength < 0)
throw new Error("[mobx.array] Out of range: " + newLength);
var currentLength = adm.values.length;
if (newLength === currentLength)
return;
else if (newLength > currentLength)
spliceWithArray(adm, currentLength, 0, new Array(newLength - currentLength));
else
spliceWithArray(adm, newLength, currentLength - newLength);
}
function updateArrayLength(adm, oldLength, delta) {
if (oldLength !== adm.lastKnownLength)
throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed. Did you use peek() to change it?");
checkIfStateModificationsAreAllowed();
adm.lastKnownLength += delta;
if (delta > 0 && oldLength + delta > OBSERVABLE_ARRAY_BUFFER_SIZE)
reserveArrayBuffer(oldLength + delta);
}
function spliceWithArray(adm, index, deleteCount, newItems) {
var length = adm.values.length;
if ((newItems === undefined || newItems.length === 0) && (deleteCount === 0 || length === 0))
return [];
if (index === undefined)
index = 0;
else if (index > length)
index = length;
else if (index < 0)
index = Math.max(0, length + index);
if (arguments.length === 2)
deleteCount = length - index;
else if (deleteCount === undefined || deleteCount === null)
deleteCount = 0;
else
deleteCount = Math.max(0, Math.min(deleteCount, length - index));
if (newItems === undefined)
newItems = EMPTY_ARRAY;
else
newItems = newItems.map(adm.makeChildReactive);
var lengthDelta = newItems.length - deleteCount;
updateArrayLength(adm, length, lengthDelta);
var res = (_a = adm.values).splice.apply(_a, [index, deleteCount].concat(newItems));
notifyArraySplice(adm, index, res, newItems);
return res;
var _a;
}
function makeReactiveArrayItem(value) {
assertUnwrapped(value, "Array values cannot have modifiers");
if (this.mode === ValueMode.Flat || this.mode === ValueMode.Reference)
return value;
return makeChildObservable(value, this.mode, this.atom.name + "@" + this.atom.id + " / ArrayEntry");
}
function notifyArrayChildUpdate(adm, index, oldValue) {
adm.atom.reportChanged();
if (adm.changeEvent)
adm.changeEvent.emit({ object: adm.array, type: "update", index: index, oldValue: oldValue });
}
function notifyArraySplice(adm, index, deleted, added) {
if (deleted.length === 0 && added.length === 0)
return;
adm.atom.reportChanged();
if (adm.changeEvent)
adm.changeEvent.emit({ object: adm.array, type: "splice", index: index, addedCount: added.length, removed: deleted });
}
var ObservableArray = (function (_super) {
__extends(ObservableArray, _super);
function ObservableArray(initialValues, mode, name) {
_super.call(this);
var adm = this.$mobx = {
atom: new Atom(name || "ObservableArray"),
values: undefined,
changeEvent: undefined,
lastKnownLength: 0,
mode: mode,
array: this,
makeChildReactive: function (v) { return makeReactiveArrayItem.call(adm, v); }
};
Object.defineProperty(this, "$mobx", {
enumerable: false,
configurable: false,
writable: false
});
if (initialValues && initialValues.length) {
updateArrayLength(adm, 0, initialValues.length);
adm.values = initialValues.map(adm.makeChildReactive);
}
else
adm.values = [];
}
ObservableArray.prototype.observe = function (listener, fireImmediately) {
if (fireImmediately === void 0) { fireImmediately = false; }
if (this.$mobx.changeEvent === undefined)
this.$mobx.changeEvent = new SimpleEventEmitter();
if (fireImmediately)
listener({ object: this, type: "splice", index: 0, addedCount: this.$mobx.values.length, removed: [] });
return this.$mobx.changeEvent.on(listener);
};
ObservableArray.prototype.clear = function () {
return this.splice(0);
};
ObservableArray.prototype.replace = function (newItems) {
return spliceWithArray(this.$mobx, 0, this.$mobx.values.length, newItems);
};
ObservableArray.prototype.toJSON = function () {
this.$mobx.atom.reportObserved();
return this.$mobx.values.slice();
};
ObservableArray.prototype.peek = function () {
return this.$mobx.values;
};
ObservableArray.prototype.find = function (predicate, thisArg, fromIndex) {
if (fromIndex === void 0) { fromIndex = 0; }
this.$mobx.atom.reportObserved();
var items = this.$mobx.values, l = items.length;
for (var i = fromIndex; i < l; i++)
if (predicate.call(thisArg, items[i], i, this))
return items[i];
return null;
};
ObservableArray.prototype.splice = function (index, deleteCount) {
var newItems = [];
for (var _i = 2; _i < arguments.length; _i++) {
newItems[_i - 2] = arguments[_i];
}
switch (arguments.length) {
case 0:
return [];
case 1:
return spliceWithArray(this.$mobx, index);
case 2:
return spliceWithArray(this.$mobx, index, deleteCount);
}
return spliceWithArray(this.$mobx, index, deleteCount, newItems);
};
ObservableArray.prototype.push = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i - 0] = arguments[_i];
}
spliceWithArray(this.$mobx, this.$mobx.values.length, 0, items);
return this.$mobx.values.length;
};
ObservableArray.prototype.pop = function () {
return this.splice(Math.max(this.$mobx.values.length - 1, 0), 1)[0];
};
ObservableArray.prototype.shift = function () {
return this.splice(0, 1)[0];
};
ObservableArray.prototype.unshift = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i - 0] = arguments[_i];
}
spliceWithArray(this.$mobx, 0, 0, items);
return this.$mobx.values.length;
};
ObservableArray.prototype.reverse = function () {
this.$mobx.atom.reportObserved();
var clone = this.slice();
return clone.reverse.apply(clone, arguments);
};
ObservableArray.prototype.sort = function (compareFn) {
this.$mobx.atom.reportObserved();
var clone = this.slice();
return clone.sort.apply(clone, arguments);
};
ObservableArray.prototype.remove = function (value) {
var idx = this.$mobx.values.indexOf(value);
if (idx > -1) {
this.splice(idx, 1);
return true;
}
return false;
};
ObservableArray.prototype.toString = function () {
return "[mobx.array] " + Array.prototype.toString.apply(this.$mobx.values, arguments);
};
ObservableArray.prototype.toLocaleString = function () {
return "[mobx.array] " + Array.prototype.toLocaleString.apply(this.$mobx.values, arguments);
};
return ObservableArray;
})(StubArray);
makeNonEnumerable(ObservableArray.prototype, [
"constructor",
"clear",
"find",
"observe",
"pop",
"peek",
"push",
"remove",
"replace",
"reverse",
"shift",
"sort",
"splice",
"split",
"toJSON",
"toLocaleString",
"toString",
"unshift"
]);
Object.defineProperty(ObservableArray.prototype, "length", {
enumerable: false,
configurable: true,
get: function () {
return getArrayLength(this.$mobx);
},
set: function (newLength) {
setArrayLength(this.$mobx, newLength);
}
});
[
"concat",
"every",
"filter",
"forEach",
"indexOf",
"join",
"lastIndexOf",
"map",
"reduce",
"reduceRight",
"slice",
"some"
].forEach(function (funcName) {
var baseFunc = Array.prototype[funcName];
Object.defineProperty(ObservableArray.prototype, funcName, {
configurable: false,
writable: true,
enumerable: false,
value: function () {
this.$mobx.atom.reportObserved();
return baseFunc.apply(this.$mobx.values, arguments);
}
});
});
function createArrayBufferItem(index) {
Object.defineProperty(ObservableArray.prototype, "" + index, {
enumerable: false,
configurable: false,
set: function (value) {
var impl = this.$mobx;
var values = impl.values;
assertUnwrapped(value, "Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array)).");
if (index < values.length) {
checkIfStateModificationsAreAllowed();
var oldValue = values[index];
var changed = impl.mode === ValueMode.Structure ? !deepEquals(oldValue, value) : oldValue !== value;
if (changed) {
values[index] = impl.makeChildReactive(value);
notifyArrayChildUpdate(impl, index, oldValue);
}
}
else if (index === values.length)
spliceWithArray(impl, index, 0, [value]);
else
throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length);
},
get: function () {
var impl = this.$mobx;
if (impl && index < impl.values.length) {
impl.atom.reportObserved();
return impl.values[index];
}
return undefined;
}
});
}
function reserveArrayBuffer(max) {
for (var index = OBSERVABLE_ARRAY_BUFFER_SIZE; index < max; index++)
createArrayBufferItem(index);
OBSERVABLE_ARRAY_BUFFER_SIZE = max;
}
reserveArrayBuffer(1000);
function createObservableArray(initialValues, mode, name) {
return new ObservableArray(initialValues, mode, name);
}
function fastArray(initialValues) {
deprecated("fastArray is deprecated. Please use `observable(asFlat([]))`");
return createObservableArray(initialValues, ValueMode.Flat, null);
}
exports.fastArray = fastArray;
function isObservableArray(thing) {
return thing instanceof ObservableArray;
}
exports.isObservableArray = isObservableArray;
var ObservableMapMarker = {};
var ObservableMap = (function () {
function ObservableMap(initialData, valueModeFunc) {
var _this = this;
this.$mobx = ObservableMapMarker;
this._data = {};
this._hasMap = {};
this._events = undefined;
this.name = "ObservableMap";
this.id = getNextId();
this._keys = new ObservableArray(null, ValueMode.Reference, this.name + "@" + this.id + " / keys()");
this._valueMode = getValueModeFromModifierFunc(valueModeFunc);
if (isPlainObject(initialData))
this.merge(initialData);
else if (Array.isArray(initialData))
initialData.forEach(function (_a) {
var key = _a[0], value = _a[1];
return _this.set(key, value);
});
}
ObservableMap.prototype._has = function (key) {
return typeof this._data[key] !== "undefined";
};
ObservableMap.prototype.has = function (key) {
if (!this.isValidKey(key))
return false;
if (this._hasMap[key])
return this._hasMap[key].get();
return this._updateHasMapEntry(key, false).get();
};
ObservableMap.prototype.set = function (key, value) {
var _this = this;
this.assertValidKey(key);
assertUnwrapped(value, "[mobx.map.set] Expected unwrapped value to be inserted to key '" + key + "'. If you need to use modifiers pass them as second argument to the constructor");
if (this._has(key)) {
var oldValue = this._data[key].value;
var changed = this._data[key].set(value);
if (changed && this._events) {
this._events.emit({
type: "update",
object: this,
name: key,
oldValue: oldValue
});
}
}
else {
transaction(function () {
_this._data[key] = new ObservableValue(value, _this._valueMode, _this.name + "@" + _this.id + " / Entry \"" + key + "\"");
_this._updateHasMapEntry(key, true);
_this._keys.push(key);
});
this._events && this._events.emit({
type: "add",
object: this,
name: key
});
}
};
ObservableMap.prototype.delete = function (key) {
var _this = this;
if (this._has(key)) {
var oldValue = this._data[key].value;
transaction(function () {
_this._keys.remove(key);
_this._updateHasMapEntry(key, false);
var observable = _this._data[key];
observable.set(undefined);
_this._data[key] = undefined;
});
this._events && this._events.emit({
type: "delete",
object: this,
name: key,
oldValue: oldValue
});
}
};
ObservableMap.prototype._updateHasMapEntry = function (key, value) {
var entry = this._hasMap[key];
if (entry) {
entry.set(value);
}
else {
entry = this._hasMap[key] = new ObservableValue(value, ValueMode.Reference, this.name + "@" + this.id + " / Contains \"" + key + "\"");
}
return entry;
};
ObservableMap.prototype.get = function (key) {
if (this.has(key))
return this._data[key].get();
return undefined;
};
ObservableMap.prototype.keys = function () {
return this._keys.slice();
};
ObservableMap.prototype.values = function () {
return this.keys().map(this.get, this);
};
ObservableMap.prototype.entries = function () {
var _this = this;
return this.keys().map(function (key) { return [key, _this.get(key)]; });
};
ObservableMap.prototype.forEach = function (callback, thisArg) {
var _this = this;
this.keys().forEach(function (key) { return callback.call(thisArg, _this.get(key), key); });
};
ObservableMap.prototype.merge = function (other) {
var _this = this;
transaction(function () {
if (other instanceof ObservableMap)
other.keys().forEach(function (key) { return _this.set(key, other.get(key)); });
else
Object.keys(other).forEach(function (key) { return _this.set(key, other[key]); });
});
return this;
};
ObservableMap.prototype.clear = function () {
var _this = this;
transaction(function () {
_this.keys().forEach(_this.delete, _this);
});
};
Object.defineProperty(ObservableMap.prototype, "size", {
get: function () {
return this._keys.length;
},
enumerable: true,
configurable: true
});
ObservableMap.prototype.toJs = function () {
var _this = this;
var res = {};
this.keys().forEach(function (key) { return res[key] = _this.get(key); });
return res;
};
ObservableMap.prototype.isValidKey = function (key) {
if (key === null || key === undefined)
return false;
if (typeof key !== "string" && typeof key !== "number")
return false;
return true;
};
ObservableMap.prototype.assertValidKey = function (key) {
if (!this.isValidKey(key))
throw new Error("[mobx.map] Invalid key: '" + key + "'");
};
ObservableMap.prototype.toString = function () {
var _this = this;
return "[mobx.map { " + this.keys().map(function (key) { return (key + ": " + ("" + _this.get(key))); }).join(", ") + " }]";
};
ObservableMap.prototype.observe = function (callback) {
if (!this._events)
this._events = new SimpleEventEmitter();
return this._events.on(callback);
};
return ObservableMap;
})();
exports.ObservableMap = ObservableMap;
function map(initialValues, valueModifier) {
return new ObservableMap(initialValues, valueModifier);
}
exports.map = map;
function isObservableMap(thing) {
return thing instanceof ObservableMap;
}
exports.isObservableMap = isObservableMap;
var ObservableObjectMarker = {};
function asObservableObject(target, name, mode) {
if (name === void 0) { name = "ObservableObject"; }
if (mode === void 0) { mode = ValueMode.Recursive; }
if (target.$mobx) {
if (target.$mobx.type !== ObservableObjectMarker)
throw new Error("The given object is observable but not an observable object");
return target.$mobx;
}
var adm = {
type: ObservableObjectMarker,
values: {},
events: undefined,
id: getNextId(),
target: target, name: name, mode: mode
};
Object.defineProperty(target, "$mobx", {
enumerable: false,
configurable: false,
writable: false,
value: adm
});
return adm;
}
function setObservableObjectProperty(adm, propName, value) {
if (adm.values[propName])
adm.target[propName] = value;
else
defineObservableProperty(adm, propName, value);
}
function defineObservableProperty(adm, propName, value) {
assertPropertyConfigurable(adm.target, propName);
var observable;
var name = adm.name + "@" + adm.id + " / Prop \"" + propName + "\"";
var isComputed = true;
if (typeof value === "function" && value.length === 0)
observable = new ComputedValue(value, adm.target, false, name);
else if (value instanceof AsStructure && typeof value.value === "function" && value.value.length === 0)
observable = new ComputedValue(value.value, adm.target, true, name);
else {
isComputed = false;
observable = new ObservableValue(value, adm.mode, name);
}
adm.values[propName] = observable;
Object.defineProperty(adm.target, propName, {
configurable: true,
enumerable: !isComputed,
get: function () {
return observable.get();
},
set: isComputed
? throwingComputedValueSetter
: function (newValue) {
var oldValue = observable.value;
if (observable.set(newValue) && adm.events !== undefined) {
adm.events.emit({
type: "update",
object: this,
name: propName,
oldValue: oldValue
});
}
}
});
if (adm.events !== undefined) {
adm.events.emit({
type: "add",
object: adm.target,
name: propName
});
}
;
}
function observeObservableObject(object, callback, fireImmediately) {
invariant(isObservableObject(object), "Expected observable object");
invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects.");
var adm = object.$mobx;
if (adm.events === undefined)
adm.events = new SimpleEventEmitter();
return object.$mobx.events.on(callback);
}
function isObservableObject(thing) {
return thing && thing.$mobx && thing.$mobx.type === ObservableObjectMarker;
}
exports.isObservableObject = isObservableObject;
var ObservableValue = (function (_super) {
__extends(ObservableValue, _super);
function ObservableValue(value, mode, name) {
if (name === void 0) { name = "ObservableValue"; }
_super.call(this, name);
this.mode = mode;
this.hasUnreportedChange = false;
this.events = null;
this.value = undefined;
var _a = getValueModeFromValue(value, ValueMode.Recursive), childmode = _a[0], unwrappedValue = _a[1];
if (this.mode === ValueMode.Recursive)
this.mode = childmode;
this.value = makeChildObservable(unwrappedValue, this.mode, this.name);
}
ObservableValue.prototype.set = function (newValue) {
assertUnwrapped(newValue, "Modifiers cannot be used on non-initial values.");
checkIfStateModificationsAreAllowed();
var oldValue = this.value;
var changed = valueDidChange(this.mode === ValueMode.Structure, oldValue, newValue);
if (changed) {
this.value = makeChildObservable(newValue, this.mode, this.name);
this.reportChanged();
if (this.events)
this.events.emit(newValue, oldValue);
}
return changed;
};
ObservableValue.prototype.get = function () {
this.reportObserved();
return this.value;
};
ObservableValue.prototype.observe = function (listener, fireImmediately) {
if (!this.events)
this.events = new SimpleEventEmitter();
if (fireImmediately)
listener(this.value, undefined);
return this.events.on(listener);
};
ObservableValue.prototype.toString = function () {
return this.name + "@" + this.id + "[" + this.value + "]";
};
return ObservableValue;
})(Atom);
var SimpleEventEmitter = (function () {
function SimpleEventEmitter() {
this.listeners = [];
}
SimpleEventEmitter.prototype.emit = function () {
var listeners = this.listeners.slice();
for (var i = 0, l = listeners.length; i < l; i++)
listeners[i].apply(null, arguments);
};
SimpleEventEmitter.prototype.on = function (listener) {
var _this = this;
this.listeners.push(listener);
return once(function () {
var idx = _this.listeners.indexOf(listener);
if (idx !== -1)
_this.listeners.splice(idx, 1);
});
};
SimpleEventEmitter.prototype.once = function (listener) {
var subscription = this.on(function () {
subscription();
listener.apply(this, arguments);
});
return subscription;
};
return SimpleEventEmitter;
})();
exports.SimpleEventEmitter = SimpleEventEmitter;
var EMPTY_ARRAY = [];
Object.freeze(EMPTY_ARRAY);
function invariant(check, message, thing) {
if (!check)
throw new Error("[mobx] Invariant failed: " + message + (thing ? " in '" + thing + "'" : ""));
}
var deprecatedMessages = [];
function deprecated(msg) {
if (deprecatedMessages.indexOf(msg) !== -1)
return;
deprecatedMessages.push(msg);
console.error("[mobx] Deprecated: " + msg);
}
function once(func) {
var invoked = false;
return function () {
if (invoked)
return;
invoked = true;
return func.apply(this, arguments);
};
}
var noop = function () { };
function unique(list) {
var res = [];
list.forEach(function (item) {
if (res.indexOf(item) === -1)
res.push(item);
});
return res;
}
function isPlainObject(value) {
return value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype;
}
function valueDidChange(compareStructural, oldValue, newValue) {
return compareStructural
? !deepEquals(oldValue, newValue)
: oldValue !== newValue;
}
function makeNonEnumerable(object, props) {
for (var i = 0; i < props.length; i++) {
Object.defineProperty(object, props[i], {
configurable: true,
writable: true,
enumerable: false,
value: object[props[i]]
});
}
}
function isPropertyConfigurable(object, prop) {
var descriptor = Object.getOwnPropertyDescriptor(object, prop);
return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false);
}
function assertPropertyConfigurable(object, prop) {
invariant(isPropertyConfigurable(object, prop), "Cannot make property '" + prop + "' observable, it is not configurable and writable in the target object");
}
function deepEquals(a, b) {
if (a === null && b === null)
return true;
if (a === undefined && b === undefined)
return true;
var aIsArray = Array.isArray(a) || isObservableArray(a);
if (aIsArray !== (Array.isArray(b) || isObservableArray(b))) {
return false;
}
else if (aIsArray) {
if (a.length !== b.length)
return false;
for (var i = a.length; i >= 0; i--)
if (!deepEquals(a[i], b[i]))
return false;
return true;
}
else if (typeof a === "object" && typeof b === "object") {
if (a === null || b === null)
return false;
if (Object.keys(a).length !== Object.keys(b).length)
return false;
for (var prop in a) {
if (!b.hasOwnProperty(prop))
return false;
if (!deepEquals(a[prop], b[prop]))
return false;
}
return true;
}
return a === b;
}
function quickDiff(current, base) {
if (!base || !base.length)
return [current, []];
if (!current || !current.length)
return [[], base];
var added = [];
var removed = [];
var currentIndex = 0, currentSearch = 0, currentLength = current.length, currentExhausted = false, baseIndex = 0, baseSearch = 0, baseLength = base.length, isSearching = false, baseExhausted = false;
while (!baseExhausted && !currentExhausted) {
if (!isSearching) {
if (currentIndex < currentLength && baseIndex < baseLength && current[currentIndex] === base[baseIndex]) {
currentIndex++;
baseIndex++;
if (currentIndex === currentLength && baseIndex === baseLength)
return [added, removed];
continue;
}
currentSearch = currentIndex;
baseSearch = baseIndex;
isSearching = true;
}
baseSearch += 1;
currentSearch += 1;
if (baseSearch >= baseLength)
baseExhausted = true;
if (currentSearch >= currentLength)
currentExhausted = true;
if (!currentExhausted && current[currentSearch] === base[baseIndex]) {
added.push.apply(added, current.slice(currentIndex, currentSearch));
currentIndex = currentSearch + 1;
baseIndex++;
isSearching = false;
}
else if (!baseExhausted && base[baseSearch] === current[currentIndex]) {
removed.push.apply(removed, base.slice(baseIndex, baseSearch));
baseIndex = baseSearch + 1;
currentIndex++;
isSearching = false;
}
}
added.push.apply(added, current.slice(currentIndex));
removed.push.apply(removed, base.slice(baseIndex));
return [added, removed];
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}]},{},[1])(1)
}); |
$(function() {
'use strict';
// Todo Item View
// --------------
// The DOM element for a todo item...
Thorax.View.extend({
//... is a list tag.
tagName: 'li',
// Cache the template function for a single item.
name: 'todo-item',
// The DOM events specific to an item.
events: {
'click .toggle': 'toggleCompleted',
'dblclick label': 'edit',
'click .destroy': 'clear',
'keypress .edit': 'updateOnEnter',
'blur .edit': 'close',
// The "rendered" event is triggered by Thorax each time render()
// is called and the result of the template has been appended
// to the View's $el
rendered: function() {
this.$el.toggleClass( 'completed', this.model.get('completed') );
}
},
// Toggle the `"completed"` state of the model.
toggleCompleted: function() {
this.model.toggle();
},
// Switch this view into `"editing"` mode, displaying the input field.
edit: function() {
this.$el.addClass('editing');
this.$('.edit').focus();
},
// Close the `"editing"` mode, saving changes to the todo.
close: function() {
var value = this.$('.edit').val().trim();
if ( value ) {
this.model.save({ title: value });
} else {
this.clear();
}
this.$el.removeClass('editing');
},
// If you hit `enter`, we're through editing the item.
updateOnEnter: function( e ) {
if ( e.which === ENTER_KEY ) {
this.close();
}
},
// Remove the item, destroy the model from *localStorage* and delete its view.
clear: function() {
this.model.destroy();
}
});
});
|
/*
* DC jQuery Floater - jQuery Floater
* Copyright (c) 2011 Design Chemical
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
(function($){
//define the new for the plugin ans how to call it
$.fn.dcSocialFloater = function(options) {
//set default options
var defaults = {
classWrapper: 'dc-social-float',
classContent: 'dc-social-float-content',
width: 200,
idWrapper: 'dc-social-float-'+$(this).index(),
location: 'top', // top, bottom
align: 'left', // left, right
offsetLocation: '10',
offsetAlign: '10',
center: false,
centerPx: 0,
speedFloat: 1500,
speedContent: 600,
disableFloat: false,
tabText: 'Click',
event: 'click',
classTab: 'tab',
classOpen: 'dc-open',
classClose: 'dc-close',
classToggle: 'dc-toggle',
autoClose: true,
loadOpen: false,
tabClose: true,
easing: 'easeOutQuint'
};
//call in the default otions
var options = $.extend(defaults, options);
//act upon the element that is passed into the design
return this.each(function(options){
var idWrapper = defaults.idWrapper;
var floatTab = '<div class="'+defaults.classTab+'"><span>'+defaults.tabText+'</span></div>';
$(this).addClass(defaults.classContent).wrap('<div id="'+idWrapper+'" class="'+defaults.classWrapper+' '+defaults.align+'" />');
if(defaults.location == 'bottom'){
$('#'+idWrapper).addClass(defaults.location).append(floatTab);
} else {
$('#'+idWrapper).prepend(floatTab);
}
//cache vars
var $floater = $('#'+idWrapper);
var $tab = $('.'+defaults.classTab,$floater);
var $content = $('.'+defaults.classContent,$floater);
var linkOpen = $('.'+defaults.classOpen);
var linkClose = $('.'+defaults.classClose);
var linkToggle = $('.'+defaults.classToggle);
var cssPos = defaults.disableFloat == false ? 'absolute' : 'fixed' ;
$floater.css({width: defaults.width+'px', position: cssPos, zIndex: 10000});
var h_c = $content.outerHeight(true);
var h_f = $floater.outerHeight();
var h_t = $tab.outerHeight();
if(defaults.tabClose == true){
$content.hide();
}
floaterSetup($floater);
var start = $('#'+idWrapper).position().top;
if(defaults.disableFloat == false){
floatObj();
$(window).scroll(function(){
floatObj();
});
}
if(defaults.loadOpen == true){
floatOpen();
}
if(defaults.tabClose == true){
// If using hover event
if(defaults.event == 'hover'){
var config = {
sensitivity: 2,
interval: 100,
over: floatOpen,
timeout: 400,
out: floatClose
};
$floater.hoverIntent(config);
}
// If using click event
if(defaults.event == 'click'){
$tab.click(function(e){
if($floater.hasClass('active')){
floatClose();
} else {
floatOpen();
}
e.preventDefault();
});
}
$(linkOpen).click(function(e){
if($floater.not('active')){
floatOpen();
}
e.preventDefault();
});
$(linkClose).click(function(e){
if($floater.hasClass('active')){
floatClose();
}
e.preventDefault();
});
$(linkToggle).click(function(e){
if($floater.hasClass('active')){
floatClose();
} else {
floatOpen();
}
e.preventDefault();
});
// Auto-close
if(defaults.autoClose == true){
$('body').mouseup(function(e){
if($floater.hasClass('active')){
if(!$(e.target).parents('#'+defaults.idWrapper+'.'+defaults.classWrapper).length){
floatClose();
}
}
});
}
} else {
// Add active class if tabClose false
$floater.addClass('active');
}
function floatOpen(){
$('.'+defaults.classWrapper).css({zIndex: 10000});
$floater.css({zIndex: 10001});
var h_fpx = h_c+'px';
if(defaults.location == 'bottom'){
$content.animate({marginTop: '-'+h_fpx}, defaults.speed).slideDown(defaults.speedContent);
} else {
$content.slideDown(defaults.speedContent);
}
$floater.addClass('active');
}
function floatClose(){
$content.slideUp(defaults.speedContent, function(){
$floater.removeClass('active');
});
}
function floatObj(){
var scroll = $(document).scrollTop();
var moveTo = start + scroll;
var h_b = $('body').height();
var h_f = $floater.height();
var h_c = $content.height();
$floater.stop().animate({top: moveTo}, defaults.speedFloat, defaults.easing);
}
// Set up positioning
function floaterSetup(obj){
var location = defaults.location;
var align = defaults.align;
var offsetL = defaults.offsetLocation;
var offsetA = defaults.offsetAlign;
if(location == 'top'){
$(obj).css({top: offsetL});
} else {
$(obj).css({bottom: offsetL});
}
if(defaults.center == true){
offsetA = '50%';
}
if(align == 'left'){
$(obj).css({left: offsetA});
if(defaults.center == true){
$(obj).css({marginLeft: -defaults.centerPx+'px'});
}
} else {
$(obj).css({right: offsetA});
if(defaults.center == true){
$(obj).css({marginRight: -defaults.centerPx+'px'});
}
}
}
});
};
})(jQuery);
jQuery(document).ready(function($) {
$('.pinItButton').click(function(){
exec_pinmarklet();
});
}); |
function array_intersect_key (arr1) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir (http://brett-zamir.me)
// % note 1: These only output associative arrays (would need to be
// % note 1: all numeric and counting from zero to be numeric)
// * example 1: $array1 = {a: 'green', b: 'brown', c: 'blue', 0: 'red'}
// * example 1: $array2 = {a: 'green', 0: 'yellow', 1: 'red'}
// * example 1: array_intersect_key($array1, $array2)
// * returns 1: {0: 'red', a: 'green'}
var retArr = {},
argl = arguments.length,
arglm1 = argl - 1,
k1 = '',
arr = {},
i = 0,
k = '';
arr1keys: for (k1 in arr1) {
arrs: for (i = 1; i < argl; i++) {
arr = arguments[i];
for (k in arr) {
if (k === k1) {
if (i === arglm1) {
retArr[k1] = arr1[k1];
}
// If the innermost loop always leads at least once to an equal value, continue the loop until done
continue arrs;
}
}
// If it reaches here, it wasn't found in at least one array, so try next value
continue arr1keys;
}
}
return retArr;
}
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("specialchar","cy",{euro:"Arwydd yr Ewro",lsquo:"Dyfynnod chwith unigol",rsquo:"Dyfynnod dde unigol",ldquo:"Dyfynnod chwith dwbl",rdquo:"Dyfynnod dde dwbl",ndash:"Cysylltnod en",mdash:"Cysylltnod em",iexcl:"Ebychnod gwrthdro",cent:"Arwydd sent",pound:"Arwydd punt",curren:"Arwydd arian cyfred",yen:"Arwydd yen",brvbar:"Bar toriedig",sect:"Arwydd adran",uml:"Didolnod",copy:"Arwydd hawlfraint",ordf:"Dangosydd benywaidd",laquo:"Dyfynnod dwbl ar ongl i'r chwith",not:"Arwydd Nid",
reg:"Arwydd cofrestredig",macr:"Macron",deg:"Arwydd gradd",sup2:"Dau uwchsgript",sup3:"Tri uwchsgript",acute:"Acen ddyrchafedig",micro:"Arwydd micro",para:"Arwydd pilcrow",middot:"Dot canol",cedil:"Sedila",sup1:"Un uwchsgript",ordm:"Dangosydd gwrywaidd",raquo:"Dyfynnod dwbl ar ongl i'r dde",frac14:"Ffracsiwn cyffredin un cwarter",frac12:"Ffracsiwn cyffredin un hanner",frac34:"Ffracsiwn cyffredin tri chwarter",iquest:"Marc cwestiwn gwrthdroëdig",Agrave:"Priflythyren A Lladinaidd gydag acen ddisgynedig",
Aacute:"Priflythyren A Lladinaidd gydag acen ddyrchafedig",Acirc:"Priflythyren A Lladinaidd gydag acen grom",Atilde:"Priflythyren A Lladinaidd gyda thild",Auml:"Priflythyren A Lladinaidd gyda didolnod",Aring:"Priflythyren A Lladinaidd gyda chylch uwchben",AElig:"Priflythyren Æ Lladinaidd",Ccedil:"Priflythyren C Lladinaidd gyda sedila",Egrave:"Priflythyren E Lladinaidd gydag acen ddisgynedig",Eacute:"Priflythyren E Lladinaidd gydag acen ddyrchafedig",Ecirc:"Priflythyren E Lladinaidd gydag acen grom",
Euml:"Priflythyren E Lladinaidd gyda didolnod",Igrave:"Priflythyren I Lladinaidd gydag acen ddisgynedig",Iacute:"Priflythyren I Lladinaidd gydag acen ddyrchafedig",Icirc:"Priflythyren I Lladinaidd gydag acen grom",Iuml:"Priflythyren I Lladinaidd gyda didolnod",ETH:"Priflythyren Eth",Ntilde:"Priflythyren N Lladinaidd gyda thild",Ograve:"Priflythyren O Lladinaidd gydag acen ddisgynedig",Oacute:"Priflythyren O Lladinaidd gydag acen ddyrchafedig",Ocirc:"Priflythyren O Lladinaidd gydag acen grom",Otilde:"Priflythyren O Lladinaidd gyda thild",
Ouml:"Priflythyren O Lladinaidd gyda didolnod",times:"Arwydd lluosi",Oslash:"Priflythyren O Lladinaidd gyda strôc",Ugrave:"Priflythyren U Lladinaidd gydag acen ddisgynedig",Uacute:"Priflythyren U Lladinaidd gydag acen ddyrchafedig",Ucirc:"Priflythyren U Lladinaidd gydag acen grom",Uuml:"Priflythyren U Lladinaidd gyda didolnod",Yacute:"Priflythyren Y Lladinaidd gydag acen ddyrchafedig",THORN:"Priflythyren Thorn",szlig:"Llythyren s fach Lladinaidd siarp ",agrave:"Llythyren a fach Lladinaidd gydag acen ddisgynedig",
aacute:"Llythyren a fach Lladinaidd gydag acen ddyrchafedig",acirc:"Llythyren a fach Lladinaidd gydag acen grom",atilde:"Llythyren a fach Lladinaidd gyda thild",auml:"Llythyren a fach Lladinaidd gyda didolnod",aring:"Llythyren a fach Lladinaidd gyda chylch uwchben",aelig:"Llythyren æ fach Lladinaidd",ccedil:"Llythyren c fach Lladinaidd gyda sedila",egrave:"Llythyren e fach Lladinaidd gydag acen ddisgynedig",eacute:"Llythyren e fach Lladinaidd gydag acen ddyrchafedig",ecirc:"Llythyren e fach Lladinaidd gydag acen grom",
euml:"Llythyren e fach Lladinaidd gyda didolnod",igrave:"Llythyren i fach Lladinaidd gydag acen ddisgynedig",iacute:"Llythyren i fach Lladinaidd gydag acen ddyrchafedig",icirc:"Llythyren i fach Lladinaidd gydag acen grom",iuml:"Llythyren i fach Lladinaidd gyda didolnod",eth:"Llythyren eth fach",ntilde:"Llythyren n fach Lladinaidd gyda thild",ograve:"Llythyren o fach Lladinaidd gydag acen ddisgynedig",oacute:"Llythyren o fach Lladinaidd gydag acen ddyrchafedig",ocirc:"Llythyren o fach Lladinaidd gydag acen grom",
otilde:"Llythyren o fach Lladinaidd gyda thild",ouml:"Llythyren o fach Lladinaidd gyda didolnod",divide:"Arwydd rhannu",oslash:"Llythyren o fach Lladinaidd gyda strôc",ugrave:"Llythyren u fach Lladinaidd gydag acen ddisgynedig",uacute:"Llythyren u fach Lladinaidd gydag acen ddyrchafedig",ucirc:"Llythyren u fach Lladinaidd gydag acen grom",uuml:"Llythyren u fach Lladinaidd gyda didolnod",yacute:"Llythyren y fach Lladinaidd gydag acen ddisgynedig",thorn:"Llythyren o fach Lladinaidd gyda strôc",yuml:"Llythyren y fach Lladinaidd gyda didolnod",
OElig:"Priflythyren cwlwm OE Lladinaidd ",oelig:"Priflythyren cwlwm oe Lladinaidd ",372:"Priflythyren W gydag acen grom",374:"Priflythyren Y gydag acen grom",373:"Llythyren w fach gydag acen grom",375:"Llythyren y fach gydag acen grom",sbquo:"Dyfynnod sengl 9-isel",8219:"Dyfynnod sengl 9-uchel cildro",bdquo:"Dyfynnod dwbl 9-isel",hellip:"Coll geiriau llorweddol",trade:"Arwydd marc masnachol",9658:"Pwyntydd du i'r dde",bull:"Bwled",rarr:"Saeth i'r dde",rArr:"Saeth ddwbl i'r dde",hArr:"Saeth ddwbl i'r chwith",
diams:"Siwt diemwnt du",asymp:"Bron yn hafal iddo"}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.