text
stringlengths 2
1.05M
|
|---|
/*
* Copyright (C) 2009 Google Inc. 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 Google Inc. 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 THE COPYRIGHT
* OWNER OR CONTRIBUTORS 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.
*/
/**
* @unrestricted
*/
Common.Settings = class {
/**
* @param {!Common.SettingsStorage} globalStorage
* @param {!Common.SettingsStorage} localStorage
*/
constructor(globalStorage, localStorage) {
this._globalStorage = globalStorage;
this._localStorage = localStorage;
this._sessionStorage = new Common.SettingsStorage({});
this._eventSupport = new Common.Object();
/** @type {!Map<string, !Common.Setting>} */
this._registry = new Map();
/** @type {!Map<string, !Common.Setting>} */
this._moduleSettings = new Map();
self.runtime.extensions('setting').forEach(this._registerModuleSetting.bind(this));
}
/**
* @param {!Runtime.Extension} extension
*/
_registerModuleSetting(extension) {
var descriptor = extension.descriptor();
var settingName = descriptor['settingName'];
var isRegex = descriptor['settingType'] === 'regex';
var defaultValue = descriptor['defaultValue'];
var storageType;
switch (descriptor['storageType']) {
case ('local'):
storageType = Common.SettingStorageType.Local;
break;
case ('session'):
storageType = Common.SettingStorageType.Session;
break;
case ('global'):
storageType = Common.SettingStorageType.Global;
break;
default:
storageType = Common.SettingStorageType.Global;
}
var setting = isRegex ? this.createRegExpSetting(settingName, defaultValue, undefined, storageType) :
this.createSetting(settingName, defaultValue, storageType);
if (descriptor['title'])
setting.setTitle(descriptor['title']);
this._moduleSettings.set(settingName, setting);
}
/**
* @param {string} settingName
* @return {!Common.Setting}
*/
moduleSetting(settingName) {
var setting = this._moduleSettings.get(settingName);
if (!setting)
throw new Error('No setting registered: ' + settingName);
return setting;
}
/**
* @param {string} settingName
* @return {!Common.Setting}
*/
settingForTest(settingName) {
var setting = this._registry.get(settingName);
if (!setting)
throw new Error('No setting registered: ' + settingName);
return setting;
}
/**
* @param {string} key
* @param {*} defaultValue
* @param {!Common.SettingStorageType=} storageType
* @return {!Common.Setting}
*/
createSetting(key, defaultValue, storageType) {
var storage = this._storageFromType(storageType);
if (!this._registry.get(key))
this._registry.set(key, new Common.Setting(this, key, defaultValue, this._eventSupport, storage));
return /** @type {!Common.Setting} */ (this._registry.get(key));
}
/**
* @param {string} key
* @param {*} defaultValue
* @return {!Common.Setting}
*/
createLocalSetting(key, defaultValue) {
return this.createSetting(key, defaultValue, Common.SettingStorageType.Local);
}
/**
* @param {string} key
* @param {string} defaultValue
* @param {string=} regexFlags
* @param {!Common.SettingStorageType=} storageType
* @return {!Common.RegExpSetting}
*/
createRegExpSetting(key, defaultValue, regexFlags, storageType) {
if (!this._registry.get(key)) {
this._registry.set(
key,
new Common.RegExpSetting(
this, key, defaultValue, this._eventSupport, this._storageFromType(storageType), regexFlags));
}
return /** @type {!Common.RegExpSetting} */ (this._registry.get(key));
}
clearAll() {
this._globalStorage.removeAll();
this._localStorage.removeAll();
var versionSetting = Common.settings.createSetting(Common.VersionController._currentVersionName, 0);
versionSetting.set(Common.VersionController.currentVersion);
}
/**
* @param {!Common.SettingStorageType=} storageType
* @return {!Common.SettingsStorage}
*/
_storageFromType(storageType) {
switch (storageType) {
case (Common.SettingStorageType.Local):
return this._localStorage;
case (Common.SettingStorageType.Session):
return this._sessionStorage;
case (Common.SettingStorageType.Global):
return this._globalStorage;
}
return this._globalStorage;
}
};
/**
* @unrestricted
*/
Common.SettingsStorage = class {
/**
* @param {!Object} object
* @param {function(string, string)=} setCallback
* @param {function(string)=} removeCallback
* @param {function(string)=} removeAllCallback
* @param {string=} storagePrefix
*/
constructor(object, setCallback, removeCallback, removeAllCallback, storagePrefix) {
this._object = object;
this._setCallback = setCallback || function() {};
this._removeCallback = removeCallback || function() {};
this._removeAllCallback = removeAllCallback || function() {};
this._storagePrefix = storagePrefix || '';
}
/**
* @param {string} name
* @param {string} value
*/
set(name, value) {
name = this._storagePrefix + name;
this._object[name] = value;
this._setCallback(name, value);
}
/**
* @param {string} name
* @return {boolean}
*/
has(name) {
name = this._storagePrefix + name;
return name in this._object;
}
/**
* @param {string} name
* @return {string}
*/
get(name) {
name = this._storagePrefix + name;
return this._object[name];
}
/**
* @param {string} name
*/
remove(name) {
name = this._storagePrefix + name;
delete this._object[name];
this._removeCallback(name);
}
removeAll() {
this._object = {};
this._removeAllCallback();
}
_dumpSizes() {
Common.console.log('Ten largest settings: ');
var sizes = {__proto__: null};
for (var key in this._object)
sizes[key] = this._object[key].length;
var keys = Object.keys(sizes);
function comparator(key1, key2) {
return sizes[key2] - sizes[key1];
}
keys.sort(comparator);
for (var i = 0; i < 10 && i < keys.length; ++i)
Common.console.log('Setting: \'' + keys[i] + '\', size: ' + sizes[keys[i]]);
}
};
/**
* @template V
* @unrestricted
*/
Common.Setting = class {
/**
* @param {!Common.Settings} settings
* @param {string} name
* @param {V} defaultValue
* @param {!Common.Object} eventSupport
* @param {!Common.SettingsStorage} storage
*/
constructor(settings, name, defaultValue, eventSupport, storage) {
this._settings = settings;
this._name = name;
this._defaultValue = defaultValue;
this._eventSupport = eventSupport;
this._storage = storage;
/** @type {string} */
this._title = '';
}
/**
* @param {function(!Common.Event)} listener
* @param {!Object=} thisObject
*/
addChangeListener(listener, thisObject) {
this._eventSupport.addEventListener(this._name, listener, thisObject);
}
/**
* @param {function(!Common.Event)} listener
* @param {!Object=} thisObject
*/
removeChangeListener(listener, thisObject) {
this._eventSupport.removeEventListener(this._name, listener, thisObject);
}
get name() {
return this._name;
}
/**
* @return {string}
*/
title() {
return this._title;
}
/**
* @param {string} title
*/
setTitle(title) {
this._title = title;
}
/**
* @return {V}
*/
get() {
if (typeof this._value !== 'undefined')
return this._value;
this._value = this._defaultValue;
if (this._storage.has(this._name)) {
try {
this._value = JSON.parse(this._storage.get(this._name));
} catch (e) {
this._storage.remove(this._name);
}
}
return this._value;
}
/**
* @param {V} value
*/
set(value) {
this._value = value;
try {
var settingString = JSON.stringify(value);
try {
this._storage.set(this._name, settingString);
} catch (e) {
this._printSettingsSavingError(e.message, this._name, settingString);
}
} catch (e) {
Common.console.error('Cannot stringify setting with name: ' + this._name + ', error: ' + e.message);
}
this._eventSupport.dispatchEventToListeners(this._name, value);
}
remove() {
this._settings._registry.delete(this._name);
this._settings._moduleSettings.delete(this._name);
this._storage.remove(this._name);
}
/**
* @param {string} message
* @param {string} name
* @param {string} value
*/
_printSettingsSavingError(message, name, value) {
var errorMessage =
'Error saving setting with name: ' + this._name + ', value length: ' + value.length + '. Error: ' + message;
console.error(errorMessage);
Common.console.error(errorMessage);
this._storage._dumpSizes();
}
};
/**
* @unrestricted
*/
Common.RegExpSetting = class extends Common.Setting {
/**
* @param {!Common.Settings} settings
* @param {string} name
* @param {string} defaultValue
* @param {!Common.Object} eventSupport
* @param {!Common.SettingsStorage} storage
* @param {string=} regexFlags
*/
constructor(settings, name, defaultValue, eventSupport, storage, regexFlags) {
super(settings, name, defaultValue ? [{pattern: defaultValue}] : [], eventSupport, storage);
this._regexFlags = regexFlags;
}
/**
* @override
* @return {string}
*/
get() {
var result = [];
var items = this.getAsArray();
for (var i = 0; i < items.length; ++i) {
var item = items[i];
if (item.pattern && !item.disabled)
result.push(item.pattern);
}
return result.join('|');
}
/**
* @return {!Array.<{pattern: string, disabled: (boolean|undefined)}>}
*/
getAsArray() {
return super.get();
}
/**
* @override
* @param {string} value
*/
set(value) {
this.setAsArray([{pattern: value}]);
}
/**
* @param {!Array.<{pattern: string, disabled: (boolean|undefined)}>} value
*/
setAsArray(value) {
delete this._regex;
super.set(value);
}
/**
* @return {?RegExp}
*/
asRegExp() {
if (typeof this._regex !== 'undefined')
return this._regex;
this._regex = null;
try {
var pattern = this.get();
if (pattern)
this._regex = new RegExp(pattern, this._regexFlags || '');
} catch (e) {
}
return this._regex;
}
};
/**
* @unrestricted
*/
Common.VersionController = class {
updateVersion() {
var localStorageVersion =
window.localStorage ? window.localStorage[Common.VersionController._currentVersionName] : 0;
var versionSetting = Common.settings.createSetting(Common.VersionController._currentVersionName, 0);
var currentVersion = Common.VersionController.currentVersion;
var oldVersion = versionSetting.get() || parseInt(localStorageVersion || '0', 10);
if (oldVersion === 0) {
// First run, no need to do anything.
versionSetting.set(currentVersion);
return;
}
var methodsToRun = this._methodsToRunToUpdateVersion(oldVersion, currentVersion);
for (var i = 0; i < methodsToRun.length; ++i)
this[methodsToRun[i]].call(this);
versionSetting.set(currentVersion);
}
/**
* @param {number} oldVersion
* @param {number} currentVersion
*/
_methodsToRunToUpdateVersion(oldVersion, currentVersion) {
var result = [];
for (var i = oldVersion; i < currentVersion; ++i)
result.push('_updateVersionFrom' + i + 'To' + (i + 1));
return result;
}
_updateVersionFrom0To1() {
this._clearBreakpointsWhenTooMany(Common.settings.createLocalSetting('breakpoints', []), 500000);
}
_updateVersionFrom1To2() {
Common.settings.createSetting('previouslyViewedFiles', []).set([]);
}
_updateVersionFrom2To3() {
Common.settings.createSetting('fileSystemMapping', {}).set({});
Common.settings.createSetting('fileMappingEntries', []).remove();
}
_updateVersionFrom3To4() {
var advancedMode = Common.settings.createSetting('showHeaSnapshotObjectsHiddenProperties', false);
Common.moduleSetting('showAdvancedHeapSnapshotProperties').set(advancedMode.get());
advancedMode.remove();
}
_updateVersionFrom4To5() {
var settingNames = {
'FileSystemViewSidebarWidth': 'fileSystemViewSplitViewState',
'elementsSidebarWidth': 'elementsPanelSplitViewState',
'StylesPaneSplitRatio': 'stylesPaneSplitViewState',
'heapSnapshotRetainersViewSize': 'heapSnapshotSplitViewState',
'InspectorView.splitView': 'InspectorView.splitViewState',
'InspectorView.screencastSplitView': 'InspectorView.screencastSplitViewState',
'Inspector.drawerSplitView': 'Inspector.drawerSplitViewState',
'layerDetailsSplitView': 'layerDetailsSplitViewState',
'networkSidebarWidth': 'networkPanelSplitViewState',
'sourcesSidebarWidth': 'sourcesPanelSplitViewState',
'scriptsPanelNavigatorSidebarWidth': 'sourcesPanelNavigatorSplitViewState',
'sourcesPanelSplitSidebarRatio': 'sourcesPanelDebuggerSidebarSplitViewState',
'timeline-details': 'timelinePanelDetailsSplitViewState',
'timeline-split': 'timelinePanelRecorsSplitViewState',
'timeline-view': 'timelinePanelTimelineStackSplitViewState',
'auditsSidebarWidth': 'auditsPanelSplitViewState',
'layersSidebarWidth': 'layersPanelSplitViewState',
'profilesSidebarWidth': 'profilesPanelSplitViewState',
'resourcesSidebarWidth': 'resourcesPanelSplitViewState'
};
var empty = {};
for (var oldName in settingNames) {
var newName = settingNames[oldName];
var oldNameH = oldName + 'H';
var newValue = null;
var oldSetting = Common.settings.createSetting(oldName, empty);
if (oldSetting.get() !== empty) {
newValue = newValue || {};
newValue.vertical = {};
newValue.vertical.size = oldSetting.get();
oldSetting.remove();
}
var oldSettingH = Common.settings.createSetting(oldNameH, empty);
if (oldSettingH.get() !== empty) {
newValue = newValue || {};
newValue.horizontal = {};
newValue.horizontal.size = oldSettingH.get();
oldSettingH.remove();
}
if (newValue)
Common.settings.createSetting(newName, {}).set(newValue);
}
}
_updateVersionFrom5To6() {
var settingNames = {
'debuggerSidebarHidden': 'sourcesPanelSplitViewState',
'navigatorHidden': 'sourcesPanelNavigatorSplitViewState',
'WebInspector.Drawer.showOnLoad': 'Inspector.drawerSplitViewState'
};
for (var oldName in settingNames) {
var oldSetting = Common.settings.createSetting(oldName, null);
if (oldSetting.get() === null) {
oldSetting.remove();
continue;
}
var newName = settingNames[oldName];
var invert = oldName === 'WebInspector.Drawer.showOnLoad';
var hidden = oldSetting.get() !== invert;
oldSetting.remove();
var showMode = hidden ? 'OnlyMain' : 'Both';
var newSetting = Common.settings.createSetting(newName, {});
var newValue = newSetting.get() || {};
newValue.vertical = newValue.vertical || {};
newValue.vertical.showMode = showMode;
newValue.horizontal = newValue.horizontal || {};
newValue.horizontal.showMode = showMode;
newSetting.set(newValue);
}
}
_updateVersionFrom6To7() {
var settingNames = {
'sourcesPanelNavigatorSplitViewState': 'sourcesPanelNavigatorSplitViewState',
'elementsPanelSplitViewState': 'elementsPanelSplitViewState',
'stylesPaneSplitViewState': 'stylesPaneSplitViewState',
'sourcesPanelDebuggerSidebarSplitViewState': 'sourcesPanelDebuggerSidebarSplitViewState'
};
var empty = {};
for (var name in settingNames) {
var setting = Common.settings.createSetting(name, empty);
var value = setting.get();
if (value === empty)
continue;
// Zero out saved percentage sizes, and they will be restored to defaults.
if (value.vertical && value.vertical.size && value.vertical.size < 1)
value.vertical.size = 0;
if (value.horizontal && value.horizontal.size && value.horizontal.size < 1)
value.horizontal.size = 0;
setting.set(value);
}
}
_updateVersionFrom7To8() {
}
_updateVersionFrom8To9() {
var settingNames = ['skipStackFramesPattern', 'workspaceFolderExcludePattern'];
for (var i = 0; i < settingNames.length; ++i) {
var setting = Common.settings.createSetting(settingNames[i], '');
var value = setting.get();
if (!value)
return;
if (typeof value === 'string')
value = [value];
for (var j = 0; j < value.length; ++j) {
if (typeof value[j] === 'string')
value[j] = {pattern: value[j]};
}
setting.set(value);
}
}
_updateVersionFrom9To10() {
// This one is localStorage specific, which is fine.
if (!window.localStorage)
return;
for (var key in window.localStorage) {
if (key.startsWith('revision-history'))
window.localStorage.removeItem(key);
}
}
_updateVersionFrom10To11() {
var oldSettingName = 'customDevicePresets';
var newSettingName = 'customEmulatedDeviceList';
var oldSetting = Common.settings.createSetting(oldSettingName, undefined);
var list = oldSetting.get();
if (!Array.isArray(list))
return;
var newList = [];
for (var i = 0; i < list.length; ++i) {
var value = list[i];
var device = {};
device['title'] = value['title'];
device['type'] = 'unknown';
device['user-agent'] = value['userAgent'];
device['capabilities'] = [];
if (value['touch'])
device['capabilities'].push('touch');
if (value['mobile'])
device['capabilities'].push('mobile');
device['screen'] = {};
device['screen']['vertical'] = {width: value['width'], height: value['height']};
device['screen']['horizontal'] = {width: value['height'], height: value['width']};
device['screen']['device-pixel-ratio'] = value['deviceScaleFactor'];
device['modes'] = [];
device['show-by-default'] = true;
device['show'] = 'Default';
newList.push(device);
}
if (newList.length)
Common.settings.createSetting(newSettingName, []).set(newList);
oldSetting.remove();
}
_updateVersionFrom11To12() {
this._migrateSettingsFromLocalStorage();
}
_updateVersionFrom12To13() {
this._migrateSettingsFromLocalStorage();
Common.settings.createSetting('timelineOverviewMode', '').remove();
}
_updateVersionFrom13To14() {
var defaultValue = {'throughput': -1, 'latency': 0};
Common.settings.createSetting('networkConditions', defaultValue).set(defaultValue);
}
_updateVersionFrom14To15() {
var setting = Common.settings.createLocalSetting('workspaceExcludedFolders', {});
var oldValue = setting.get();
var newValue = {};
for (var fileSystemPath in oldValue) {
newValue[fileSystemPath] = [];
for (var entry of oldValue[fileSystemPath])
newValue[fileSystemPath].push(entry.path);
}
setting.set(newValue);
}
_updateVersionFrom15To16() {
var setting = Common.settings.createSetting('InspectorView.panelOrder', {});
var tabOrders = setting.get();
for (var key of Object.keys(tabOrders))
tabOrders[key] = (tabOrders[key] + 1) * 10;
setting.set(tabOrders);
}
_updateVersionFrom16To17() {
var setting = Common.settings.createSetting('networkConditionsCustomProfiles', []);
var oldValue = setting.get();
var newValue = [];
if (Array.isArray(oldValue)) {
for (var preset of oldValue) {
if (typeof preset.title === 'string' && typeof preset.value === 'object' &&
typeof preset.value.throughput === 'number' && typeof preset.value.latency === 'number') {
newValue.push({
title: preset.title,
value:
{download: preset.value.throughput, upload: preset.value.throughput, latency: preset.value.latency}
});
}
}
}
setting.set(newValue);
}
_updateVersionFrom17To18() {
var setting = Common.settings.createLocalSetting('workspaceExcludedFolders', {});
var oldValue = setting.get();
var newValue = {};
for (var oldKey in oldValue) {
var newKey = oldKey.replace(/\\/g, '/');
if (!newKey.startsWith('file://')) {
if (newKey.startsWith('/'))
newKey = 'file://' + newKey;
else
newKey = 'file:///' + newKey;
}
newValue[newKey] = oldValue[oldKey];
}
setting.set(newValue);
}
_updateVersionFrom18To19() {
var defaultColumns = {status: true, type: true, initiator: true, size: true, time: true};
var visibleColumnSettings = Common.settings.createSetting('networkLogColumnsVisibility', defaultColumns);
var visibleColumns = visibleColumnSettings.get();
visibleColumns.name = true;
visibleColumns.timeline = true;
var configs = {};
for (var columnId in visibleColumns) {
if (!visibleColumns.hasOwnProperty(columnId))
continue;
configs[columnId.toLowerCase()] = {visible: visibleColumns[columnId]};
}
var newSetting = Common.settings.createSetting('networkLogColumns', {});
newSetting.set(configs);
visibleColumnSettings.remove();
}
_updateVersionFrom19To20() {
var oldSetting = Common.settings.createSetting('InspectorView.panelOrder', {});
var newSetting = Common.settings.createSetting('panel-tabOrder', {});
newSetting.set(oldSetting.get());
oldSetting.remove();
}
_updateVersionFrom20To21() {
var networkColumns = Common.settings.createSetting('networkLogColumns', {});
var columns = /** @type {!Object} */ (networkColumns.get());
delete columns['timeline'];
delete columns['waterfall'];
networkColumns.set(columns);
}
_updateVersionFrom21To22() {
var breakpointsSetting = Common.settings.createLocalSetting('breakpoints', []);
var breakpoints = breakpointsSetting.get();
for (var breakpoint of breakpoints) {
breakpoint['url'] = breakpoint['sourceFileId'];
delete breakpoint['sourceFileId'];
}
breakpointsSetting.set(breakpoints);
}
_updateVersionFrom22To23() {
// This update is no-op.
}
_updateVersionFrom23To24() {
var oldSetting = Common.settings.createSetting('searchInContentScripts', false);
var newSetting = Common.settings.createSetting('searchInAnonymousAndContentScripts', false);
newSetting.set(oldSetting.get());
oldSetting.remove();
}
_updateVersionFrom24To25() {
var defaultColumns = {status: true, type: true, initiator: true, size: true, time: true};
var networkLogColumnsSetting = Common.settings.createSetting('networkLogColumns', defaultColumns);
var columns = networkLogColumnsSetting.get();
delete columns.product;
networkLogColumnsSetting.set(columns);
}
_migrateSettingsFromLocalStorage() {
// This step migrates all the settings except for the ones below into the browser profile.
var localSettings = new Set([
'advancedSearchConfig', 'breakpoints', 'consoleHistory', 'domBreakpoints', 'eventListenerBreakpoints',
'fileSystemMapping', 'lastSelectedSourcesSidebarPaneTab', 'previouslyViewedFiles', 'savedURLs',
'watchExpressions', 'workspaceExcludedFolders', 'xhrBreakpoints'
]);
if (!window.localStorage)
return;
for (var key in window.localStorage) {
if (localSettings.has(key))
continue;
var value = window.localStorage[key];
window.localStorage.removeItem(key);
Common.settings._globalStorage[key] = value;
}
}
/**
* @param {!Common.Setting} breakpointsSetting
* @param {number} maxBreakpointsCount
*/
_clearBreakpointsWhenTooMany(breakpointsSetting, maxBreakpointsCount) {
// If there are too many breakpoints in a storage, it is likely due to a recent bug that caused
// periodical breakpoints duplication leading to inspector slowness.
if (breakpointsSetting.get().length > maxBreakpointsCount)
breakpointsSetting.set([]);
}
};
Common.VersionController._currentVersionName = 'inspectorVersion';
Common.VersionController.currentVersion = 25;
/**
* @type {!Common.Settings}
*/
Common.settings;
/**
* @enum {symbol}
*/
Common.SettingStorageType = {
Global: Symbol('Global'),
Local: Symbol('Local'),
Session: Symbol('Session')
};
/**
* @param {string} settingName
* @return {!Common.Setting}
*/
Common.moduleSetting = function(settingName) {
return Common.settings.moduleSetting(settingName);
};
/**
* @param {string} settingName
* @return {!Common.Setting}
*/
Common.settingForTest = function(settingName) {
return Common.settings.settingForTest(settingName);
};
|
'use strict';
var ProbeError = require('./lib/common').ProbeError;
var needle = require('needle');
var merge = require('deepmerge');
var pkg = require('./package.json');
var probeStream = require('./stream');
var URL = require('url').URL;
var defaultAgent = pkg.name + '/' + pkg.version + '(+https://github.com/nodeca/probe-image-size)';
var defaults = {
open_timeout: 10000,
response_timeout: 60000,
read_timeout: 60000,
follow_max: 10,
// Use to ignore bad certificates.
//rejectUnauthorized: false,
headers: {
'User-Agent': defaultAgent
}
};
module.exports = function probeHttp(src, options) {
return new Promise(function (resolve, reject) {
var stream, len, finalUrl = src;
try {
stream = needle.get(src, merge.all([ defaults, options ]));
} catch (err) {
reject(err);
return;
}
stream.on('redirect', function (location) {
finalUrl = new URL(location, finalUrl).href;
});
stream.on('header', function (statusCode, headers) {
if (statusCode !== 200) {
reject(new ProbeError('bad status code: ' + statusCode, null, statusCode));
stream.request.abort();
return;
}
len = headers['content-length'];
});
stream.on('err', function (err) {
reject(err);
stream.request.abort();
});
probeStream(stream, true)
.then(function (result) {
if (len && len.match(/^\d+$/)) result.length = +len;
result.url = finalUrl;
resolve(result);
stream.request.abort();
})
.catch(function (err) {
reject(err);
stream.request.abort();
});
});
};
module.exports.parsers = require('./lib/parsers_stream');
|
'use strict';
var getTag = require('./_getTag'),
isObjectLike = require('./isObjectLike');
/** `Object#toString` result references. */
var weakMapTag = '[object WeakMap]';
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
module.exports = isWeakMap;
|
const BlockRewardAuRa = artifacts.require('BlockRewardAuRaTokensMock');
const ERC677BridgeTokenRewardable = artifacts.require('ERC677BridgeTokenRewardable');
const AdminUpgradeabilityProxy = artifacts.require('AdminUpgradeabilityProxy');
const RandomAuRa = artifacts.require('RandomAuRaMock');
const ValidatorSetAuRa = artifacts.require('ValidatorSetAuRaMock');
const StakingAuRaTokens = artifacts.require('StakingAuRaTokensMock');
const StakingAuRaCoins = artifacts.require('StakingAuRaCoinsMock');
const ERROR_MSG = 'VM Exception while processing transaction: revert';
const BN = web3.utils.BN;
require('chai')
.use(require('chai-as-promised'))
.use(require('chai-bn')(BN))
.should();
contract('StakingAuRa', async accounts => {
let owner;
let initialValidators;
let initialStakingAddresses;
let initialPoolIds;
let blockRewardAuRa;
let randomAuRa;
let stakingAuRa;
let validatorSetAuRa;
beforeEach(async () => {
owner = accounts[0];
initialValidators = accounts.slice(1, 3 + 1); // accounts[1...3]
initialStakingAddresses = accounts.slice(4, 6 + 1); // accounts[4...6]
initialStakingAddresses.length.should.be.equal(3);
initialStakingAddresses[0].should.not.be.equal('0x0000000000000000000000000000000000000000');
initialStakingAddresses[1].should.not.be.equal('0x0000000000000000000000000000000000000000');
initialStakingAddresses[2].should.not.be.equal('0x0000000000000000000000000000000000000000');
// Deploy BlockReward contract
blockRewardAuRa = await BlockRewardAuRa.new();
blockRewardAuRa = await AdminUpgradeabilityProxy.new(blockRewardAuRa.address, owner);
blockRewardAuRa = await BlockRewardAuRa.at(blockRewardAuRa.address);
// Deploy Random contract
randomAuRa = await RandomAuRa.new();
randomAuRa = await AdminUpgradeabilityProxy.new(randomAuRa.address, owner);
randomAuRa = await RandomAuRa.at(randomAuRa.address);
// Deploy Staking contract
stakingAuRa = await StakingAuRaTokens.new();
stakingAuRa = await AdminUpgradeabilityProxy.new(stakingAuRa.address, owner);
stakingAuRa = await StakingAuRaTokens.at(stakingAuRa.address);
// Deploy ValidatorSet contract
validatorSetAuRa = await ValidatorSetAuRa.new();
validatorSetAuRa = await AdminUpgradeabilityProxy.new(validatorSetAuRa.address, owner);
validatorSetAuRa = await ValidatorSetAuRa.at(validatorSetAuRa.address);
// Initialize ValidatorSet
await validatorSetAuRa.initialize(
blockRewardAuRa.address, // _blockRewardContract
'0x0000000000000000000000000000000000000000', // _governanceContract
randomAuRa.address, // _randomContract
stakingAuRa.address, // _stakingContract
initialValidators, // _initialMiningAddresses
initialStakingAddresses, // _initialStakingAddresses
false // _firstValidatorIsUnremovable
).should.be.fulfilled;
initialPoolIds = [];
for (let i = 0; i < initialValidators.length; i++) {
initialPoolIds.push(await validatorSetAuRa.idByMiningAddress.call(initialValidators[i]));
}
});
describe('addPool(), transferAndCall()', async () => {
let candidateMiningAddress;
let candidateStakingAddress;
let erc677Token;
let stakeUnit;
let useTransferAndCall = false;
beforeEach(async () => {
candidateMiningAddress = accounts[7];
candidateStakingAddress = accounts[8];
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
// Deploy ERC677 contract
erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for candidate (imagine that the candidate got 2 STAKE_UNITs from a bridge)
stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
const mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(candidateStakingAddress, mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(candidateStakingAddress));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(
await erc677Token.stakingContract.call()
);
// Pass ERC677 contract address to Staking contract
'0x0000000000000000000000000000000000000000'.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
erc677Token.address.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
// Emulate block number
await stakingAuRa.setCurrentBlockNumber(2).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(2).should.be.fulfilled;
});
for (let step = 0; step < 2; step++) {
it('should create a new pool' + fnName(step), async () => {
let lastPoolId = await validatorSetAuRa.lastPoolId.call();
const poolId = ++lastPoolId;
false.should.be.equal(await stakingAuRa.isPoolActive.call(poolId));
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
true.should.be.equal(await stakingAuRa.isPoolActive.call(poolId));
});
it('should fail if mining address is 0' + fnName(step), async () => {
await addPool(stakeUnit.mul(new BN(1)), '0x0000000000000000000000000000000000000000', {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
});
it('should fail if mining address is equal to staking' + fnName(step), async () => {
await addPool(stakeUnit.mul(new BN(1)), candidateStakingAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if the pool with the same mining/staking address is already existed' + fnName(step), async () => {
const candidateMiningAddress2 = accounts[9];
const candidateStakingAddress2 = accounts[10];
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
await erc677Token.mint(candidateMiningAddress, stakeUnit.mul(new BN(2)), {from: owner}).should.be.fulfilled;
await erc677Token.mint(candidateMiningAddress2, stakeUnit.mul(new BN(2)), {from: owner}).should.be.fulfilled;
await erc677Token.mint(candidateStakingAddress2, stakeUnit.mul(new BN(2)), {from: owner}).should.be.fulfilled;
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress2}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress2, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateStakingAddress, {from: candidateMiningAddress2}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateStakingAddress2, {from: candidateMiningAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateMiningAddress2}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress2, {from: candidateMiningAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateStakingAddress, {from: candidateStakingAddress2}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateStakingAddress2, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress2, {from: candidateStakingAddress2}).should.be.fulfilled;
});
it('should fail if gasPrice is 0' + fnName(step), async () => {
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress, gasPrice: 0}).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if ERC contract is not specified' + fnName(step), async () => {
// Set ERC677 contract address to zero
await stakingAuRa.setErc677TokenContractMock('0x0000000000000000000000000000000000000000').should.be.fulfilled;
// Try to add a new pool
let lastPoolId = await validatorSetAuRa.lastPoolId.call();
const poolId = ++lastPoolId;
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
false.should.be.equal(await stakingAuRa.isPoolActive.call(poolId));
// Pass ERC677 contract address to ValidatorSet contract
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
// Add a new pool
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
true.should.be.equal(await stakingAuRa.isPoolActive.call(poolId));
});
it('should fail if staking amount is 0' + fnName(step), async () => {
await addPool(new BN(0), candidateMiningAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if block.number is inside disallowed range' + fnName(step), async () => {
await stakingAuRa.setCurrentBlockNumber(119960).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(119960).should.be.fulfilled;
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setCurrentBlockNumber(116560).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(116560).should.be.fulfilled;
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
});
it('should fail if staking amount is less than CANDIDATE_MIN_STAKE' + fnName(step), async () => {
await addPool(stakeUnit.mul(new BN(1)).div(new BN(2)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
});
it('should fail if candidate doesn\'t have enough funds' + fnName(step), async () => {
await addPool(stakeUnit.mul(new BN(3)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await addPool(stakeUnit.mul(new BN(2)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
});
it('stake amount should be increased' + fnName(step), async () => {
const amount = stakeUnit.mul(new BN(2));
await addPool(amount, candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
const poolId = await validatorSetAuRa.idByStakingAddress.call(candidateStakingAddress);
amount.should.be.bignumber.equal(await stakingAuRa.stakeAmount.call(poolId, '0x0000000000000000000000000000000000000000'));
amount.should.be.bignumber.equal(await stakingAuRa.stakeAmountByCurrentEpoch.call(poolId, '0x0000000000000000000000000000000000000000'));
amount.should.be.bignumber.equal(await stakingAuRa.stakeAmountTotal.call(poolId));
});
it('should be able to add more than one pool' + fnName(step), async () => {
let lastPoolId = await validatorSetAuRa.lastPoolId.call();
const candidate1MiningAddress = candidateMiningAddress;
const candidate1StakingAddress = candidateStakingAddress;
const candidate2MiningAddress = accounts[9];
const candidate2StakingAddress = accounts[10];
const candidate1PoolId = lastPoolId - 0 + 1;
const candidate2PoolId = candidate1PoolId + 1;
const amount1 = stakeUnit.mul(new BN(2));
const amount2 = stakeUnit.mul(new BN(3));
// Emulate having necessary amount for the candidate #2
await erc677Token.mint(candidate2StakingAddress, amount2, {from: owner}).should.be.fulfilled;
amount2.should.be.bignumber.equal(await erc677Token.balanceOf.call(candidate2StakingAddress));
// Add two new pools
(await stakingAuRa.isPoolActive.call(candidate1PoolId)).should.be.equal(false);
(await stakingAuRa.isPoolActive.call(candidate2PoolId)).should.be.equal(false);
await addPool(amount1, candidate1MiningAddress, {from: candidate1StakingAddress}).should.be.fulfilled;
await addPool(amount2, candidate2MiningAddress, {from: candidate2StakingAddress}).should.be.fulfilled;
(await stakingAuRa.isPoolActive.call(candidate1PoolId)).should.be.equal(true);
(await stakingAuRa.isPoolActive.call(candidate2PoolId)).should.be.equal(true);
(new BN(candidate1PoolId)).should.be.bignumber.equal(
await validatorSetAuRa.idByStakingAddress.call(candidate1StakingAddress)
);
(new BN(candidate2PoolId)).should.be.bignumber.equal(
await validatorSetAuRa.idByStakingAddress.call(candidate2StakingAddress)
);
// Check indexes (0...2 are busy by initial validators)
new BN(3).should.be.bignumber.equal(await stakingAuRa.poolIndex.call(candidate1PoolId));
new BN(4).should.be.bignumber.equal(await stakingAuRa.poolIndex.call(candidate2PoolId));
// Check indexes in the `poolsToBeElected` list
new BN(0).should.be.bignumber.equal(await stakingAuRa.poolToBeElectedIndex.call(candidate1PoolId));
new BN(1).should.be.bignumber.equal(await stakingAuRa.poolToBeElectedIndex.call(candidate2PoolId));
// Check pools' existence
const validators = await validatorSetAuRa.getValidators.call();
(await stakingAuRa.getPools.call()).bignumbersEqual([
await validatorSetAuRa.idByMiningAddress.call(validators[0]),
await validatorSetAuRa.idByMiningAddress.call(validators[1]),
await validatorSetAuRa.idByMiningAddress.call(validators[2]),
candidate1PoolId,
candidate2PoolId
]);
});
it('shouldn\'t allow adding more than MAX_CANDIDATES pools' + fnName(step), async () => {
let lastPoolId = await validatorSetAuRa.lastPoolId.call();
for (let p = initialValidators.length; p < 100; p++) {
// Add a new pool
const poolId = ++lastPoolId;
await stakingAuRa.addPoolActiveMock(poolId).should.be.fulfilled;
new BN(p).should.be.bignumber.equal(await stakingAuRa.poolIndex.call(poolId));
await validatorSetAuRa.incrementLastPoolId();
}
new BN(lastPoolId).should.be.bignumber.equal(await validatorSetAuRa.lastPoolId.call());
// Try to add a new pool outside of max limit
const poolId = ++lastPoolId;
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
false.should.be.equal(await stakingAuRa.isPoolActive.call(poolId));
});
it('should remove added pool from the list of inactive pools' + fnName(step), async () => {
let lastPoolId = await validatorSetAuRa.lastPoolId.call();
const candidatePoolId = ++lastPoolId;
await stakingAuRa.addPoolInactiveMock(candidatePoolId).should.be.fulfilled;
(await stakingAuRa.getPoolsInactive.call()).bignumbersEqual([candidatePoolId]);
await addPool(stakeUnit.mul(new BN(1)), candidateMiningAddress, {from: candidateStakingAddress}).should.be.fulfilled;
true.should.be.equal(await stakingAuRa.isPoolActive.call(candidatePoolId));
(await stakingAuRa.getPoolsInactive.call()).length.should.be.equal(0);
});
it('switch useTransferAndCall variable', async () => {
useTransferAndCall = !useTransferAndCall;
});
}
it('onTokenTransfer should accept and save pool metadata', async () => {
const amount = stakeUnit.mul(new BN(1));
const name = 'Grüße';
const description = 'Grüße Grüße Grüße Grüße Grüße';
const nameHex = web3.utils.utf8ToHex(name).replace('0x', '');
const nameLength = web3.utils.numberToHex(nameHex.length / 2).replace('0x', '').padStart(2, '0');
const descriptionHex = web3.utils.utf8ToHex(description).replace('0x', '');
const descriptionLength = web3.utils.numberToHex(descriptionHex.length / 2).replace('0x', '').padStart(4, '0');
const data = `${candidateMiningAddress}01${nameLength}${nameHex}${descriptionLength}${descriptionHex}`;
await erc677Token.transferAndCall(stakingAuRa.address, amount, data, {from: candidateStakingAddress}).should.be.fulfilled;
const poolId = await validatorSetAuRa.idByMiningAddress.call(candidateMiningAddress);
(await validatorSetAuRa.poolName.call(poolId)).should.be.equal(name);
(await validatorSetAuRa.poolDescription.call(poolId)).should.be.equal(description);
});
it('onTokenTransfer should accept pool empty metadata', async () => {
const amount = stakeUnit.mul(new BN(1));
const data = `${candidateMiningAddress}01000000`;
await erc677Token.transferAndCall(stakingAuRa.address, amount, data, {from: candidateStakingAddress}).should.be.fulfilled;
const poolId = await validatorSetAuRa.idByMiningAddress.call(candidateMiningAddress);
(await validatorSetAuRa.poolName.call(poolId)).should.be.equal('');
(await validatorSetAuRa.poolDescription.call(poolId)).should.be.equal('');
});
it('onTokenTransfer should not accept invalid data length', async () => {
const amount = stakeUnit.mul(new BN(1));
await erc677Token.transferAndCall(stakingAuRa.address, amount, `${candidateMiningAddress}01010000`, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await erc677Token.transferAndCall(stakingAuRa.address, amount, `${candidateMiningAddress}01000001`, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await erc677Token.transferAndCall(stakingAuRa.address, amount, `${candidateMiningAddress}0100`, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
await erc677Token.transferAndCall(stakingAuRa.address, amount, `${candidateMiningAddress}01`, {from: candidateStakingAddress}).should.be.rejectedWith(ERROR_MSG);
});
function fnName(step) {
return step == 0 ? ' [addPool]' : ' [transferAndCall]';
}
function addPool(amount, miningAddress, options) {
const poolName = `Pool name for ${options.from}`;
const poolDescription = `Pool description for ${options.from}`;
if (useTransferAndCall) {
const poolNameHex = web3.utils.utf8ToHex(poolName).replace('0x', '');
const poolNameLength = web3.utils.numberToHex(poolNameHex.length / 2).replace('0x', '').padStart(2, '0');
const poolDescriptionHex = web3.utils.utf8ToHex(poolDescription).replace('0x', '');
const poolDescriptionLength = web3.utils.numberToHex(poolDescriptionHex.length / 2).replace('0x', '').padStart(4, '0');
const data = `${miningAddress}01${poolNameLength}${poolNameHex}${poolDescriptionLength}${poolDescriptionHex}`;
return erc677Token.transferAndCall(stakingAuRa.address, amount, data, options);
}
return stakingAuRa.addPool(amount, miningAddress, poolName, poolDescription, options);
}
});
describe('areStakeAndWithdrawAllowed', async () => {
it('should return false during stakeWithdrawDisallowPeriod', async () => {
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
76, // _stakingEpochDuration
0, // _stakingEpochStartBlock
10 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(66).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(true);
for (let block = 67; block <= 76; block++) {
await stakingAuRa.setCurrentBlockNumber(block).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(false);
}
await stakingAuRa.setStakingEpochStartBlock(77).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(76).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(false);
await stakingAuRa.setCurrentBlockNumber(77).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(true);
await stakingAuRa.setCurrentBlockNumber(142).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(true);
for (let block = 143; block <= 152; block++) {
await stakingAuRa.setCurrentBlockNumber(block).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(false);
}
await stakingAuRa.setStakingEpochStartBlock(153).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(152).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(false);
await stakingAuRa.setCurrentBlockNumber(153).should.be.fulfilled;
(await stakingAuRa.areStakeAndWithdrawAllowed.call()).should.be.equal(true);
});
});
describe('balance', async () => {
let erc677Token;
let mintAmount;
beforeEach(async () => {
// Deploy ERC677 contract
erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for an arbitrary address
const stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(accounts[10], mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(accounts[10]));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(
await erc677Token.stakingContract.call()
);
});
it('cannot be increased by token.transfer function', async () => {
await erc677Token.transfer(stakingAuRa.address, mintAmount, {from: accounts[10]}).should.be.rejectedWith(ERROR_MSG);
await erc677Token.transfer(accounts[11], mintAmount, {from: accounts[10]}).should.be.fulfilled;
});
it('cannot be increased by token.transferFrom function', async () => {
await erc677Token.approve(accounts[9], mintAmount, {from: accounts[10]}).should.be.fulfilled;
await erc677Token.transferFrom(accounts[10], stakingAuRa.address, mintAmount, {from: accounts[9]}).should.be.rejectedWith(ERROR_MSG);
await erc677Token.transferFrom(accounts[10], accounts[11], mintAmount, {from: accounts[9]}).should.be.fulfilled;
});
it('cannot be increased by token.transferAndCall function with an empty data param', async () => {
await erc677Token.transferAndCall(stakingAuRa.address, mintAmount, [], {from: accounts[10]}).should.be.rejectedWith(ERROR_MSG);
await erc677Token.transferAndCall(accounts[11], mintAmount, [], {from: accounts[10]}).should.be.fulfilled;
});
it('cannot be increased by sending native coins', async () => {
await web3.eth.sendTransaction({from: owner, to: stakingAuRa.address, value: 1}).should.be.rejectedWith(ERROR_MSG);
await web3.eth.sendTransaction({from: owner, to: accounts[1], value: 1}).should.be.fulfilled;
});
});
describe('claimReward()', async () => {
let delegator;
let delegatorMinStake;
let erc677Token;
beforeEach(async () => {
// Initialize BlockRewardAuRa
await blockRewardAuRa.initialize(
validatorSetAuRa.address,
'0x0000000000000000000000000000000000000000'
).should.be.fulfilled;
// Initialize RandomAuRa
await randomAuRa.initialize(
114, // _collectRoundLength
validatorSetAuRa.address,
true
).should.be.fulfilled;
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
// Start the network
await setCurrentBlockNumber(1);
await callFinalizeChange();
(await validatorSetAuRa.validatorSetApplyBlock.call()).should.be.bignumber.equal(new BN(1));
// Deploy ERC677 contract
erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
await erc677Token.setBlockRewardContract(blockRewardAuRa.address).should.be.fulfilled;
await erc677Token.setStakingContract(stakingAuRa.address).should.be.fulfilled;
// Validators place stakes during the epoch #0
const candidateMinStake = await stakingAuRa.candidateMinStake.call();
for (let i = 0; i < initialStakingAddresses.length; i++) {
// Mint some balance for each validator (imagine that each validator got the tokens from a bridge)
await erc677Token.mint(initialStakingAddresses[i], candidateMinStake, {from: owner}).should.be.fulfilled;
candidateMinStake.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[i]));
// Validator places stake on themselves
await stakingAuRa.stake(initialStakingAddresses[i], candidateMinStake, {from: initialStakingAddresses[i]}).should.be.fulfilled;
}
// Mint some balance for a delegator (imagine that the delegator got the tokens from a bridge)
delegator = accounts[10];
delegatorMinStake = await stakingAuRa.delegatorMinStake.call();
await erc677Token.mint(delegator, delegatorMinStake, {from: owner}).should.be.fulfilled;
delegatorMinStake.should.be.bignumber.equal(await erc677Token.balanceOf.call(delegator));
// The delegator places stake on the first validator
await stakingAuRa.stake(initialStakingAddresses[0], delegatorMinStake, {from: delegator}).should.be.fulfilled;
// Staking epoch #0 finishes
const stakingEpochEndBlock = (await stakingAuRa.stakingEpochStartBlock.call()).add(new BN(120954));
await setCurrentBlockNumber(stakingEpochEndBlock);
const blocksCreated = stakingEpochEndBlock.sub(await validatorSetAuRa.validatorSetApplyBlock.call()).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(0), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
await callReward();
});
async function _claimRewardStakeIncreasing(epochsPoolRewarded, epochsStakeIncreased) {
const miningAddress = initialValidators[0];
const stakingAddress = initialStakingAddresses[0];
const poolId = initialPoolIds[0];
const epochPoolReward = new BN(web3.utils.toWei('1', 'ether'));
const maxStakingEpoch = Math.max(Math.max.apply(null, epochsPoolRewarded), Math.max.apply(null, epochsStakeIncreased));
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(await web3.eth.getBalance(blockRewardAuRa.address)).should.be.equal('0');
// Emulate rewards for the pool
for (let i = 0; i < epochsPoolRewarded.length; i++) {
const stakingEpoch = epochsPoolRewarded[i];
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
}
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(epochsPoolRewarded.length)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(epochsPoolRewarded.length)));
let prevStakingEpoch = 0;
const validatorStakeAmount = await stakingAuRa.stakeAmount.call(poolId, '0x0000000000000000000000000000000000000000');
let stakeAmount = await stakingAuRa.stakeAmount.call(poolId, delegator);
let stakeAmountOnEpoch = [new BN(0)];
let s = 0;
for (let epoch = 1; epoch <= maxStakingEpoch; epoch++) {
const stakingEpoch = epochsStakeIncreased[s];
if (stakingEpoch == epoch) {
const stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
// Emulate delegator's stake increasing
await erc677Token.mint(delegator, delegatorMinStake, {from: owner}).should.be.fulfilled;
delegatorMinStake.should.be.bignumber.equal(await erc677Token.balanceOf.call(delegator));
await stakingAuRa.stake(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
for (let e = prevStakingEpoch + 1; e <= stakingEpoch; e++) {
stakeAmountOnEpoch[e] = stakeAmount;
}
stakeAmount = await stakingAuRa.stakeAmount.call(poolId, delegator);
prevStakingEpoch = stakingEpoch;
s++;
}
// Emulate snapshotting for the pool
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, epoch + 1, poolId).should.be.fulfilled;
}
const lastEpochRewarded = epochsPoolRewarded[epochsPoolRewarded.length - 1];
await stakingAuRa.setStakingEpoch(lastEpochRewarded + 1).should.be.fulfilled;
if (prevStakingEpoch < lastEpochRewarded) {
for (let e = prevStakingEpoch + 1; e <= lastEpochRewarded; e++) {
stakeAmountOnEpoch[e] = stakeAmount;
}
}
let delegatorRewardExpected = new BN(0);
let validatorRewardExpected = new BN(0);
for (let i = 0; i < epochsPoolRewarded.length; i++) {
const stakingEpoch = epochsPoolRewarded[i];
await blockRewardAuRa.setValidatorMinRewardPercent(stakingEpoch, 30);
const delegatorShare = await blockRewardAuRa.delegatorShare.call(
stakingEpoch,
stakeAmountOnEpoch[stakingEpoch],
validatorStakeAmount,
validatorStakeAmount.add(stakeAmountOnEpoch[stakingEpoch]),
epochPoolReward
);
const validatorShare = await blockRewardAuRa.validatorShare.call(
stakingEpoch,
validatorStakeAmount,
validatorStakeAmount.add(stakeAmountOnEpoch[stakingEpoch]),
epochPoolReward
);
delegatorRewardExpected = delegatorRewardExpected.add(delegatorShare);
validatorRewardExpected = validatorRewardExpected.add(validatorShare);
}
return {
delegatorMinStake,
miningAddress,
stakingAddress,
epochPoolReward,
maxStakingEpoch,
delegatorRewardExpected,
validatorRewardExpected
};
}
async function _delegatorNeverStakedBefore() {
const miningAddress = initialValidators[0];
const stakingAddress = initialStakingAddresses[0];
const poolId = initialPoolIds[0];
const epochPoolReward = new BN(web3.utils.toWei('1', 'ether'));
let unclaimedReward = new BN(0);
// Emulate the fact that the delegator never staked before
let stakingEpoch = 1;
let stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await callFinalizeChange();
await stakingAuRa.orderWithdraw(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
let stakingEpochEndBlock = stakingEpochStartBlock.add(new BN(120954 - 1));
await setCurrentBlockNumber(stakingEpochEndBlock);
let blocksCreated = stakingEpochEndBlock.sub(await validatorSetAuRa.validatorSetApplyBlock.call()).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(stakingEpoch), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
await callReward(); // finish staking epoch #1
unclaimedReward = unclaimedReward.add((await stakingAuRa.getRewardAmount.call([], stakingAddress, delegator)).tokenRewardSum);
stakingEpoch = 2;
stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await callFinalizeChange();
await stakingAuRa.claimOrderedWithdraw(stakingAddress, {from: delegator}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(poolId, delegator)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.orderedWithdrawAmount.call(poolId, delegator)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeFirstEpoch.call(poolId, delegator)).should.be.bignumber.equal(new BN(1));
(await stakingAuRa.stakeLastEpoch.call(poolId, delegator)).should.be.bignumber.equal(new BN(2));
await stakingAuRa.setStakeFirstEpoch(poolId, delegator, new BN(0)).should.be.fulfilled;
await stakingAuRa.setStakeLastEpoch(poolId, delegator, new BN(0)).should.be.fulfilled;
await stakingAuRa.clearDelegatorStakeSnapshot(poolId, delegator, new BN(1)).should.be.fulfilled;
await stakingAuRa.clearDelegatorStakeSnapshot(poolId, delegator, new BN(2)).should.be.fulfilled;
stakingEpochEndBlock = stakingEpochStartBlock.add(new BN(120954 - 1));
await setCurrentBlockNumber(stakingEpochEndBlock);
blocksCreated = stakingEpochEndBlock.sub(await validatorSetAuRa.validatorSetApplyBlock.call()).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(stakingEpoch), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
await callReward(); // finish staking epoch #2
for (let i = 0; i < initialStakingAddresses.length; i++) {
unclaimedReward = unclaimedReward.add((await stakingAuRa.getRewardAmount.call([], initialStakingAddresses[i], initialStakingAddresses[i])).tokenRewardSum);
}
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(3));
return {miningAddress, stakingAddress, poolId, epochPoolReward, unclaimedReward};
}
async function testClaimRewardRandom(epochsPoolRewarded, epochsStakeIncreased) {
const {
delegatorMinStake,
miningAddress,
stakingAddress,
epochPoolReward,
maxStakingEpoch,
delegatorRewardExpected,
validatorRewardExpected
} = await _claimRewardStakeIncreasing(
epochsPoolRewarded,
epochsStakeIncreased
);
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
let weiSpent = new BN(0);
let epochsPoolRewardedRandom = epochsPoolRewarded;
shuffle(epochsPoolRewardedRandom);
for (let i = 0; i < epochsPoolRewardedRandom.length; i++) {
const stakingEpoch = epochsPoolRewardedRandom[i];
let result = await stakingAuRa.claimReward([stakingEpoch], stakingAddress, {from: delegator}).should.be.fulfilled;
let tx = await web3.eth.getTransaction(result.tx);
weiSpent = weiSpent.add((new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice)));
// Call once again to ensure the reward cannot be withdrawn twice
result = await stakingAuRa.claimReward([stakingEpoch], stakingAddress, {from: delegator}).should.be.fulfilled;
tx = await web3.eth.getTransaction(result.tx);
weiSpent = weiSpent.add((new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice)));
}
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(delegatorRewardExpected));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(delegatorRewardExpected).sub(weiSpent));
const validatorTokensBalanceBefore = await erc677Token.balanceOf.call(stakingAddress);
const validatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(stakingAddress));
weiSpent = new BN(0);
shuffle(epochsPoolRewardedRandom);
for (let i = 0; i < epochsPoolRewardedRandom.length; i++) {
const stakingEpoch = epochsPoolRewardedRandom[i];
const result = await stakingAuRa.claimReward([stakingEpoch], stakingAddress, {from: stakingAddress}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
weiSpent = weiSpent.add((new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice)));
}
const validatorTokensBalanceAfter = await erc677Token.balanceOf.call(stakingAddress);
const validatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(stakingAddress));
validatorTokensBalanceAfter.should.be.bignumber.equal(validatorTokensBalanceBefore.add(validatorRewardExpected));
validatorCoinsBalanceAfter.should.be.bignumber.equal(validatorCoinsBalanceBefore.add(validatorRewardExpected).sub(weiSpent));
const blockRewardBalanceExpected = epochPoolReward.mul(new BN(epochsPoolRewarded.length)).sub(delegatorRewardExpected).sub(validatorRewardExpected);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardBalanceExpected);
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(blockRewardBalanceExpected);
}
async function testClaimRewardAfterStakeIncreasing(epochsPoolRewarded, epochsStakeIncreased) {
const {
delegatorMinStake,
miningAddress,
stakingAddress,
epochPoolReward,
maxStakingEpoch,
delegatorRewardExpected,
validatorRewardExpected
} = await _claimRewardStakeIncreasing(
epochsPoolRewarded,
epochsStakeIncreased
);
let rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([], stakingAddress, delegator);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(delegatorRewardExpected);
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(delegatorRewardExpected);
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
const result = await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(delegatorRewardExpected));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(delegatorRewardExpected).sub(weiSpent));
rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([], stakingAddress, stakingAddress);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(validatorRewardExpected);
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(validatorRewardExpected);
await stakingAuRa.claimReward([], stakingAddress, {from: stakingAddress}).should.be.fulfilled;
const blockRewardBalanceExpected = epochPoolReward.mul(new BN(epochsPoolRewarded.length)).sub(delegatorRewardExpected).sub(validatorRewardExpected);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardBalanceExpected);
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(blockRewardBalanceExpected);
}
async function testClaimRewardAfterStakeMovements(epochsPoolRewarded, epochsStakeMovement) {
const miningAddress = initialValidators[0];
const stakingAddress = initialStakingAddresses[0];
const poolId = initialPoolIds[0];
const epochPoolReward = new BN(web3.utils.toWei('1', 'ether'));
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(await web3.eth.getBalance(blockRewardAuRa.address)).should.be.equal('0');
for (let i = 0; i < epochsPoolRewarded.length; i++) {
const stakingEpoch = epochsPoolRewarded[i];
// Emulate snapshotting for the pool
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, poolId).should.be.fulfilled;
// Emulate rewards for the pool
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
}
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(epochsPoolRewarded.length)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(epochsPoolRewarded.length)));
for (let i = 0; i < epochsStakeMovement.length; i++) {
const stakingEpoch = epochsStakeMovement[i];
// Emulate delegator's stake movement
const stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await stakingAuRa.orderWithdraw(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
await stakingAuRa.orderWithdraw(stakingAddress, delegatorMinStake.neg(), {from: delegator}).should.be.fulfilled;
}
const stakeFirstEpoch = await stakingAuRa.stakeFirstEpoch.call(poolId, delegator);
await stakingAuRa.setStakeFirstEpoch(poolId, delegator, 0);
await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setStakeFirstEpoch(poolId, delegator, stakeFirstEpoch);
if (epochsPoolRewarded.length > 0) {
if (epochsPoolRewarded.length > 1) {
const reversedEpochsPoolRewarded = [...epochsPoolRewarded].reverse();
await stakingAuRa.claimReward(reversedEpochsPoolRewarded, stakingAddress, {from: delegator}).should.be.rejectedWith(ERROR_MSG);
}
await stakingAuRa.setStakingEpoch(epochsPoolRewarded[epochsPoolRewarded.length - 1]).should.be.fulfilled;
await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setStakingEpoch(epochsPoolRewarded[epochsPoolRewarded.length - 1] + 1).should.be.fulfilled;
if (epochsPoolRewarded.length == 1) {
const validatorStakeAmount = await blockRewardAuRa.snapshotPoolValidatorStakeAmount.call(epochsPoolRewarded[0], poolId);
await blockRewardAuRa.setSnapshotPoolValidatorStakeAmount(epochsPoolRewarded[0], miningAddress, 0);
const result = await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.fulfilled;
result.logs.length.should.be.equal(1);
result.logs[0].args.tokensAmount.should.be.bignumber.equal(new BN(0));
result.logs[0].args.nativeCoinsAmount.should.be.bignumber.equal(new BN(0));
await blockRewardAuRa.setSnapshotPoolValidatorStakeAmount(epochsPoolRewarded[0], miningAddress, validatorStakeAmount);
await stakingAuRa.clearRewardWasTaken(poolId, delegator, epochsPoolRewarded[0]);
}
}
const delegatorRewardExpected = epochPoolReward.mul(new BN(epochsPoolRewarded.length)).div(new BN(2));
const rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([], stakingAddress, delegator);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(delegatorRewardExpected);
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(delegatorRewardExpected);
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
let weiSpent = new BN(0);
for (let i = 0; i < 3; i++) {
// We call `claimReward` several times, but it withdraws the reward only once
const result = await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
weiSpent = weiSpent.add((new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice)));
}
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(delegatorRewardExpected));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(delegatorRewardExpected).sub(weiSpent));
for (let i = 0; i < 3; i++) {
// We call `claimReward` several times, but it withdraws the reward only once
const result = await stakingAuRa.claimReward([], stakingAddress, {from: stakingAddress}).should.be.fulfilled;
if (i == 0) {
result.logs.length.should.be.equal(epochsPoolRewarded.length);
} else {
result.logs.length.should.be.equal(0);
}
}
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(new BN(0));
}
it('reward tries to be withdrawn before first stake', async () => {
let {
miningAddress,
stakingAddress,
poolId,
epochPoolReward,
unclaimedReward
} = await _delegatorNeverStakedBefore();
const blockRewardInitialBalance = await erc677Token.balanceOf.call(blockRewardAuRa.address);
// Emulate snapshotting and rewards for the pool on the epoch #9
let stakingEpoch = 9;
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, poolId).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
unclaimedReward = unclaimedReward.add(epochPoolReward);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardInitialBalance.add(epochPoolReward));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward);
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate the delegator's first stake on epoch #10
stakingEpoch = 10;
stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await stakingAuRa.stake(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
unclaimedReward = unclaimedReward.add(epochPoolReward);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardInitialBalance.add(epochPoolReward.mul(new BN(2))));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(2)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate rewards for the pool on epoch #11
stakingEpoch = 11;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
unclaimedReward = unclaimedReward.add(epochPoolReward);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardInitialBalance.add(epochPoolReward.mul(new BN(3))));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(3)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
await stakingAuRa.setStakingEpoch(12).should.be.fulfilled;
const rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([9, 10], stakingAddress, delegator);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(new BN(0));
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(new BN(0));
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
let result = await stakingAuRa.claimReward([9, 10], stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
result.logs.length.should.be.equal(0);
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore);
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.sub(weiSpent));
const stakeTokenInflationRate = await blockRewardAuRa.STAKE_TOKEN_INFLATION_RATE.call();
result = await stakingAuRa.claimReward([], stakingAddress, {from: stakingAddress}).should.be.fulfilled;
if (stakeTokenInflationRate == 0) {
result.logs.length.should.be.equal(3);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(9));
result.logs[1].args.stakingEpoch.should.be.bignumber.equal(new BN(10));
result.logs[2].args.stakingEpoch.should.be.bignumber.equal(new BN(11));
} else {
result.logs.length.should.be.equal(5);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(1));
result.logs[1].args.stakingEpoch.should.be.bignumber.equal(new BN(2));
result.logs[2].args.stakingEpoch.should.be.bignumber.equal(new BN(9));
result.logs[3].args.stakingEpoch.should.be.bignumber.equal(new BN(10));
result.logs[4].args.stakingEpoch.should.be.bignumber.equal(new BN(11));
}
for (let i = 0; i < result.logs.length; i++) {
unclaimedReward = unclaimedReward.sub(result.logs[i].args.tokensAmount);
}
result = await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.fulfilled;
result.logs.length.should.be.equal(1);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(11));
unclaimedReward = unclaimedReward.sub(result.logs[0].args.tokensAmount);
const blockRewardTokenBalance = await erc677Token.balanceOf.call(blockRewardAuRa.address);
blockRewardTokenBalance.sub(unclaimedReward).should.be.bignumber.lte(new BN(1)); // because of rounding error
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeFirstEpoch.call(poolId, delegator)).should.be.bignumber.equal(new BN(11));
(await stakingAuRa.stakeLastEpoch.call(poolId, delegator)).should.be.bignumber.equal(new BN(0));
});
it('delegator stakes and withdraws at the same epoch', async () => {
let {
miningAddress,
stakingAddress,
poolId,
epochPoolReward,
unclaimedReward
} = await _delegatorNeverStakedBefore();
const blockRewardInitialBalance = await erc677Token.balanceOf.call(blockRewardAuRa.address);
// Emulate snapshotting and rewards for the pool on the epoch #9
let stakingEpoch = 9;
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, poolId).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
unclaimedReward = unclaimedReward.add(epochPoolReward);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardInitialBalance.add(epochPoolReward));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward);
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate the delegator's first stake and withdrawal on epoch #10
stakingEpoch = 10;
stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await stakingAuRa.stake(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
await stakingAuRa.withdraw(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
unclaimedReward = unclaimedReward.add(epochPoolReward);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardInitialBalance.add(epochPoolReward.mul(new BN(2))));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(2)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate rewards for the pool on epoch #11
stakingEpoch = 11;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
unclaimedReward = unclaimedReward.add(epochPoolReward);
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(blockRewardInitialBalance.add(epochPoolReward.mul(new BN(3))));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(3)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
await stakingAuRa.setStakingEpoch(12).should.be.fulfilled;
const rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([], stakingAddress, delegator);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(new BN(0));
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(new BN(0));
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
let result = await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
result.logs.length.should.be.equal(0);
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore);
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.sub(weiSpent));
const stakeTokenInflationRate = await blockRewardAuRa.STAKE_TOKEN_INFLATION_RATE.call();
result = await stakingAuRa.claimReward([], stakingAddress, {from: stakingAddress}).should.be.fulfilled;
if (stakeTokenInflationRate == 0) {
result.logs.length.should.be.equal(3);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(9));
result.logs[1].args.stakingEpoch.should.be.bignumber.equal(new BN(10));
result.logs[2].args.stakingEpoch.should.be.bignumber.equal(new BN(11));
} else {
result.logs.length.should.be.equal(5);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(1));
result.logs[1].args.stakingEpoch.should.be.bignumber.equal(new BN(2));
result.logs[2].args.stakingEpoch.should.be.bignumber.equal(new BN(9));
result.logs[3].args.stakingEpoch.should.be.bignumber.equal(new BN(10));
result.logs[4].args.stakingEpoch.should.be.bignumber.equal(new BN(11));
}
for (let i = 0; i < result.logs.length; i++) {
unclaimedReward = unclaimedReward.sub(result.logs[i].args.tokensAmount);
}
const blockRewardTokenBalance = await erc677Token.balanceOf.call(blockRewardAuRa.address);
blockRewardTokenBalance.sub(unclaimedReward).should.be.bignumber.lte(new BN(1)); // because of rounding error
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeFirstEpoch.call(poolId, delegator)).should.be.bignumber.equal(new BN(11));
(await stakingAuRa.stakeLastEpoch.call(poolId, delegator)).should.be.bignumber.equal(new BN(11));
});
it('non-rewarded epochs are passed', async () => {
const miningAddress = initialValidators[0];
const stakingAddress = initialStakingAddresses[0];
const poolId = initialPoolIds[0];
const epochPoolReward = new BN(web3.utils.toWei('1', 'ether'));
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(await web3.eth.getBalance(blockRewardAuRa.address)).should.be.equal('0');
const epochsPoolRewarded = [10, 20, 30, 40, 50];
for (let i = 0; i < epochsPoolRewarded.length; i++) {
const stakingEpoch = epochsPoolRewarded[i];
// Emulate snapshotting for the pool
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, poolId).should.be.fulfilled;
// Emulate rewards for the pool
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
}
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(epochsPoolRewarded.length)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(epochsPoolRewarded.length)));
await stakingAuRa.setStakingEpoch(51);
const epochsToWithdrawFrom = [15, 25, 35, 45];
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
const result = await stakingAuRa.claimReward(epochsToWithdrawFrom, stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
result.logs.length.should.be.equal(epochsToWithdrawFrom.length);
for (let i = 0; i < result.logs.length; i++) {
result.logs[i].args.stakingEpoch.should.be.bignumber.equal(new BN(epochsToWithdrawFrom[i]));
result.logs[i].args.tokensAmount.should.be.bignumber.equal(new BN(0));
result.logs[i].args.nativeCoinsAmount.should.be.bignumber.equal(new BN(0));
}
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore);
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.sub(weiSpent));
});
it('stake movements', async () => {
await testClaimRewardAfterStakeMovements(
[5, 15, 25, 35],
[10, 20, 30]
);
});
it('stake movements', async () => {
await testClaimRewardAfterStakeMovements(
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9]
);
});
it('stake movements', async () => {
await testClaimRewardAfterStakeMovements(
[1, 3, 6, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
);
});
it('stake movements', async () => {
await testClaimRewardAfterStakeMovements(
[],
[1, 2, 3]
);
});
it('stake movements', async () => {
await testClaimRewardAfterStakeMovements(
[2],
[1, 2, 3]
);
});
it('stake increasing', async () => {
await testClaimRewardAfterStakeIncreasing(
[5, 15, 25, 35],
[4, 14, 24, 34]
);
});
it('stake increasing', async () => {
await testClaimRewardAfterStakeIncreasing(
[5, 15, 25, 35],
[10, 20, 30]
);
});
it('stake increasing', async () => {
await testClaimRewardAfterStakeIncreasing(
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5]
);
});
it('stake increasing', async () => {
await testClaimRewardAfterStakeIncreasing(
[1, 3, 6, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
);
});
it('stake increasing', async () => {
await testClaimRewardAfterStakeIncreasing(
[5, 15, 25],
[5, 15, 25]
);
});
it('stake increasing', async () => {
await testClaimRewardAfterStakeIncreasing(
[5, 7, 9],
[6, 8, 10]
);
});
it('random withdrawal', async () => {
await testClaimRewardRandom(
[5, 15, 25, 35],
[4, 14, 24, 34]
);
});
it('random withdrawal', async () => {
await testClaimRewardRandom(
[5, 15, 25, 35],
[10, 20, 30]
);
});
it('random withdrawal', async () => {
await testClaimRewardRandom(
[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5]
);
});
it('random withdrawal', async () => {
await testClaimRewardRandom(
[1, 3, 6, 10],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
);
});
it('random withdrawal', async () => {
await testClaimRewardRandom(
[5, 15, 25],
[5, 15, 25]
);
});
it('random withdrawal', async () => {
await testClaimRewardRandom(
[5, 7, 9],
[6, 8, 10]
);
});
it('reward is got from the first epoch', async () => {
await testClaimRewardAfterStakeMovements([1], []);
});
it('stake is withdrawn forever', async () => {
const miningAddress = initialValidators[0];
const stakingAddress = initialStakingAddresses[0];
const poolId = initialPoolIds[0];
const epochPoolReward = new BN(web3.utils.toWei('1', 'ether'));
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(await web3.eth.getBalance(blockRewardAuRa.address)).should.be.equal('0');
let stakingEpoch;
// Emulate snapshotting and rewards for the pool
stakingEpoch = 9;
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, poolId).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward);
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward);
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate delegator's stake withdrawal
stakingEpoch = 10;
const stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await stakingAuRa.orderWithdraw(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(2)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(2)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate rewards for the pool
stakingEpoch = 11;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(3)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(3)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
await stakingAuRa.setStakingEpoch(12).should.be.fulfilled;
const delegatorRewardExpected = epochPoolReward.mul(new BN(2)).div(new BN(2));
const rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([], stakingAddress, delegator);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(delegatorRewardExpected);
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(delegatorRewardExpected);
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
let result = await stakingAuRa.claimReward([], stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
result.logs.length.should.be.equal(2);
result.logs[0].event.should.be.equal("ClaimedReward");
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(9));
result.logs[0].args.tokensAmount.should.be.bignumber.equal(epochPoolReward.div(new BN(2)));
result.logs[0].args.nativeCoinsAmount.should.be.bignumber.equal(epochPoolReward.div(new BN(2)));
result.logs[1].event.should.be.equal("ClaimedReward");
result.logs[1].args.stakingEpoch.should.be.bignumber.equal(new BN(10));
result.logs[1].args.tokensAmount.should.be.bignumber.equal(epochPoolReward.div(new BN(2)));
result.logs[1].args.nativeCoinsAmount.should.be.bignumber.equal(epochPoolReward.div(new BN(2)));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(delegatorRewardExpected));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(delegatorRewardExpected).sub(weiSpent));
result = await stakingAuRa.claimReward([], stakingAddress, {from: stakingAddress}).should.be.fulfilled;
result.logs.length.should.be.equal(3);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(9));
result.logs[1].args.stakingEpoch.should.be.bignumber.equal(new BN(10));
result.logs[2].args.stakingEpoch.should.be.bignumber.equal(new BN(11));
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(new BN(0));
});
it('stake is withdrawn forever', async () => {
const miningAddress = initialValidators[0];
const stakingAddress = initialStakingAddresses[0];
const poolId = initialPoolIds[0];
const epochPoolReward = new BN(web3.utils.toWei('1', 'ether'));
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(new BN(0));
(await web3.eth.getBalance(blockRewardAuRa.address)).should.be.equal('0');
let stakingEpoch;
// Emulate snapshotting and rewards for the pool
stakingEpoch = 9;
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, poolId).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward);
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward);
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate delegator's stake withdrawal
stakingEpoch = 10;
const stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
await stakingAuRa.orderWithdraw(stakingAddress, delegatorMinStake, {from: delegator}).should.be.fulfilled;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(2)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(2)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
// Emulate rewards for the pool
stakingEpoch = 11;
await blockRewardAuRa.setEpochPoolReward(stakingEpoch, miningAddress, epochPoolReward, {value: epochPoolReward}).should.be.fulfilled;
(await erc677Token.balanceOf.call(blockRewardAuRa.address)).should.be.bignumber.equal(epochPoolReward.mul(new BN(3)));
(new BN(await web3.eth.getBalance(blockRewardAuRa.address))).should.be.bignumber.equal(epochPoolReward.mul(new BN(3)));
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch + 1, poolId).should.be.fulfilled;
await stakingAuRa.setStakingEpoch(12).should.be.fulfilled;
const rewardAmountsCalculated = await stakingAuRa.getRewardAmount.call([11], stakingAddress, delegator);
rewardAmountsCalculated.tokenRewardSum.should.be.bignumber.equal(new BN(0));
rewardAmountsCalculated.nativeRewardSum.should.be.bignumber.equal(new BN(0));
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
const result = await stakingAuRa.claimReward([11], stakingAddress, {from: delegator}).should.be.fulfilled;
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
result.logs.length.should.be.equal(0);
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore);
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.sub(weiSpent));
});
it('gas consumption for one staking epoch is OK', async () => {
const stakingEpoch = 2600;
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, stakingEpoch, initialPoolIds[i]);
}
await stakingAuRa.setStakingEpoch(stakingEpoch).should.be.fulfilled;
const stakingEpochStartBlock = new BN(120954 * stakingEpoch + 1);
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(stakingEpochStartBlock).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await setCurrentBlockNumber(stakingEpochStartBlock);
let result = await validatorSetAuRa.emitInitiateChange().should.be.fulfilled;
result.logs[0].event.should.be.equal("InitiateChange");
result.logs[0].args.newSet.should.be.deep.equal(initialValidators);
const currentBlock = stakingEpochStartBlock.add(new BN(Math.floor(initialValidators.length / 2) + 1));
await setCurrentBlockNumber(currentBlock);
(await validatorSetAuRa.validatorSetApplyBlock.call()).should.be.bignumber.equal(new BN(0));
await callFinalizeChange();
const validatorSetApplyBlock = await validatorSetAuRa.validatorSetApplyBlock.call();
validatorSetApplyBlock.should.be.bignumber.equal(currentBlock);
(await validatorSetAuRa.getValidators.call()).should.be.deep.equal(initialValidators);
await accrueBridgeFees();
const stakingEpochEndBlock = stakingEpochStartBlock.add(new BN(120954 - 1));
await setCurrentBlockNumber(stakingEpochEndBlock);
const blocksCreated = stakingEpochEndBlock.sub(validatorSetApplyBlock).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(stakingEpoch), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
let blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
let blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
for (let i = 0; i < initialValidators.length; i++) {
(await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
(await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
}
await callReward();
(await validatorSetAuRa.validatorSetApplyBlock.call()).should.be.bignumber.equal(new BN(0));
let distributedTokensAmount = new BN(0);
let distributedCoinsAmount = new BN(0);
for (let i = 0; i < initialValidators.length; i++) {
const epochPoolTokenReward = await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i]);
const epochPoolNativeReward = await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i]);
epochPoolTokenReward.should.be.bignumber.above(new BN(0));
epochPoolNativeReward.should.be.bignumber.above(new BN(0));
distributedTokensAmount = distributedTokensAmount.add(epochPoolTokenReward);
distributedCoinsAmount = distributedCoinsAmount.add(epochPoolNativeReward);
}
let blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
let blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.add(distributedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.add(distributedCoinsAmount));
// The delegator claims their rewards
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([stakingEpoch], initialStakingAddresses[0], delegator));
result = await stakingAuRa.claimReward([stakingEpoch], initialStakingAddresses[0], {from: delegator}).should.be.fulfilled;
result.logs[0].event.should.be.equal("ClaimedReward");
result.logs[0].args.fromPoolStakingAddress.should.be.equal(initialStakingAddresses[0]);
result.logs[0].args.staker.should.be.equal(delegator);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(stakingEpoch));
const claimedTokensAmount = result.logs[0].args.tokensAmount;
const claimedCoinsAmount = result.logs[0].args.nativeCoinsAmount;
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(claimedTokensAmount);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(claimedCoinsAmount);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
if (!!process.env.SOLIDITY_COVERAGE !== true) {
result.receipt.gasUsed.should.be.below(3020000);
}
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(claimedTokensAmount));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(claimedCoinsAmount).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(claimedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(claimedCoinsAmount));
});
it('gas consumption for one staking epoch is OK', async () => {
const maxStakingEpoch = 20;
maxStakingEpoch.should.be.above(2);
// Loop of staking epochs
for (let stakingEpoch = 1; stakingEpoch <= maxStakingEpoch; stakingEpoch++) {
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(stakingEpoch));
const stakingEpochStartBlock = await stakingAuRa.stakingEpochStartBlock.call();
stakingEpochStartBlock.should.be.bignumber.equal(new BN(120954 * stakingEpoch + 1));
await setCurrentBlockNumber(stakingEpochStartBlock);
const result = await validatorSetAuRa.emitInitiateChange().should.be.fulfilled;
result.logs[0].event.should.be.equal("InitiateChange");
result.logs[0].args.newSet.should.be.deep.equal(initialValidators);
const currentBlock = stakingEpochStartBlock.add(new BN(Math.floor(initialValidators.length / 2) + 1));
await setCurrentBlockNumber(currentBlock);
(await validatorSetAuRa.validatorSetApplyBlock.call()).should.be.bignumber.equal(new BN(0));
await callFinalizeChange();
const validatorSetApplyBlock = await validatorSetAuRa.validatorSetApplyBlock.call();
validatorSetApplyBlock.should.be.bignumber.equal(currentBlock);
(await validatorSetAuRa.getValidators.call()).should.be.deep.equal(initialValidators);
await accrueBridgeFees();
const stakingEpochEndBlock = stakingEpochStartBlock.add(new BN(120954 - 1));
await setCurrentBlockNumber(stakingEpochEndBlock);
const blocksCreated = stakingEpochEndBlock.sub(validatorSetApplyBlock).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(stakingEpoch), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
for (let i = 0; i < initialValidators.length; i++) {
(await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
(await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
}
await callReward();
let distributedTokensAmount = new BN(0);
let distributedCoinsAmount = new BN(0);
for (let i = 0; i < initialValidators.length; i++) {
const epochPoolTokenReward = await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i]);
const epochPoolNativeReward = await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i]);
epochPoolTokenReward.should.be.bignumber.above(new BN(0));
epochPoolNativeReward.should.be.bignumber.above(new BN(0));
distributedTokensAmount = distributedTokensAmount.add(epochPoolTokenReward);
distributedCoinsAmount = distributedCoinsAmount.add(epochPoolNativeReward);
}
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.add(distributedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.add(distributedCoinsAmount));
}
// The delegator claims their rewards
let initialGasConsumption = new BN(0);
let startGasConsumption = new BN(0);
let endGasConsumption = new BN(0);
let blockRewardTokensBalanceTotalBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
let blockRewardCoinsBalanceTotalBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
let tokensDelegatorGotForAllEpochs = new BN(0);
let coinsDelegatorGotForAllEpochs = new BN(0);
for (let stakingEpoch = 1; stakingEpoch <= maxStakingEpoch; stakingEpoch++) {
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([stakingEpoch], initialStakingAddresses[0], delegator));
let result = await stakingAuRa.claimReward([stakingEpoch], initialStakingAddresses[0], {from: delegator}).should.be.fulfilled;
result.logs[0].event.should.be.equal("ClaimedReward");
result.logs[0].args.fromPoolStakingAddress.should.be.equal(initialStakingAddresses[0]);
result.logs[0].args.staker.should.be.equal(delegator);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(stakingEpoch));
const claimedTokensAmount = result.logs[0].args.tokensAmount;
const claimedCoinsAmount = result.logs[0].args.nativeCoinsAmount;
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(claimedTokensAmount);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(claimedCoinsAmount);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
if (stakingEpoch == 1) {
initialGasConsumption = new BN(result.receipt.gasUsed);
} else if (stakingEpoch == 2) {
startGasConsumption = new BN(result.receipt.gasUsed);
} else if (stakingEpoch == maxStakingEpoch) {
endGasConsumption = new BN(result.receipt.gasUsed);
}
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(claimedTokensAmount));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(claimedCoinsAmount).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(claimedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(claimedCoinsAmount));
tokensDelegatorGotForAllEpochs = tokensDelegatorGotForAllEpochs.add(claimedTokensAmount);
coinsDelegatorGotForAllEpochs = coinsDelegatorGotForAllEpochs.add(claimedCoinsAmount);
// console.log(`stakingEpoch = ${stakingEpoch}, gasUsed = ${result.receipt.gasUsed}, cumulativeGasUsed = ${result.receipt.cumulativeGasUsed}`);
}
if (!!process.env.SOLIDITY_COVERAGE !== true) {
const perEpochGasConsumption = endGasConsumption.sub(startGasConsumption).div(new BN(maxStakingEpoch - 2));
perEpochGasConsumption.should.be.bignumber.below(new BN(1109));
// Check gas consumption for the case when the delegator didn't touch their
// stake for 50 years (2600 staking epochs)
const maxGasConsumption = initialGasConsumption.sub(perEpochGasConsumption).add(perEpochGasConsumption.mul(new BN(2600)));
maxGasConsumption.should.be.bignumber.below(new BN(3020000));
}
let blockRewardTokensBalanceTotalAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
let blockRewardCoinsBalanceTotalAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.equal(blockRewardTokensBalanceTotalBefore.sub(tokensDelegatorGotForAllEpochs));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.equal(blockRewardCoinsBalanceTotalBefore.sub(coinsDelegatorGotForAllEpochs));
// The validators claim their rewards
let tokensValidatorsGotForAllEpochs = new BN(0);
let coinsValidatorsGotForAllEpochs = new BN(0);
for (let v = 0; v < initialStakingAddresses.length; v++) {
for (let stakingEpoch = 1; stakingEpoch <= maxStakingEpoch; stakingEpoch++) {
const validator = initialStakingAddresses[v];
const validatorTokensBalanceBefore = await erc677Token.balanceOf.call(validator);
const validatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(validator));
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([stakingEpoch], validator, validator));
let result = await stakingAuRa.claimReward([stakingEpoch], validator, {from: validator}).should.be.fulfilled;
result.logs[0].event.should.be.equal("ClaimedReward");
result.logs[0].args.fromPoolStakingAddress.should.be.equal(validator);
result.logs[0].args.staker.should.be.equal(validator);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(stakingEpoch));
const claimedTokensAmount = result.logs[0].args.tokensAmount;
const claimedCoinsAmount = result.logs[0].args.nativeCoinsAmount;
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(claimedTokensAmount);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(claimedCoinsAmount);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const validatorTokensBalanceAfter = await erc677Token.balanceOf.call(validator);
const validatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(validator));
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
validatorTokensBalanceAfter.should.be.bignumber.equal(validatorTokensBalanceBefore.add(claimedTokensAmount));
validatorCoinsBalanceAfter.should.be.bignumber.equal(validatorCoinsBalanceBefore.add(claimedCoinsAmount).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(claimedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(claimedCoinsAmount));
tokensValidatorsGotForAllEpochs = tokensValidatorsGotForAllEpochs.add(claimedTokensAmount);
coinsValidatorsGotForAllEpochs = coinsValidatorsGotForAllEpochs.add(claimedCoinsAmount);
}
}
blockRewardTokensBalanceTotalAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
blockRewardCoinsBalanceTotalAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.equal(blockRewardTokensBalanceTotalBefore.sub(tokensDelegatorGotForAllEpochs).sub(tokensValidatorsGotForAllEpochs));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.equal(blockRewardCoinsBalanceTotalBefore.sub(coinsDelegatorGotForAllEpochs).sub(coinsValidatorsGotForAllEpochs));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.gte(new BN(0));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.gte(new BN(0));
});
it('gas consumption for 52 staking epochs (1 continuous year) is OK', async () => {
const maxStakingEpoch = 52;
// Loop of staking epochs
for (let stakingEpoch = 1; stakingEpoch <= maxStakingEpoch; stakingEpoch++) {
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(stakingEpoch));
const stakingEpochStartBlock = await stakingAuRa.stakingEpochStartBlock.call();
stakingEpochStartBlock.should.be.bignumber.equal(new BN(120954 * stakingEpoch + 1));
await setCurrentBlockNumber(stakingEpochStartBlock);
const result = await validatorSetAuRa.emitInitiateChange().should.be.fulfilled;
result.logs[0].event.should.be.equal("InitiateChange");
result.logs[0].args.newSet.should.be.deep.equal(initialValidators);
const currentBlock = stakingEpochStartBlock.add(new BN(Math.floor(initialValidators.length / 2) + 1));
await setCurrentBlockNumber(currentBlock);
(await validatorSetAuRa.validatorSetApplyBlock.call()).should.be.bignumber.equal(new BN(0));
await callFinalizeChange();
const validatorSetApplyBlock = await validatorSetAuRa.validatorSetApplyBlock.call();
validatorSetApplyBlock.should.be.bignumber.equal(currentBlock);
(await validatorSetAuRa.getValidators.call()).should.be.deep.equal(initialValidators);
await accrueBridgeFees();
const stakingEpochEndBlock = stakingEpochStartBlock.add(new BN(120954 - 1));
await setCurrentBlockNumber(stakingEpochEndBlock);
const blocksCreated = stakingEpochEndBlock.sub(validatorSetApplyBlock).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(stakingEpoch), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
for (let i = 0; i < initialValidators.length; i++) {
(await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
(await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
}
await callReward();
let distributedTokensAmount = new BN(0);
let distributedCoinsAmount = new BN(0);
for (let i = 0; i < initialValidators.length; i++) {
const epochPoolTokenReward = await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i]);
const epochPoolNativeReward = await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i]);
epochPoolTokenReward.should.be.bignumber.above(new BN(0));
epochPoolNativeReward.should.be.bignumber.above(new BN(0));
distributedTokensAmount = distributedTokensAmount.add(epochPoolTokenReward);
distributedCoinsAmount = distributedCoinsAmount.add(epochPoolNativeReward);
}
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.add(distributedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.add(distributedCoinsAmount));
}
// The delegator claims their rewards
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const blockRewardTokensBalanceTotalBefore = blockRewardTokensBalanceBefore;
const blockRewardCoinsBalanceTotalBefore = blockRewardCoinsBalanceBefore;
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([], initialStakingAddresses[0], delegator));
const result = await stakingAuRa.claimReward([], initialStakingAddresses[0], {from: delegator}).should.be.fulfilled;
let tokensDelegatorGotForAllEpochs = new BN(0);
let coinsDelegatorGotForAllEpochs = new BN(0);
for (let i = 0; i < maxStakingEpoch; i++) {
result.logs[i].event.should.be.equal("ClaimedReward");
result.logs[i].args.fromPoolStakingAddress.should.be.equal(initialStakingAddresses[0]);
result.logs[i].args.staker.should.be.equal(delegator);
result.logs[i].args.stakingEpoch.should.be.bignumber.equal(new BN(i + 1));
tokensDelegatorGotForAllEpochs = tokensDelegatorGotForAllEpochs.add(result.logs[i].args.tokensAmount);
coinsDelegatorGotForAllEpochs = coinsDelegatorGotForAllEpochs.add(result.logs[i].args.nativeCoinsAmount);
}
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(tokensDelegatorGotForAllEpochs);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(coinsDelegatorGotForAllEpochs);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
// console.log(`gasUsed = ${result.receipt.gasUsed}, cumulativeGasUsed = ${result.receipt.cumulativeGasUsed}`);
if (!!process.env.SOLIDITY_COVERAGE !== true) {
result.receipt.gasUsed.should.be.below(2200000);
}
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
tokensDelegatorGotForAllEpochs.should.be.bignumber.gte(new BN(0));
coinsDelegatorGotForAllEpochs.should.be.bignumber.gte(new BN(0));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(tokensDelegatorGotForAllEpochs));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(coinsDelegatorGotForAllEpochs).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(tokensDelegatorGotForAllEpochs));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(coinsDelegatorGotForAllEpochs));
// The validators claim their rewards
let tokensValidatorsGotForAllEpochs = new BN(0);
let coinsValidatorsGotForAllEpochs = new BN(0);
for (let v = 0; v < initialStakingAddresses.length; v++) {
const validator = initialStakingAddresses[v];
const validatorTokensBalanceBefore = await erc677Token.balanceOf.call(validator);
const validatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(validator));
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([], validator, validator));
const result = await stakingAuRa.claimReward([], validator, {from: validator}).should.be.fulfilled;
let claimedTokensAmount = new BN(0);
let claimedCoinsAmount = new BN(0);
for (let i = 0; i < maxStakingEpoch; i++) {
result.logs[i].event.should.be.equal("ClaimedReward");
result.logs[i].args.fromPoolStakingAddress.should.be.equal(validator);
result.logs[i].args.staker.should.be.equal(validator);
result.logs[i].args.stakingEpoch.should.be.bignumber.equal(new BN(i + 1));
claimedTokensAmount = claimedTokensAmount.add(result.logs[i].args.tokensAmount);
claimedCoinsAmount = claimedCoinsAmount.add(result.logs[i].args.nativeCoinsAmount);
}
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(claimedTokensAmount);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(claimedCoinsAmount);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const validatorTokensBalanceAfter = await erc677Token.balanceOf.call(validator);
const validatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(validator));
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
claimedTokensAmount.should.be.bignumber.gte(new BN(0));
claimedCoinsAmount.should.be.bignumber.gte(new BN(0));
validatorTokensBalanceAfter.should.be.bignumber.equal(validatorTokensBalanceBefore.add(claimedTokensAmount));
validatorCoinsBalanceAfter.should.be.bignumber.equal(validatorCoinsBalanceBefore.add(claimedCoinsAmount).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(claimedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(claimedCoinsAmount));
tokensValidatorsGotForAllEpochs = tokensValidatorsGotForAllEpochs.add(claimedTokensAmount);
coinsValidatorsGotForAllEpochs = coinsValidatorsGotForAllEpochs.add(claimedCoinsAmount);
}
const blockRewardTokensBalanceTotalAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceTotalAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.equal(blockRewardTokensBalanceTotalBefore.sub(tokensDelegatorGotForAllEpochs).sub(tokensValidatorsGotForAllEpochs));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.equal(blockRewardCoinsBalanceTotalBefore.sub(coinsDelegatorGotForAllEpochs).sub(coinsValidatorsGotForAllEpochs));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.gte(new BN(0));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.gte(new BN(0));
});
it('gas consumption for 52 staking epochs (10 years including gaps) is OK', async () => {
const maxStakingEpochs = 52;
const gapSize = 10;
// Loop of staking epochs
for (let s = 0; s < maxStakingEpochs; s++) {
const stakingEpoch = (await stakingAuRa.stakingEpoch.call()).toNumber();
const stakingEpochStartBlock = await stakingAuRa.stakingEpochStartBlock.call();
stakingEpochStartBlock.should.be.bignumber.equal(new BN(120954 * stakingEpoch + 1));
await setCurrentBlockNumber(stakingEpochStartBlock);
const result = await validatorSetAuRa.emitInitiateChange().should.be.fulfilled;
result.logs[0].event.should.be.equal("InitiateChange");
result.logs[0].args.newSet.should.be.deep.equal(initialValidators);
const currentBlock = stakingEpochStartBlock.add(new BN(Math.floor(initialValidators.length / 2) + 1));
await setCurrentBlockNumber(currentBlock);
(await validatorSetAuRa.validatorSetApplyBlock.call()).should.be.bignumber.equal(new BN(0));
await callFinalizeChange();
const validatorSetApplyBlock = await validatorSetAuRa.validatorSetApplyBlock.call();
validatorSetApplyBlock.should.be.bignumber.equal(currentBlock);
(await validatorSetAuRa.getValidators.call()).should.be.deep.equal(initialValidators);
await accrueBridgeFees();
const stakingEpochEndBlock = stakingEpochStartBlock.add(new BN(120954 - 1));
await setCurrentBlockNumber(stakingEpochEndBlock);
const blocksCreated = stakingEpochEndBlock.sub(validatorSetApplyBlock).div(new BN(initialValidators.length));
blocksCreated.should.be.bignumber.above(new BN(0));
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.setBlocksCreated(new BN(stakingEpoch), initialValidators[i], blocksCreated).should.be.fulfilled;
await randomAuRa.setSentReveal(initialValidators[i]).should.be.fulfilled;
}
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
for (let i = 0; i < initialValidators.length; i++) {
(await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
(await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i])).should.be.bignumber.equal(new BN(0));
}
await callReward();
let distributedTokensAmount = new BN(0);
let distributedCoinsAmount = new BN(0);
for (let i = 0; i < initialValidators.length; i++) {
const epochPoolTokenReward = await blockRewardAuRa.epochPoolTokenReward.call(stakingEpoch, initialPoolIds[i]);
const epochPoolNativeReward = await blockRewardAuRa.epochPoolNativeReward.call(stakingEpoch, initialPoolIds[i]);
epochPoolTokenReward.should.be.bignumber.above(new BN(0));
epochPoolNativeReward.should.be.bignumber.above(new BN(0));
distributedTokensAmount = distributedTokensAmount.add(epochPoolTokenReward);
distributedCoinsAmount = distributedCoinsAmount.add(epochPoolNativeReward);
}
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.add(distributedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.add(distributedCoinsAmount));
const nextStakingEpoch = stakingEpoch + gapSize; // jump through a few epochs
await stakingAuRa.setStakingEpoch(nextStakingEpoch).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(owner).should.be.fulfilled;
await stakingAuRa.setStakingEpochStartBlock(120954 * nextStakingEpoch + 1).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
for (let i = 0; i < initialValidators.length; i++) {
await blockRewardAuRa.snapshotPoolStakeAmounts(stakingAuRa.address, nextStakingEpoch, initialPoolIds[i]);
}
}
const epochsPoolGotRewardFor = await blockRewardAuRa.epochsPoolGotRewardFor.call(initialPoolIds[0]);
// The delegator claims their rewards
const delegatorTokensBalanceBefore = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(delegator));
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const blockRewardTokensBalanceTotalBefore = blockRewardTokensBalanceBefore;
const blockRewardCoinsBalanceTotalBefore = blockRewardCoinsBalanceBefore;
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([], initialStakingAddresses[0], delegator));
const result = await stakingAuRa.claimReward([], initialStakingAddresses[0], {from: delegator}).should.be.fulfilled;
let tokensDelegatorGotForAllEpochs = new BN(0);
let coinsDelegatorGotForAllEpochs = new BN(0);
for (let i = 0; i < maxStakingEpochs; i++) {
result.logs[i].event.should.be.equal("ClaimedReward");
result.logs[i].args.fromPoolStakingAddress.should.be.equal(initialStakingAddresses[0]);
result.logs[i].args.staker.should.be.equal(delegator);
result.logs[i].args.stakingEpoch.should.be.bignumber.equal(epochsPoolGotRewardFor[i]);
tokensDelegatorGotForAllEpochs = tokensDelegatorGotForAllEpochs.add(result.logs[i].args.tokensAmount);
coinsDelegatorGotForAllEpochs = coinsDelegatorGotForAllEpochs.add(result.logs[i].args.nativeCoinsAmount);
}
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(tokensDelegatorGotForAllEpochs);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(coinsDelegatorGotForAllEpochs);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
// console.log(`gasUsed = ${result.receipt.gasUsed}, cumulativeGasUsed = ${result.receipt.cumulativeGasUsed}`);
if (!!process.env.SOLIDITY_COVERAGE !== true) {
result.receipt.gasUsed.should.be.below(2700000);
}
const delegatorTokensBalanceAfter = await erc677Token.balanceOf.call(delegator);
const delegatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(delegator));
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
tokensDelegatorGotForAllEpochs.should.be.bignumber.gte(new BN(0));
coinsDelegatorGotForAllEpochs.should.be.bignumber.gte(new BN(0));
delegatorTokensBalanceAfter.should.be.bignumber.equal(delegatorTokensBalanceBefore.add(tokensDelegatorGotForAllEpochs));
delegatorCoinsBalanceAfter.should.be.bignumber.equal(delegatorCoinsBalanceBefore.add(coinsDelegatorGotForAllEpochs).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(tokensDelegatorGotForAllEpochs));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(coinsDelegatorGotForAllEpochs));
// The validators claim their rewards
let tokensValidatorsGotForAllEpochs = new BN(0);
let coinsValidatorsGotForAllEpochs = new BN(0);
for (let v = 0; v < initialStakingAddresses.length; v++) {
const validator = initialStakingAddresses[v];
const validatorTokensBalanceBefore = await erc677Token.balanceOf.call(validator);
const validatorCoinsBalanceBefore = new BN(await web3.eth.getBalance(validator));
const blockRewardTokensBalanceBefore = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceBefore = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
const expectedClaimRewardAmounts = (await stakingAuRa.getRewardAmount.call([], validator, validator));
const result = await stakingAuRa.claimReward([], validator, {from: validator}).should.be.fulfilled;
let claimedTokensAmount = new BN(0);
let claimedCoinsAmount = new BN(0);
for (let i = 0; i < maxStakingEpochs; i++) {
result.logs[i].event.should.be.equal("ClaimedReward");
result.logs[i].args.fromPoolStakingAddress.should.be.equal(validator);
result.logs[i].args.staker.should.be.equal(validator);
result.logs[i].args.stakingEpoch.should.be.bignumber.equal(epochsPoolGotRewardFor[i]);
claimedTokensAmount = claimedTokensAmount.add(result.logs[i].args.tokensAmount);
claimedCoinsAmount = claimedCoinsAmount.add(result.logs[i].args.nativeCoinsAmount);
}
expectedClaimRewardAmounts.tokenRewardSum.should.be.bignumber.equal(claimedTokensAmount);
expectedClaimRewardAmounts.nativeRewardSum.should.be.bignumber.equal(claimedCoinsAmount);
const tx = await web3.eth.getTransaction(result.tx);
const weiSpent = (new BN(result.receipt.gasUsed)).mul(new BN(tx.gasPrice));
const validatorTokensBalanceAfter = await erc677Token.balanceOf.call(validator);
const validatorCoinsBalanceAfter = new BN(await web3.eth.getBalance(validator));
const blockRewardTokensBalanceAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
claimedTokensAmount.should.be.bignumber.gte(new BN(0));
claimedCoinsAmount.should.be.bignumber.gte(new BN(0));
validatorTokensBalanceAfter.should.be.bignumber.equal(validatorTokensBalanceBefore.add(claimedTokensAmount));
validatorCoinsBalanceAfter.should.be.bignumber.equal(validatorCoinsBalanceBefore.add(claimedCoinsAmount).sub(weiSpent));
blockRewardTokensBalanceAfter.should.be.bignumber.equal(blockRewardTokensBalanceBefore.sub(claimedTokensAmount));
blockRewardCoinsBalanceAfter.should.be.bignumber.equal(blockRewardCoinsBalanceBefore.sub(claimedCoinsAmount));
tokensValidatorsGotForAllEpochs = tokensValidatorsGotForAllEpochs.add(claimedTokensAmount);
coinsValidatorsGotForAllEpochs = coinsValidatorsGotForAllEpochs.add(claimedCoinsAmount);
}
const blockRewardTokensBalanceTotalAfter = await erc677Token.balanceOf.call(blockRewardAuRa.address);
const blockRewardCoinsBalanceTotalAfter = new BN(await web3.eth.getBalance(blockRewardAuRa.address));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.equal(blockRewardTokensBalanceTotalBefore.sub(tokensDelegatorGotForAllEpochs).sub(tokensValidatorsGotForAllEpochs));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.equal(blockRewardCoinsBalanceTotalBefore.sub(coinsDelegatorGotForAllEpochs).sub(coinsValidatorsGotForAllEpochs));
blockRewardTokensBalanceTotalAfter.should.be.bignumber.gte(new BN(0));
blockRewardCoinsBalanceTotalAfter.should.be.bignumber.gte(new BN(0));
});
});
describe('clearUnremovableValidator()', async () => {
beforeEach(async () => {
// Deploy ValidatorSet contract
validatorSetAuRa = await ValidatorSetAuRa.new();
validatorSetAuRa = await AdminUpgradeabilityProxy.new(validatorSetAuRa.address, owner);
validatorSetAuRa = await ValidatorSetAuRa.at(validatorSetAuRa.address);
// Initialize ValidatorSet
await validatorSetAuRa.initialize(
blockRewardAuRa.address, // _blockRewardContract
'0x0000000000000000000000000000000000000000', // _governanceContract
'0x3000000000000000000000000000000000000001', // _randomContract
stakingAuRa.address, // _stakingContract
initialValidators, // _initialMiningAddresses
initialStakingAddresses, // _initialStakingAddresses
true // _firstValidatorIsUnremovable
).should.be.fulfilled;
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
});
it('should add validator pool to the poolsToBeElected list', async () => {
// Deploy ERC677 contract
const erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for the non-removable validator (imagine that the validator got 2 STAKE_UNITs from a bridge)
const stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
const mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(initialStakingAddresses[0], mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[0]));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(await erc677Token.stakingContract.call());
// Pass ERC677 contract address to Staking contract
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
erc677Token.address.should.be.equal(await stakingAuRa.erc677TokenContract.call());
// Emulate block number
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
// Place a stake for itself
await stakingAuRa.stake(initialStakingAddresses[0], stakeUnit.mul(new BN(1)), {from: initialStakingAddresses[0]}).should.be.fulfilled;
(await stakingAuRa.getPoolsToBeElected.call()).length.should.be.equal(0);
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.clearUnremovableValidator(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPoolsToBeElected.call()).should.be.deep.equal([
initialPoolIds[0]
]);
const likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(stakeUnit);
likelihoodInfo.sum.should.be.bignumber.equal(stakeUnit);
});
it('should add validator pool to the poolsToBeRemoved list', async () => {
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
(await stakingAuRa.getPoolsToBeRemoved.call()).should.be.deep.equal([
initialPoolIds[1],
initialPoolIds[2]
]);
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.clearUnremovableValidator(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPoolsToBeRemoved.call()).should.be.deep.equal([
initialPoolIds[1],
initialPoolIds[2],
initialPoolIds[0]
]);
});
it('can only be called by the ValidatorSet contract', async () => {
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.clearUnremovableValidator(initialPoolIds[0], {from: accounts[8]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.clearUnremovableValidator(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
});
it('non-removable validator pool id cannot be zero', async () => {
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.clearUnremovableValidator(0, {from: accounts[7]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.clearUnremovableValidator(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
});
});
describe('incrementStakingEpoch()', async () => {
it('should increment', async () => {
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(0));
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.incrementStakingEpoch({from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(1));
});
it('can only be called by ValidatorSet contract', async () => {
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.incrementStakingEpoch({from: accounts[8]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.incrementStakingEpoch({from: accounts[7]}).should.be.fulfilled;
});
});
describe('initialize()', async () => {
beforeEach(async () => {
await stakingAuRa.setCurrentBlockNumber(0);
});
it('should initialize successfully', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
new BN(120954).should.be.bignumber.equal(
await stakingAuRa.stakingEpochDuration.call()
);
new BN(4320).should.be.bignumber.equal(
await stakingAuRa.stakeWithdrawDisallowPeriod.call()
);
new BN(0).should.be.bignumber.equal(
await stakingAuRa.stakingEpochStartBlock.call()
);
validatorSetAuRa.address.should.be.equal(
await stakingAuRa.validatorSetContract.call()
);
'0x0000000000000000000000000000000000000000'.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
for (let i = 0; i < initialStakingAddresses.length; i++) {
new BN(i).should.be.bignumber.equal(
await stakingAuRa.poolIndex.call(initialPoolIds[i])
);
true.should.be.equal(
await stakingAuRa.isPoolActive.call(initialPoolIds[i])
);
new BN(i).should.be.bignumber.equal(
await stakingAuRa.poolToBeRemovedIndex.call(initialPoolIds[i])
);
}
(await stakingAuRa.getPools.call()).should.be.deep.equal(initialPoolIds);
new BN(web3.utils.toWei('1', 'ether')).should.be.bignumber.equal(
await stakingAuRa.delegatorMinStake.call()
);
new BN(web3.utils.toWei('1', 'ether')).should.be.bignumber.equal(
await stakingAuRa.candidateMinStake.call()
);
});
it('should fail if ValidatorSet contract address is zero', async () => {
await stakingAuRa.initialize(
'0x0000000000000000000000000000000000000000', // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if delegatorMinStake is zero', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('0', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if candidateMinStake is zero', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('0', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if already initialized', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if stakingEpochDuration is 0', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
0, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if stakeWithdrawDisallowPeriod is 0', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
0 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
it('should fail if stakeWithdrawDisallowPeriod >= stakingEpochDuration', async () => {
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
120954 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
});
it('should fail if some pool id is 0', async () => {
initialPoolIds[0] = 0;
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.rejectedWith(ERROR_MSG);
});
});
describe('moveStake()', async () => {
let delegatorAddress;
let erc677Token;
let mintAmount;
let stakeUnit;
beforeEach(async () => {
delegatorAddress = accounts[7];
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
// Deploy ERC677 contract
erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for delegator and candidates (imagine that they got some STAKE_UNITs from a bridge)
stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(initialStakingAddresses[0], mintAmount, {from: owner}).should.be.fulfilled;
await erc677Token.mint(initialStakingAddresses[1], mintAmount, {from: owner}).should.be.fulfilled;
await erc677Token.mint(delegatorAddress, mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[0]));
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[1]));
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(delegatorAddress));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(await erc677Token.stakingContract.call());
// Pass ERC677 contract address to Staking contract
'0x0000000000000000000000000000000000000000'.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
erc677Token.address.should.be.equal(await stakingAuRa.erc677TokenContract.call());
// Place stakes
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[0], mintAmount, {from: initialStakingAddresses[0]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[0], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
});
it('should move entire stake', async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[0], delegatorAddress)).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[0], delegatorAddress)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(mintAmount);
});
it('should move part of the stake', async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[0], delegatorAddress)).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], stakeUnit, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[0], delegatorAddress)).should.be.bignumber.equal(stakeUnit);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(stakeUnit);
});
it('should move part of the stake', async () => {
await erc677Token.mint(delegatorAddress, mintAmount, {from: owner}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
const sourcePool = initialStakingAddresses[0];
const sourcePoolId = initialPoolIds[0];
const targetPool = initialStakingAddresses[1];
const targetPoolId = initialPoolIds[1];
(await stakingAuRa.stakeAmount.call(sourcePoolId, delegatorAddress)).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmount.call(targetPoolId, delegatorAddress)).should.be.bignumber.equal(mintAmount);
const moveAmount = stakeUnit.div(new BN(2));
moveAmount.should.be.bignumber.below(await stakingAuRa.delegatorMinStake.call());
await stakingAuRa.moveStake(sourcePool, targetPool, moveAmount, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(sourcePoolId, delegatorAddress)).should.be.bignumber.equal(mintAmount.sub(moveAmount));
(await stakingAuRa.stakeAmount.call(targetPoolId, delegatorAddress)).should.be.bignumber.equal(mintAmount.add(moveAmount));
});
it('should fail for zero gas price', async () => {
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], mintAmount, {from: delegatorAddress, gasPrice: 0}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
});
it('should fail if the source and destination addresses are the same', async () => {
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[0], mintAmount, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
});
it('should fail if the staker tries to move more than they have', async () => {
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], mintAmount.mul(new BN(2)), {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.moveStake(initialStakingAddresses[0], initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
});
});
describe('stake(), transferAndCall() [tokens]', async () => {
let delegatorAddress;
let erc677Token;
let mintAmount;
let candidateMinStake;
let delegatorMinStake;
let useTransferAndCall = false;
beforeEach(async () => {
delegatorAddress = accounts[7];
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
candidateMinStake = await stakingAuRa.candidateMinStake.call();
delegatorMinStake = await stakingAuRa.delegatorMinStake.call();
// Deploy ERC677 contract
erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for delegator and candidates (imagine that they got some STAKE_UNITs from a bridge)
const stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(initialStakingAddresses[1], mintAmount, {from: owner}).should.be.fulfilled;
await erc677Token.mint(delegatorAddress, mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[1]));
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(delegatorAddress));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(await erc677Token.stakingContract.call());
// Pass ERC677 contract address to Staking contract
'0x0000000000000000000000000000000000000000'.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
erc677Token.address.should.be.equal(await stakingAuRa.erc677TokenContract.call());
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
});
for (let step = 0; step < 2; step++) {
it('should place a stake' + fnName(step), async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(mintAmount);
const result = await stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
const events = await stakingAuRa.getPastEvents('PlacedStake', {fromBlock: result.receipt.blockNumber, toBlock: result.receipt.blockNumber});
events[0].event.should.be.equal("PlacedStake");
events[0].args.toPoolStakingAddress.should.be.equal(initialStakingAddresses[1]);
events[0].args.staker.should.be.equal(delegatorAddress);
events[0].args.stakingEpoch.should.be.bignumber.equal(new BN(0));
events[0].args.amount.should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(mintAmount.mul(new BN(2)));
});
it('should fail for zero gas price' + fnName(step), async () => {
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1], gasPrice: 0}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if erc677TokenContract address is not defined' + fnName(step), async () => {
await stakingAuRa.setErc677TokenContractMock('0x0000000000000000000000000000000000000000').should.be.fulfilled;
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if erc677TokenContract address is defined but msg.value is not zero' + fnName(step), async () => {
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1], value: 1}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail for a non-existing pool' + fnName(step), async () => {
await stake(accounts[10], mintAmount, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stake('0x0000000000000000000000000000000000000000', mintAmount, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
});
it('should fail for a zero amount' + fnName(step), async () => {
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stake(initialStakingAddresses[1], new BN(0), {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
});
it('should fail for a banned validator' + fnName(step), async () => {
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await validatorSetAuRa.setRandomContract(accounts[8]).should.be.fulfilled;
await validatorSetAuRa.removeMaliciousValidators([initialValidators[1]], {from: accounts[8]}).should.be.fulfilled;
await stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
});
it('should only success in the allowed staking window' + fnName(step), async () => {
await stakingAuRa.setCurrentBlockNumber(117000).should.be.fulfilled;
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if a candidate stakes less than CANDIDATE_MIN_STAKE' + fnName(step), async () => {
const halfOfCandidateMinStake = candidateMinStake.div(new BN(2));
await stake(initialStakingAddresses[1], halfOfCandidateMinStake, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if a delegator stakes less than DELEGATOR_MIN_STAKE' + fnName(step), async () => {
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
const halfOfDelegatorMinStake = delegatorMinStake.div(new BN(2));
await stake(initialStakingAddresses[1], halfOfDelegatorMinStake, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
});
it('should fail if a delegator stakes into an empty pool' + fnName(step), async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(new BN(0));
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
});
it('should increase a stake amount' + fnName(step), async () => {
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake);
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake.mul(new BN(2)));
});
it('should increase the stakeAmountByCurrentEpoch' + fnName(step), async () => {
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake);
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake.mul(new BN(2)));
});
it('should increase a total stake amount' + fnName(step), async () => {
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake);
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake.mul(new BN(2))));
});
it('should add a delegator to the pool' + fnName(step), async () => {
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.poolDelegators.call(initialPoolIds[1])).length.should.be.equal(0);
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.poolDelegators.call(initialPoolIds[1])).should.be.deep.equal([delegatorAddress]);
});
it('should update pool\'s likelihood' + fnName(step), async () => {
let likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods.length.should.be.equal(0);
likelihoodInfo.sum.should.be.bignumber.equal(new BN(0));
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(candidateMinStake);
likelihoodInfo.sum.should.be.bignumber.equal(candidateMinStake);
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
likelihoodInfo.sum.should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
await stake(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake.mul(new BN(2))));
likelihoodInfo.sum.should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake.mul(new BN(2))));
});
it('should fail if the staker stakes more than they have' + fnName(step), async () => {
await stake(initialStakingAddresses[1], mintAmount.mul(new BN(2)), {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should decrease the balance of the staker and increase the balance of the Staking contract' + fnName(step), async () => {
(await erc677Token.balanceOf.call(stakingAuRa.address)).should.be.bignumber.equal(new BN(0));
await stake(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await erc677Token.balanceOf.call(initialStakingAddresses[1])).should.be.bignumber.equal(mintAmount.sub(candidateMinStake));
(await erc677Token.balanceOf.call(stakingAuRa.address)).should.be.bignumber.equal(candidateMinStake);
});
it('switch useTransferAndCall variable', async () => {
useTransferAndCall = !useTransferAndCall;
});
}
function fnName(step) {
return step == 0 ? ' [stake]' : ' [transferAndCall]';
}
function stake(stakingAddress, amount, options) {
if (useTransferAndCall) {
return erc677Token.transferAndCall(stakingAuRa.address, amount, stakingAddress, options);
}
return stakingAuRa.stake(stakingAddress, amount, options);
}
});
describe('stake() [native coins]', async () => {
let delegatorAddress;
let candidateMinStake;
let delegatorMinStake;
beforeEach(async () => {
delegatorAddress = accounts[7];
// Deploy StakingAuRa contract
stakingAuRa = await StakingAuRaCoins.new();
stakingAuRa = await AdminUpgradeabilityProxy.new(stakingAuRa.address, owner);
stakingAuRa = await StakingAuRaCoins.at(stakingAuRa.address);
await validatorSetAuRa.setStakingContract(stakingAuRa.address).should.be.fulfilled;
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
candidateMinStake = await stakingAuRa.candidateMinStake.call();
delegatorMinStake = await stakingAuRa.delegatorMinStake.call();
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
});
it('should place a stake', async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(candidateMinStake);
const result = await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
result.logs[0].event.should.be.equal("PlacedStake");
result.logs[0].args.toPoolStakingAddress.should.be.equal(initialStakingAddresses[1]);
result.logs[0].args.staker.should.be.equal(delegatorAddress);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(0));
result.logs[0].args.amount.should.be.bignumber.equal(delegatorMinStake);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake);
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
});
it('should fail for zero gas price', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake, gasPrice: 0}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
});
it('should fail for a non-existing pool', async () => {
await stakingAuRa.stake(accounts[10], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.stake('0x0000000000000000000000000000000000000000', 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.rejectedWith(ERROR_MSG);
});
it('should fail for a zero amount', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: 0}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
});
it('should fail for a banned validator', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
await validatorSetAuRa.setRandomContract(accounts[8]).should.be.fulfilled;
await validatorSetAuRa.removeMaliciousValidators([initialValidators[1]], {from: accounts[8]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.rejectedWith(ERROR_MSG);
});
it('should only success in the allowed staking window', async () => {
await stakingAuRa.setCurrentBlockNumber(117000).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
});
it('should fail if a candidate stakes less than CANDIDATE_MIN_STAKE', async () => {
const halfOfCandidateMinStake = candidateMinStake.div(new BN(2));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: halfOfCandidateMinStake}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
});
it('should fail if a delegator stakes less than DELEGATOR_MIN_STAKE', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
const halfOfDelegatorMinStake = delegatorMinStake.div(new BN(2));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: halfOfDelegatorMinStake}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
});
it('should fail if a delegator stakes into an empty pool', async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
});
it('should increase a stake amount', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake.mul(new BN(2)));
});
it('should increase the stakeAmountByCurrentEpoch', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(delegatorMinStake.mul(new BN(2)));
});
it('should increase a total stake amount', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake.mul(new BN(2))));
});
it('should add a delegator to the pool', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
(await stakingAuRa.poolDelegators.call(initialPoolIds[1])).length.should.be.equal(0);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
(await stakingAuRa.poolDelegators.call(initialPoolIds[1])).should.be.deep.equal([delegatorAddress]);
});
it('should update pool\'s likelihood', async () => {
let likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods.length.should.be.equal(0);
likelihoodInfo.sum.should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(candidateMinStake);
likelihoodInfo.sum.should.be.bignumber.equal(candidateMinStake);
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
likelihoodInfo.sum.should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: delegatorAddress, value: delegatorMinStake}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake.mul(new BN(2))));
likelihoodInfo.sum.should.be.bignumber.equal(candidateMinStake.add(delegatorMinStake.mul(new BN(2))));
});
it('should decrease the balance of the staker and increase the balance of the Staking contract', async () => {
(await web3.eth.getBalance(stakingAuRa.address)).should.be.equal('0');
const initialBalance = new BN(await web3.eth.getBalance(initialStakingAddresses[1]));
await stakingAuRa.stake(initialStakingAddresses[1], 0, {from: initialStakingAddresses[1], value: candidateMinStake}).should.be.fulfilled;
(new BN(await web3.eth.getBalance(initialStakingAddresses[1]))).should.be.bignumber.below(initialBalance.sub(candidateMinStake));
(new BN(await web3.eth.getBalance(stakingAuRa.address))).should.be.bignumber.equal(candidateMinStake);
});
});
describe('removePool()', async () => {
beforeEach(async () => {
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
});
it('should remove a pool', async () => {
(await stakingAuRa.getPools.call()).should.be.deep.equal(initialPoolIds);
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.removePool(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPools.call()).should.be.deep.equal([
initialPoolIds[2],
initialPoolIds[1]
]);
(await stakingAuRa.getPoolsInactive.call()).length.should.be.equal(0);
});
it('can only be called by the ValidatorSetAuRa contract', async () => {
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.removePool(initialPoolIds[0], {from: accounts[8]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.removePool(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
});
it('shouldn\'t remove a nonexistent pool', async () => {
(await stakingAuRa.getPools.call()).should.be.deep.equal(initialPoolIds);
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.removePool(10, {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPools.call()).should.be.deep.equal(initialPoolIds);
});
it('should reset pool index', async () => {
(await stakingAuRa.poolIndex.call(initialPoolIds[1])).should.be.bignumber.equal(new BN(1));
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.removePool(initialPoolIds[1], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.poolIndex.call(initialPoolIds[1])).should.be.bignumber.equal(new BN(0));
});
it('should add/remove a pool to/from the utility lists', async () => {
// Deploy ERC677 contract
const erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for candidate (imagine that the candidate got 2 STAKE_UNITs from a bridge)
const stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
const mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(initialStakingAddresses[0], mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[0]));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(await erc677Token.stakingContract.call());
// Pass ERC677 contract address to Staking contract
'0x0000000000000000000000000000000000000000'.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
erc677Token.address.should.be.equal(await stakingAuRa.erc677TokenContract.call());
// The first validator places stake for themselves
(await stakingAuRa.getPoolsToBeElected.call()).length.should.be.deep.equal(0);
(await stakingAuRa.getPoolsToBeRemoved.call()).should.be.deep.equal(initialPoolIds);
await stakingAuRa.stake(initialStakingAddresses[0], stakeUnit.mul(new BN(1)), {from: initialStakingAddresses[0]}).should.be.fulfilled;
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[0])).should.be.bignumber.equal(stakeUnit);
(await stakingAuRa.getPoolsToBeElected.call()).should.be.deep.equal([initialPoolIds[0]]);
(await stakingAuRa.getPoolsToBeRemoved.call()).should.be.deep.equal([
initialPoolIds[2],
initialPoolIds[1]
]);
// Remove the pool
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
(await stakingAuRa.poolInactiveIndex.call(initialPoolIds[0])).should.be.bignumber.equal(new BN(0));
await stakingAuRa.removePool(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
await stakingAuRa.removePool(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPoolsInactive.call()).should.be.deep.equal([initialPoolIds[0]]);
(await stakingAuRa.poolInactiveIndex.call(initialPoolIds[0])).should.be.bignumber.equal(new BN(0));
await stakingAuRa.setStakeAmountTotal(initialPoolIds[0], 0);
await stakingAuRa.removePool(initialPoolIds[0], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPoolsInactive.call()).length.should.be.equal(0);
(await stakingAuRa.getPoolsToBeElected.call()).length.should.be.deep.equal(0);
(await stakingAuRa.poolToBeRemovedIndex.call(initialPoolIds[1])).should.be.bignumber.equal(new BN(1));
await stakingAuRa.removePool(initialPoolIds[1], {from: accounts[7]}).should.be.fulfilled;
(await stakingAuRa.getPoolsToBeRemoved.call()).should.be.deep.equal([initialPoolIds[2]]);
(await stakingAuRa.poolToBeRemovedIndex.call(initialPoolIds[1])).should.be.bignumber.equal(new BN(0));
});
});
describe('removeMyPool()', async () => {
beforeEach(async () => {
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
});
it('should fail for zero gas price', async () => {
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.incrementStakingEpoch({from: accounts[7]}).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0], gasPrice: 0}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0]}).should.be.fulfilled;
});
it('should fail if Staking contract is not initialized', async () => {
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.incrementStakingEpoch({from: accounts[7]}).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress('0x0000000000000000000000000000000000000000').should.be.fulfilled;
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0]}).should.be.fulfilled;
});
it('should fail for initial validator during the initial staking epoch', async () => {
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(0));
(await validatorSetAuRa.isValidator.call(initialValidators[0])).should.be.equal(true);
(await validatorSetAuRa.miningByStakingAddress.call(initialStakingAddresses[0])).should.be.equal(initialValidators[0]);
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.incrementStakingEpoch({from: accounts[7]}).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0]}).should.be.fulfilled
});
it('should fail for a non-removable validator', async () => {
// Deploy Staking contract
stakingAuRa = await StakingAuRaTokens.new();
stakingAuRa = await AdminUpgradeabilityProxy.new(stakingAuRa.address, owner);
stakingAuRa = await StakingAuRaTokens.at(stakingAuRa.address);
// Deploy ValidatorSet contract
validatorSetAuRa = await ValidatorSetAuRa.new();
validatorSetAuRa = await AdminUpgradeabilityProxy.new(validatorSetAuRa.address, owner);
validatorSetAuRa = await ValidatorSetAuRa.at(validatorSetAuRa.address);
// Initialize ValidatorSet
await validatorSetAuRa.initialize(
blockRewardAuRa.address, // _blockRewardContract
'0x0000000000000000000000000000000000000000', // _governanceContract
'0x3000000000000000000000000000000000000001', // _randomContract
stakingAuRa.address, // _stakingContract
initialValidators, // _initialMiningAddresses
initialStakingAddresses, // _initialStakingAddresses
true // _firstValidatorIsUnremovable
).should.be.fulfilled;
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
(await stakingAuRa.getPools.call()).should.be.deep.equal(initialPoolIds);
await stakingAuRa.setValidatorSetAddress(accounts[7]).should.be.fulfilled;
await stakingAuRa.incrementStakingEpoch({from: accounts[7]}).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await stakingAuRa.removeMyPool({from: initialStakingAddresses[0]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.removeMyPool({from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.getPools.call()).should.be.deep.equal([
initialPoolIds[0],
initialPoolIds[2]
]);
});
});
describe('withdraw()', async () => {
let delegatorAddress;
let erc677Token;
let mintAmount;
let candidateMinStake;
let delegatorMinStake;
beforeEach(async () => {
delegatorAddress = accounts[7];
// Initialize StakingAuRa
await stakingAuRa.initialize(
validatorSetAuRa.address, // _validatorSetContract
'0x0000000000000000000000000000000000000000', // _governanceContract
initialPoolIds, // _initialIds
web3.utils.toWei('1', 'ether'), // _delegatorMinStake
web3.utils.toWei('1', 'ether'), // _candidateMinStake
120954, // _stakingEpochDuration
0, // _stakingEpochStartBlock
4320 // _stakeWithdrawDisallowPeriod
).should.be.fulfilled;
candidateMinStake = await stakingAuRa.candidateMinStake.call();
delegatorMinStake = await stakingAuRa.delegatorMinStake.call();
// Deploy ERC677 contract
erc677Token = await ERC677BridgeTokenRewardable.new("STAKE", "STAKE", 18, 100, {from: owner});
// Mint some balance for delegator and candidates (imagine that they got some STAKE_UNITs from a bridge)
const stakeUnit = new BN(web3.utils.toWei('1', 'ether'));
mintAmount = stakeUnit.mul(new BN(2));
await erc677Token.mint(initialStakingAddresses[0], mintAmount, {from: owner}).should.be.fulfilled;
await erc677Token.mint(initialStakingAddresses[1], mintAmount, {from: owner}).should.be.fulfilled;
await erc677Token.mint(initialStakingAddresses[2], mintAmount, {from: owner}).should.be.fulfilled;
await erc677Token.mint(delegatorAddress, mintAmount, {from: owner}).should.be.fulfilled;
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(initialStakingAddresses[1]));
mintAmount.should.be.bignumber.equal(await erc677Token.balanceOf.call(delegatorAddress));
// Pass Staking contract address to ERC677 contract
await erc677Token.setStakingContract(stakingAuRa.address, {from: owner}).should.be.fulfilled;
stakingAuRa.address.should.be.equal(await erc677Token.stakingContract.call());
// Pass ERC677 contract address to Staking contract
'0x0000000000000000000000000000000000000000'.should.be.equal(
await stakingAuRa.erc677TokenContract.call()
);
await stakingAuRa.setErc677TokenContract(erc677Token.address, {from: owner}).should.be.fulfilled;
erc677Token.address.should.be.equal(await stakingAuRa.erc677TokenContract.call());
await stakingAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
});
it('should withdraw a stake', async () => {
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(mintAmount);
(await erc677Token.balanceOf.call(initialStakingAddresses[1])).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(mintAmount.mul(new BN(2)));
(await erc677Token.balanceOf.call(delegatorAddress)).should.be.bignumber.equal(new BN(0));
const result = await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
result.logs[0].event.should.be.equal("WithdrewStake");
result.logs[0].args.fromPoolStakingAddress.should.be.equal(initialStakingAddresses[1]);
result.logs[0].args.staker.should.be.equal(delegatorAddress);
result.logs[0].args.stakingEpoch.should.be.bignumber.equal(new BN(0));
result.logs[0].args.amount.should.be.bignumber.equal(mintAmount);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmountTotal.call(initialPoolIds[1])).should.be.bignumber.equal(mintAmount);
(await erc677Token.balanceOf.call(delegatorAddress)).should.be.bignumber.equal(mintAmount);
});
it('should fail for zero gas price', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1], gasPrice: 0}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if not initialized', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.setValidatorSetAddress('0x0000000000000000000000000000000000000000').should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setValidatorSetAddress(validatorSetAuRa.address).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail for a zero pool address', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw('0x0000000000000000000000000000000000000000', mintAmount, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail for a zero amount', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], new BN(0), {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('shouldn\'t allow withdrawing from a banned pool', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
await validatorSetAuRa.setBannedUntil(initialStakingAddresses[1], 100).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await validatorSetAuRa.setBannedUntil(initialStakingAddresses[1], 0).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
});
it('shouldn\'t allow withdrawing during the stakeWithdrawDisallowPeriod', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(117000).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(117000).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setCurrentBlockNumber(116000).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(116000).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if non-zero residue is less than CANDIDATE_MIN_STAKE', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount.sub(candidateMinStake).add(new BN(1)), {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount.sub(candidateMinStake), {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], candidateMinStake, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('should fail if non-zero residue is less than DELEGATOR_MIN_STAKE', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount.sub(delegatorMinStake).add(new BN(1)), {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount.sub(delegatorMinStake), {from: delegatorAddress}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], delegatorMinStake, {from: delegatorAddress}).should.be.fulfilled;
});
it('should fail if withdraw more than staked', async () => {
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount.add(new BN(1)), {from: initialStakingAddresses[1]}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
});
it('initial validator cannot withdraw initial stake', async () => {
(await stakingAuRa.candidateMinStake.call()).should.be.bignumber.equal(mintAmount.div(new BN(2)));
const zero = new BN(0);
const one = new BN(1);
const initialStake = mintAmount.sub(one);
const stakingAddress = initialStakingAddresses[1];
const poolId = initialPoolIds[1];
await stakingAuRa.stake(stakingAddress, initialStake, { from: stakingAddress }).should.be.fulfilled;
await stakingAuRa.setInitialStake(poolId, initialStake).should.be.fulfilled;
await stakingAuRa.stake(stakingAddress, one, { from: stakingAddress }).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(poolId, '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(mintAmount);
await stakingAuRa.withdraw(stakingAddress, one, { from: stakingAddress }).should.be.fulfilled;
(await stakingAuRa.stakeAmount.call(poolId, '0x0000000000000000000000000000000000000000')).should.be.bignumber.equal(initialStake);
await stakingAuRa.withdraw(stakingAddress, one, { from: stakingAddress }).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(stakingAddress, initialStake, { from: stakingAddress }).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.setInitialStake(poolId, zero).should.be.fulfilled;
await stakingAuRa.withdraw(stakingAddress, initialStake, { from: stakingAddress }).should.be.fulfilled;
});
it('should fail if withdraw already ordered amount', async () => {
// Set `initiateChangeAllowed` boolean flag to `true`
await validatorSetAuRa.setCurrentBlockNumber(1).should.be.fulfilled;
await validatorSetAuRa.setSystemAddress(owner).should.be.fulfilled;
await validatorSetAuRa.finalizeChange({from: owner}).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(100).should.be.fulfilled;
// Place a stake during the initial staking epoch
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[0], mintAmount, {from: initialStakingAddresses[0]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[2], mintAmount, {from: initialStakingAddresses[2]}).should.be.fulfilled;
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.fulfilled;
// Change staking epoch
await stakingAuRa.setCurrentBlockNumber(120954).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(120954).should.be.fulfilled;
await validatorSetAuRa.setBlockRewardContract(accounts[7]).should.be.fulfilled;
await validatorSetAuRa.newValidatorSet({from: accounts[7]}).should.be.fulfilled;
await validatorSetAuRa.setBlockRewardContract(blockRewardAuRa.address).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(120970).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(120970).should.be.fulfilled;
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(1));
// Finalize a new validator set
await blockRewardAuRa.initialize(validatorSetAuRa.address, '0x0000000000000000000000000000000000000000').should.be.fulfilled;
await validatorSetAuRa.emitInitiateChange().should.be.fulfilled;
await validatorSetAuRa.finalizeChange({from: owner}).should.be.fulfilled;
// Order withdrawal
const orderedAmount = mintAmount.div(new BN(4));
await stakingAuRa.orderWithdraw(initialStakingAddresses[1], orderedAmount, {from: delegatorAddress}).should.be.fulfilled;
// The second validator removes their pool
(await validatorSetAuRa.isValidator.call(initialValidators[1])).should.be.equal(true);
(await stakingAuRa.getPoolsInactive.call()).length.should.be.equal(0);
await stakingAuRa.removeMyPool({from: initialStakingAddresses[1]}).should.be.fulfilled;
(await stakingAuRa.getPoolsInactive.call()).should.be.deep.equal([initialPoolIds[1]]);
// Change staking epoch and enqueue pending validators
await stakingAuRa.setCurrentBlockNumber(120954*2).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(120954*2).should.be.fulfilled;
await validatorSetAuRa.setBlockRewardContract(accounts[7]).should.be.fulfilled;
await validatorSetAuRa.newValidatorSet({from: accounts[7]}).should.be.fulfilled;
await validatorSetAuRa.setBlockRewardContract(blockRewardAuRa.address).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(120970*2).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(120970*2).should.be.fulfilled;
(await stakingAuRa.stakingEpoch.call()).should.be.bignumber.equal(new BN(2));
// Finalize a new validator set
await validatorSetAuRa.emitInitiateChange().should.be.fulfilled;
await validatorSetAuRa.finalizeChange({from: owner}).should.be.fulfilled;
(await validatorSetAuRa.isValidator.call(initialValidators[1])).should.be.equal(false);
// Check withdrawal for a delegator
const restOfAmount = mintAmount.mul(new BN(3)).div(new BN(4));
(await stakingAuRa.poolDelegators.call(initialPoolIds[1])).should.be.deep.equal([delegatorAddress]);
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(restOfAmount);
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount, {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], restOfAmount.add(new BN(1)), {from: delegatorAddress}).should.be.rejectedWith(ERROR_MSG);
await stakingAuRa.withdraw(initialStakingAddresses[1], restOfAmount, {from: delegatorAddress}).should.be.fulfilled;
(await stakingAuRa.stakeAmountByCurrentEpoch.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.stakeAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(new BN(0));
(await stakingAuRa.orderedWithdrawAmount.call(initialPoolIds[1], delegatorAddress)).should.be.bignumber.equal(orderedAmount);
(await stakingAuRa.poolDelegators.call(initialPoolIds[1])).length.should.be.equal(0);
(await stakingAuRa.poolDelegatorsInactive.call(initialPoolIds[1])).should.be.deep.equal([delegatorAddress]);
});
it('should decrease likelihood', async () => {
let likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.sum.should.be.bignumber.equal(new BN(0));
await stakingAuRa.stake(initialStakingAddresses[1], mintAmount, {from: initialStakingAddresses[1]}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(mintAmount);
likelihoodInfo.sum.should.be.bignumber.equal(mintAmount);
await stakingAuRa.withdraw(initialStakingAddresses[1], mintAmount.div(new BN(2)), {from: initialStakingAddresses[1]}).should.be.fulfilled;
likelihoodInfo = await stakingAuRa.getPoolsLikelihood.call();
likelihoodInfo.likelihoods[0].should.be.bignumber.equal(mintAmount.div(new BN(2)));
likelihoodInfo.sum.should.be.bignumber.equal(mintAmount.div(new BN(2)));
});
// TODO: add unit tests for native coin withdrawal
});
// TODO: ...add other tests...
async function accrueBridgeFees() {
const fee = web3.utils.toWei('1');
await blockRewardAuRa.setNativeToErcBridgesAllowed([owner], {from: owner}).should.be.fulfilled;
await blockRewardAuRa.setErcToNativeBridgesAllowed([owner], {from: owner}).should.be.fulfilled;
await blockRewardAuRa.addBridgeTokenRewardReceivers(fee, {from: owner}).should.be.fulfilled;
await blockRewardAuRa.addBridgeNativeRewardReceivers(fee, {from: owner}).should.be.fulfilled;
(await blockRewardAuRa.bridgeTokenReward.call()).should.be.bignumber.equal(fee);
(await blockRewardAuRa.bridgeNativeReward.call()).should.be.bignumber.equal(fee);
return new BN(fee);
}
async function callFinalizeChange() {
await validatorSetAuRa.setSystemAddress(owner).should.be.fulfilled;
await validatorSetAuRa.finalizeChange({from: owner}).should.be.fulfilled;
await validatorSetAuRa.setSystemAddress('0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE').should.be.fulfilled;
}
async function callReward() {
const validators = await validatorSetAuRa.getValidators.call();
await blockRewardAuRa.setSystemAddress(owner).should.be.fulfilled;
const {logs} = await blockRewardAuRa.reward([validators[0]], [0], {from: owner}).should.be.fulfilled;
// Emulate minting native coins
logs[0].event.should.be.equal("MintedNative");
const receivers = logs[0].args.receivers;
const rewards = logs[0].args.rewards;
for (let i = 0; i < receivers.length; i++) {
await blockRewardAuRa.sendCoins({from: owner, value: rewards[i]}).should.be.fulfilled;
}
await blockRewardAuRa.setSystemAddress('0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE').should.be.fulfilled;
}
async function setCurrentBlockNumber(blockNumber) {
await blockRewardAuRa.setCurrentBlockNumber(blockNumber).should.be.fulfilled;
await randomAuRa.setCurrentBlockNumber(blockNumber).should.be.fulfilled;
await stakingAuRa.setCurrentBlockNumber(blockNumber).should.be.fulfilled;
await validatorSetAuRa.setCurrentBlockNumber(blockNumber).should.be.fulfilled;
}
Array.prototype.bignumbersEqual = function(arr) {
let arr1 = [...this];
arr1 = arr1.map(item => (new BN(item)).toString())
let arr2 = [...arr];
arr2 = arr2.map(item => (new BN(item)).toString());
arr1.should.be.deep.equal(arr2);
}
});
function random(low, high) {
return Math.floor(Math.random() * (high - low) + low);
}
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
|
Object.assign(pc, function () {
var poolVec3 = [];
var poolQuat = [];
/**
* @class
* @name pc.XrHitTestSource
* @augments pc.EventHandler
* @classdesc Represents XR hit test source, which provides access to hit results of real world geometry from AR session.
* @description Represents XR hit test source, which provides access to hit results of real world geometry from AR session.
* @param {pc.XrManager} manager - WebXR Manager.
* @param {object} xrHitTestSource - XRHitTestSource object that is created by WebXR API.
* @param {boolean} transient - True if XRHitTestSource created for input source profile.
* @example
* hitTestSource.on('result', function (position, rotation) {
* target.setPosition(position);
* });
*/
var XrHitTestSource = function (manager, xrHitTestSource, transient) {
pc.EventHandler.call(this);
this.manager = manager;
this._xrHitTestSource = xrHitTestSource;
this._transient = transient;
};
XrHitTestSource.prototype = Object.create(pc.EventHandler.prototype);
XrHitTestSource.prototype.constructor = XrHitTestSource;
/**
* @event
* @name pc.XrHitTestSource#remove
* @description Fired when {pc.XrHitTestSource} is removed.
* @example
* hitTestSource.once('remove', function () {
* // hit test source has been removed
* });
*/
/**
* @event
* @name pc.XrHitTestSource#result
* @description Fired when hit test source receives new results. It provides transform information that tries to match real world picked geometry.
* @param {pc.Vec3} position - Position of hit test
* @param {pc.Quat} rotation - Rotation of hit test
* @param {pc.XrInputSource|null} inputSource - If is transient hit test source, then it will provide related input source
* @example
* hitTestSource.on('result', function (position, rotation, inputSource) {
* target.setPosition(position);
* target.setRotation(rotation);
* });
*/
/**
* @function
* @name pc.XrHitTestSource#remove
* @description Stop and remove hit test source.
*/
XrHitTestSource.prototype.remove = function () {
if (! this._xrHitTestSource)
return;
var sources = this.manager.hitTest.sources;
var ind = sources.indexOf(this);
if (ind !== -1) sources.splice(ind, 1);
this.onStop();
};
XrHitTestSource.prototype.onStop = function () {
this._xrHitTestSource.cancel();
this._xrHitTestSource = null;
this.fire('remove');
this.manager.hitTest.fire('remove', this);
};
XrHitTestSource.prototype.update = function (frame) {
if (this._transient) {
var transientResults = frame.getHitTestResultsForTransientInput(this._xrHitTestSource);
for (var i = 0; i < transientResults.length; i++) {
var transientResult = transientResults[i];
var inputSource;
if (transientResult.inputSource)
inputSource = this.manager.input._getByInputSource(transientResult.inputSource);
this.updateHitResults(transientResult.results, inputSource);
}
} else {
this.updateHitResults(frame.getHitTestResults(this._xrHitTestSource));
}
};
XrHitTestSource.prototype.updateHitResults = function (results, inputSource) {
for (var i = 0; i < results.length; i++) {
var pose = results[i].getPose(this.manager._referenceSpace);
var position = poolVec3.pop();
if (! position) position = new pc.Vec3();
position.copy(pose.transform.position);
var rotation = poolQuat.pop();
if (! rotation) rotation = new pc.Quat();
rotation.copy(pose.transform.orientation);
this.fire('result', position, rotation, inputSource);
this.manager.hitTest.fire('result', this, position, rotation, inputSource);
poolVec3.push(position);
poolQuat.push(rotation);
}
};
return { XrHitTestSource: XrHitTestSource };
}());
|
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import User from './User';
const URL = 'https://dummyapi.io/data/api/user';
const APP_ID = '607f65448ce9f17db07f0f33';
const Users = () => {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(0);
const [total, setTotal] = useState(0);
const [usersPerPage] = useState(10);
useEffect(() => {
const fetchUsers = async () => {
setLoading(true);
const FULL_URL = `${URL}?limit=${usersPerPage}&page=${currentPage}`;
const res = await axios.get(FULL_URL, {
headers: { 'app-id': APP_ID },
});
setUsers(res.data.data);
setTotal(res.data.total);
setLoading(false);
};
fetchUsers();
}, [currentPage]);
return (
<div>
<table className='content-table'>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<User users={users} loading={loading} />
</tbody>
</table>
<section className='pagination'>
<button className='btn btn-lg' onClick={() => setCurrentPage(0)}>
First
</button>
<button
className='btn btn-lg'
onClick={() => setCurrentPage((currentPage) => currentPage - 1)}
disabled={currentPage === 0}
>
Previous
</button>
<button
className='btn btn-lg'
onClick={() => setCurrentPage((currentPage) => currentPage + 1)}
disabled={
usersPerPage > users.length ||
(currentPage + 1) * usersPerPage >= total
}
>
Next
</button>
<button
className='btn btn-lg'
onClick={() => setCurrentPage(Math.floor(total / usersPerPage - 1))}
disabled={usersPerPage > users.length}
>
Last
</button>
</section>
</div>
);
};
export default Users;
|
export default function animalReducer(state = 'dog', action){
if(action.type === 'SET_ANIMAL'){
return action.payload
} else {
return state
}
}
|
const command = require('./time');
const { generateMentions } = require('./mockData');
describe('!time', () => {
describe('regex', () => {
it.each([
['!time'],
[' !time'],
['!time @odin-bot'],
['@odin-bot !time'],
])('correct strings trigger the callback', (string) => {
expect(command.regex.test(string)).toBeTruthy();
});
it.each([
['!tim'],
['tie'],
['!ti'],
['!times'],
['```function("!time", () => {}```'],
['!timea'],
[''],
[' '],
[' !'],
['@odin-bot ! time'],
['!tim&e'],
['!tim^e'],
['!time!'],
['@odin-bot! time'],
['https:!!time.com'],
])("'%s' does not trigger the callback", (string) => {
expect(command.regex.test(string)).toBeFalsy();
});
it.each([
['Check this out! !time'],
['Don\'t worry about !time'],
['Hey @odin-bot, !time'],
['!@odin-bot ^ !me !time !tests$*'],
])("'%s' - command can be anywhere in the string", (string) => {
expect(command.regex.test(string)).toBeTruthy();
});
it.each([
['@user!time'],
['it\'s about!time'],
['!timeisanillusion'],
['!time!'],
['!time*'],
['!time...'],
])("'%s' - command should be its own word!group - no leading or trailing characters", (string) => {
expect(command.regex.test(string)).toBeFalsy();
});
});
describe('callback', () => {
it('returns correct output', async () => {
expect(await command.cb(generateMentions(0))).toMatchSnapshot();
expect(await command.cb(generateMentions(1))).toMatchSnapshot();
expect(await command.cb(generateMentions(2))).toMatchSnapshot();
expect(await command.cb(generateMentions(3))).toMatchSnapshot();
});
});
});
|
'use strict';
angular.module('applicationApp')
.controller('AdminCtrl', function ($scope, $http, Auth, User) {
// Use the User $resource to fetch all users
$scope.users = User.query();
$scope.delete = function(user) {
User.remove({ id: user._id });
angular.forEach($scope.users, function(u, i) {
if (u === user) {
$scope.users.splice(i, 1);
}
});
};
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter } from 'react-router-dom';
import CssBaseline from '@material-ui/core/CssBaseline';
import { ThemeProvider } from '@material-ui/core/styles';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import theme from './theme';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
} from "@apollo/client";
const publicUrl = process.env.PUBLIC_URL;
const client = new ApolloClient({
uri: `${publicUrl || 'http://127.0.0.1:3030'}/graphql`,
cache: new InMemoryCache()
});
ReactDOM.render(
<React.StrictMode>
<HashRouter>
<ApolloProvider client={client}>
<ThemeProvider theme={theme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<App />
</ThemeProvider>
</ApolloProvider>
</HashRouter>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
//
// TwilioVideo.js
// Black
//
// Created by Martín Fernández on 6/13/17.
//
//
import { Component } from 'react'
import PropTypes from 'prop-types'
import {
NativeModules,
NativeEventEmitter,
View
} from 'react-native'
const { TWVideoModule } = NativeModules
export default class extends Component {
static propTypes = {
/**
* Flag that enables screen sharing RCTRootView instead of camera capture
*/
screenShare: PropTypes.bool,
/**
* Called when the room has connected
*
* @param {{roomName, participants}}
*/
onRoomDidConnect: PropTypes.func,
/**
* Called when the room has disconnected
*
* @param {{roomName, error}}
*/
onRoomDidDisconnect: PropTypes.func,
/**
* Called when connection with room failed
*
* @param {{roomName, error}}
*/
onRoomDidFailToConnect: PropTypes.func,
/**
* Called when a new participant has connected
*
* @param {{roomName, participant}}
*/
onRoomParticipantDidConnect: PropTypes.func,
/**
* Called when a participant has disconnected
*
* @param {{roomName, participant}}
*/
onRoomParticipantDidDisconnect: PropTypes.func,
/**
* Called when a new video track has been added
*
* @param {{participant, track, enabled}}
*/
onParticipantAddedVideoTrack: PropTypes.func,
/**
* Called when a video track has been removed
*
* @param {{participant, track}}
*/
onParticipantRemovedVideoTrack: PropTypes.func,
/**
* Called when a new audio track has been added
*
* @param {{participant, track}}
*/
onParticipantAddedAudioTrack: PropTypes.func,
/**
* Called when a audio track has been removed
*
* @param {{participant, track}}
*/
onParticipantRemovedAudioTrack: PropTypes.func,
/**
* Called when a video track has been enabled.
*
* @param {{participant, track}}
*/
onParticipantEnabledVideoTrack: PropTypes.func,
/**
* Called when a video track has been disabled.
*
* @param {{participant, track}}
*/
onParticipantDisabledVideoTrack: PropTypes.func,
/**
* Called when an audio track has been enabled.
*
* @param {{participant, track}}
*/
onParticipantEnabledAudioTrack: PropTypes.func,
/**
* Called when an audio track has been disabled.
*
* @param {{participant, track}}
*/
onParticipantDisabledAudioTrack: PropTypes.func,
/**
* Called when the camera has started
*
*/
onCameraDidStart: PropTypes.func,
/**
* Called when the camera has been interrupted
*
*/
onCameraWasInterrupted: PropTypes.func,
/**
* Called when the camera has stopped runing with an error
*
* @param {{error}} The error message description
*/
onCameraDidStopRunning: PropTypes.func,
/**
* Called when stats are received (after calling getStats)
*
*/
onStatsReceived: PropTypes.func,
...View.propTypes
}
constructor (props) {
super(props)
this._subscriptions = []
this._eventEmitter = new NativeEventEmitter(TWVideoModule)
this.setLocalVideoEnabled = this.setLocalVideoEnabled.bind(this)
this.setLocalAudioEnabled = this.setLocalAudioEnabled.bind(this)
this.flipCamera = this.flipCamera.bind(this)
this.toggleSoundSetup = this.toggleSoundSetup.bind(this)
this.connect = this.connect.bind(this)
this.disconnect = this.disconnect.bind(this)
this.setRemoteAudioPlayback = this.setRemoteAudioPlayback.bind(this)
}
componentWillMount () {
this._registerEvents()
this._startLocalVideo()
this._startLocalAudio()
}
componentWillUnmount () {
this._unregisterEvents()
this._stopLocalVideo()
this._stopLocalAudio()
}
/**
* Locally mute/ unmute all remote audio tracks from a given participant
*/
setRemoteAudioPlayback ({participantSid, enabled}) {
TWVideoModule.setRemoteAudioPlayback(participantSid, enabled)
}
/**
* Enable or disable local video
*/
setLocalVideoEnabled (enabled) {
return TWVideoModule.setLocalVideoEnabled(enabled)
}
/**
* Enable or disable local audio
*/
setLocalAudioEnabled (enabled) {
return TWVideoModule.setLocalAudioEnabled(enabled)
}
/**
* Filp between the front and back camera
*/
flipCamera () {
TWVideoModule.flipCamera()
}
/**
* Toggle audio setup from speaker (default) and headset
*/
toggleSoundSetup (speaker) {
TWVideoModule.toggleSoundSetup(speaker)
}
/**
* Get connection stats
*/
getStats () {
TWVideoModule.getStats()
}
/**
* Connect to given room name using the JWT access token
* @param {String} roomName The connecting room name
* @param {String} accessToken The Twilio's JWT access token
*/
connect ({roomName, accessToken}) {
TWVideoModule.connect(accessToken, roomName)
}
/**
* Disconnect from current room
*/
disconnect () {
TWVideoModule.disconnect()
}
_startLocalVideo () {
const screenShare = this.props.screenShare || false
TWVideoModule.startLocalVideo(screenShare)
}
_stopLocalVideo () {
TWVideoModule.stopLocalVideo()
}
_startLocalAudio () {
TWVideoModule.startLocalAudio()
}
_stopLocalAudio () {
TWVideoModule.stopLocalAudio()
}
_unregisterEvents () {
this._subscriptions.forEach(e => e.remove())
this._subscriptions = []
}
_registerEvents () {
this._subscriptions = [
this._eventEmitter.addListener('roomDidConnect', (data) => {
if (this.props.onRoomDidConnect) { this.props.onRoomDidConnect(data) }
}),
this._eventEmitter.addListener('roomDidDisconnect', (data) => {
if (this.props.onRoomDidDisconnect) { this.props.onRoomDidDisconnect(data) }
}),
this._eventEmitter.addListener('roomDidFailToConnect', (data) => {
if (this.props.onRoomDidFailToConnect) { this.props.onRoomDidFailToConnect(data) }
}),
this._eventEmitter.addListener('roomParticipantDidConnect', (data) => {
if (this.props.onRoomParticipantDidConnect) { this.props.onRoomParticipantDidConnect(data) }
}),
this._eventEmitter.addListener('roomParticipantDidDisconnect', (data) => {
if (this.props.onRoomParticipantDidDisconnect) { this.props.onRoomParticipantDidDisconnect(data) }
}),
this._eventEmitter.addListener('participantAddedVideoTrack', (data) => {
if (this.props.onParticipantAddedVideoTrack) { this.props.onParticipantAddedVideoTrack(data) }
}),
this._eventEmitter.addListener('participantRemovedVideoTrack', (data) => {
if (this.props.onParticipantRemovedVideoTrack) { this.props.onParticipantRemovedVideoTrack(data) }
}),
this._eventEmitter.addListener('participantAddedAudioTrack', (data) => {
if (this.props.onParticipantAddedAudioTrack) { this.props.onParticipantAddedAudioTrack(data) }
}),
this._eventEmitter.addListener('participantRemovedAudioTrack', (data) => {
if (this.props.onParticipantRemovedAudioTrack) { this.props.onParticipantRemovedAudioTrack(data) }
}),
this._eventEmitter.addListener('participantEnabledVideoTrack', (data) => {
if (this.props.onParticipantEnabledVideoTrack) { this.props.onParticipantEnabledVideoTrack(data) }
}),
this._eventEmitter.addListener('participantDisabledVideoTrack', (data) => {
if (this.props.onParticipantDisabledVideoTrack) { this.props.onParticipantDisabledVideoTrack(data) }
}),
this._eventEmitter.addListener('participantEnabledAudioTrack', (data) => {
if (this.props.onParticipantEnabledAudioTrack) { this.props.onParticipantEnabledAudioTrack(data) }
}),
this._eventEmitter.addListener('participantDisabledAudioTrack', (data) => {
if (this.props.onParticipantDisabledAudioTrack) { this.props.onParticipantDisabledAudioTrack(data) }
}),
this._eventEmitter.addListener('cameraDidStart', (data) => {
if (this.props.onCameraDidStart) { this.props.onCameraDidStart(data) }
}),
this._eventEmitter.addListener('cameraWasInterrupted', (data) => {
if (this.props.onCameraWasInterrupted) { this.props.onCameraWasInterrupted(data) }
}),
this._eventEmitter.addListener('cameraDidStopRunning', (data) => {
if (this.props.onCameraDidStopRunning) { this.props.onCameraDidStopRunning(data) }
}),
this._eventEmitter.addListener('statsReceived', (data) => {
if (this.props.onStatsReceived) { this.props.onStatsReceived(data) }
})
]
}
render () {
return this.props.children || null
}
}
|
import Action from '../../ActionType';
import { Filter } from '../../FilterTypes';
import { applyFilter } from '../../utils';
const initialState = {
filteredLogs: [],
filter: { ...Filter }
};
const countryReducer = (state=initialState, action) => {
let filter;
switch (action.type) {
case Action.FILTER_REQUESTER_NAT:
filter = {
...state.filter,
RequesterNatType: action.payload.natType
};
state = {
...state,
filter: filter,
filteredLogs: applyFilter(action.payload.logs, filter)
};
break;
case Action.FILTER_RESPONDER_NAT:
filter = {
...state.filter,
ResponderNatType: action.payload.natType
};
state = {
...state,
filter: filter,
filteredLogs: applyFilter(action.payload.logs, filter)
};
break;
case Action.FILTER_REQUESTER_OS:
filter = {
...state.filter,
RequesterOS: action.payload.os
};
state = {
...state,
filter: filter,
filteredLogs: applyFilter(action.payload.logs, filter)
};
break;
case Action.FILTER_RESPONDER_OS:
filter = {
...state.filter,
ResponderOS: action.payload.os
};
state = {
...state,
filter: filter,
filteredLogs: applyFilter(action.payload.logs, filter)
};
break;
case Action.FILTER_BY_PROTOCOL:
filter = {
...state.filter,
Protocol: action.payload.protocol
};
state = {
...state,
filter: filter,
filteredLogs: applyFilter(action.payload.logs, filter)
};
break;
}
return state;
};
export default countryReducer;
|
/* eslint-env jest */
export function testReducerChanges(reducer, initialState) {
let state = initialState
return (action, expectedChange) => {
const expectedState = expectedChange(state)
expect(reducer(state, action)).toEqual(expectedState)
state = expectedState
}
}
export function testReducerSelector(reducer, selector, initialState) {
let state = initialState
return (action, expectedValue) => {
const newState = reducer(state, action)
expect(selector(newState)).toEqual(expectedValue)
state = newState
}
}
|
/*jslint browser:true, devel:true, white:true, vars:true */
/*global $:false, intel:false */
//Scramble Tweak
$(function(){
var tweak = $(".tweak");
tweak.shuffleLetters();
});
document.addEventListener("deviceready", function(){
}, false);
//Write to the created file
function writeFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
var textArea = document.getElementById("text").value + "\n";
function successCallback(fs) {
fs.root.getFile("log.txt", {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
alert("Address Saved");
};
fileWriter.onerror = function(e) {
alert("Address failed to save: ");
};
var blob = new Blob([textArea], {type: "text/plain"});
fileWriter.write(blob);
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("Error while trying to save the address");
}
}
//Read from the saved file
function readFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile("log.txt", {}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var textArea = document.getElementById("text");
alert(textArea.value = this.result);
};
reader.readAsText(file);
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("Please enter an address");
}
}
//Remove from the saved file
function removeFile() {
var type = window.TEMPORARY;
var size = 5*1024*1024;
window.requestFileSystem(type, size, successCallback, errorCallback)
function successCallback(fs) {
fs.root.getFile("log.txt", {create: false}, function(fileEntry) {
fileEntry.remove(function() {
alert("Address Cleared");
}, errorCallback);
}, errorCallback);
}
function errorCallback(error) {
alert("There is nothing to clear");
}
}
|
function hexToRGB(hex, alpha) {
var r = parseInt(hex.slice(1, 3), 16),
g = parseInt(hex.slice(3, 5), 16),
b = parseInt(hex.slice(5, 7), 16);
if (alpha) {
return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
} else {
return "rgb(" + r + ", " + g + ", " + b + ")";
}
}
function obtenerPaleta(item) {
switch (item) {
case 'COMPAÑÍA LIMITADA': return paletaColorProvedorLinea[0];
case 'PERSONA NATURAL': return paletaColorProvedorLinea[1];
case 'SOCIEDAD ANÓNIMA': return paletaColorProvedorLinea[2];
case 'REACTIVOS COVID': return paletaColorProducto[0];
case 'MASCARILLA KN95': return paletaColorProducto[1];
case 'BOLSAS CADÁVER': return paletaColorProducto[2];
case 'SERVICIO LABORATORIO': return paletaColorProducto[3];
case 'PRUEBAS RÁPIDAS': return paletaColorProducto[4];
case 'PRUEBAS PCR': return paletaColorProducto[5];
default: return '#e6beff';
}
}
paletaColorLinea = palette('cb-Set2', 5).map(function(hex) {
return hexToRGB('#' +hex,0.5); });
paletaColorProvedor = palette('cb-Dark2', 3).map(function(hex) {
return hexToRGB('#' +hex,0.5); });
paletaColorProvedorLinea = palette('cb-Dark2', 3).map(function(hex) {
return hexToRGB('#' +hex,1); });
paletaColorTipoEmpresa = palette('cb-Accent', 4).map(function(hex) {
return hexToRGB('#' +hex,0.5); });
paletaColorProducto = ['rgb(25, 135, 84)','rgb(220, 53, 69)','rgb(255, 193, 7)','rgba(30, 0, 0,0.3)','rgb(91, 202, 240)','rgb(13, 110, 253)']
|
const isPortReachable = require("is-port-reachable");
const path = require("path");
const dockerCompose = require("docker-compose");
const { execSync } = require("child_process");
module.exports = async () => {
console.time("global-setup");
// ️️️✅ Best Practice: Speed up during development, if already live then do nothing
const isDBReachable = await isPortReachable(54310);
if (!isDBReachable) {
// ️️️✅ Best Practice: Start the infrastructure within a test hook - No failures occur because the DB is down
await dockerCompose.upAll({
cwd: path.join(__dirname),
log: true,
});
await dockerCompose.exec("database", ["sh", "-c", "until pg_isready ; do sleep 1; done"], {
cwd: path.join(__dirname),
});
// ️️️✅ Best Practice: Use npm script for data seeding and migrations
execSync("npm run db:migrate");
// ✅ Best Practice: Seed only metadata and not test record, read "Dealing with data" section for further information
execSync("npm run db:seed");
}
// 👍🏼 We're ready
console.timeEnd("global-setup");
};
|
// @flow
import * as React from "react";
import { shallow } from "enzyme";
import CheckBox from "../index";
const label = "Checkbox";
const onChange = jest.fn();
const value = "option";
const dataTest = "test";
const tabIndex = "-1";
const name = "name";
describe(`Default CheckBox`, () => {
const component = shallow(
<CheckBox
label={label}
onChange={onChange}
value={value}
dataTest={dataTest}
name={name}
tabIndex={tabIndex}
/>,
);
const checkbox = component.find("Checkbox__Input");
it("should contain a label", () => {
expect(component.find("Checkbox__LabelText").render().text()).toBe(label);
});
it("inputs value should match", () => {
expect(checkbox.prop("value")).toBe(value);
});
it("should have data-test", () => {
expect(checkbox.render().prop("data-test")).toBe(dataTest);
});
it("should have data-state", () => {
expect(checkbox.render().prop("data-state")).toBe("ok");
});
it("should have tabindex", () => {
expect(checkbox.render().prop("tabindex")).toBe(tabIndex);
});
it("should have name", () => {
expect(checkbox.render().prop("attribs").name).toBe(name);
});
it("should execute onChange method", () => {
checkbox.simulate("change");
expect(onChange).toHaveBeenCalled();
});
});
|
$(function () {
'use strict';
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
//-----------------------
//- MONTHLY SALES CHART -
//-----------------------
// Get context with jQuery - using jQuery's .get() method.
var salesChartCanvas = $("#salesChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
var salesChart = new Chart(salesChartCanvas);
var salesChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Electronics",
fillColor: "rgb(210, 214, 222)",
strokeColor: "rgb(210, 214, 222)",
pointColor: "rgb(210, 214, 222)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgb(220,220,220)",
data: [65, 59, 80, 81, 56, 55, 40]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: [28, 48, 40, 19, 86, 27, 90]
}
]
};
var salesChartOptions = {
//Boolean - If we should show the scale at all
showScale: true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines: false,
//String - Colour of the grid lines
scaleGridLineColor: "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth: 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - Whether the line is curved between points
bezierCurve: true,
//Number - Tension of the bezier curve between points
bezierCurveTension: 0.3,
//Boolean - Whether to show a dot for each point
pointDot: false,
//Number - Radius of each point dot in pixels
pointDotRadius: 4,
//Number - Pixel width of point dot stroke
pointDotStrokeWidth: 1,
//Number - amount extra to add to the radius to cater for hit detection outside the drawn point
pointHitDetectionRadius: 20,
//Boolean - Whether to show a stroke for datasets
datasetStroke: true,
//Number - Pixel width of dataset stroke
datasetStrokeWidth: 2,
//Boolean - Whether to fill the dataset with a color
datasetFill: true,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].lineColor%>\"></span><%=datasets[i].label%></li><%}%></ul>",
//Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: true,
//Boolean - whether to make the chart responsive to window resizing
responsive: true
};
//Create the line chart
salesChart.Line(salesChartData, salesChartOptions);
//---------------------------
//- END MONTHLY SALES CHART -
//---------------------------
//-------------
//- PIE CHART -
//-------------
// Get context with jQuery - using jQuery's .get() method.
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = [
{
value: 700,
color: "#f56954",
highlight: "#f56954",
label: "Chrome"
},
{
value: 500,
color: "#00a65a",
highlight: "#00a65a",
label: "IE"
},
{
value: 400,
color: "#f39c12",
highlight: "#f39c12",
label: "FireFox"
},
{
value: 600,
color: "#00c0ef",
highlight: "#00c0ef",
label: "Safari"
},
{
value: 300,
color: "#a94442",
highlight: "#a94442",
label: "Opera"
},
{
value: 100,
color: "#d2d6de",
highlight: "#d2d6de",
label: "Navigator"
}
];
var pieOptions = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke: true,
//String - The colour of each segment stroke
segmentStrokeColor: "#fff",
//Number - The width of each segment stroke
segmentStrokeWidth: 1,
//Number - The percentage of the chart that we cut out of the middle
percentageInnerCutout: 50, // This is 0 for Pie charts
//Number - Amount of animation steps
animationSteps: 100,
//String - Animation easing effect
animationEasing: "easeOutBounce",
//Boolean - Whether we animate the rotation of the Doughnut
animateRotate: true,
//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale: false,
//Boolean - whether to make the chart responsive to window resizing
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
//String - A legend template
legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
//String - A tooltip template
tooltipTemplate: "<%=value %> <%=label%> users"
};
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
pieChart.Doughnut(PieData, pieOptions);
//-----------------
//- END PIE CHART -
//-----------------
/* jVector Maps
* ------------
* Create a world map with markers
*/
$('#world-map-markers').vectorMap({
map: 'world_mill_en',
normalizeFunction: 'polynomial',
hoverOpacity: 0.7,
hoverColor: false,
backgroundColor: 'transparent',
regionStyle: {
initial: {
fill: 'rgba(210, 214, 222, 1)',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
},
hover: {
"fill-opacity": 0.7,
cursor: 'pointer'
},
selected: {
fill: 'yellow'
},
selectedHover: {}
},
markerStyle: {
initial: {
fill: '#00a65a',
stroke: '#111'
}
},
markers: [
{latLng: [41.90, 12.45], name: 'Vatican City'},
{latLng: [43.73, 7.41], name: 'Monaco'},
{latLng: [-0.52, 166.93], name: 'Nauru'},
{latLng: [-8.51, 179.21], name: 'Tuvalu'},
{latLng: [43.93, 12.46], name: 'San Marino'},
{latLng: [47.14, 9.52], name: 'Liechtenstein'},
{latLng: [7.11, 171.06], name: 'Marshall Islands'},
{latLng: [17.3, -62.73], name: 'Saint Kitts and Nevis'},
{latLng: [3.2, 73.22], name: 'Maldives'},
{latLng: [35.88, 14.5], name: 'Malta'},
{latLng: [12.05, -61.75], name: 'Grenada'},
{latLng: [13.16, -61.23], name: 'Saint Vincent and the Grenadines'},
{latLng: [13.16, -59.55], name: 'Barbados'},
{latLng: [17.11, -61.85], name: 'Antigua and Barbuda'},
{latLng: [-4.61, 55.45], name: 'Seychelles'},
{latLng: [7.35, 134.46], name: 'Palau'},
{latLng: [42.5, 1.51], name: 'Andorra'},
{latLng: [14.01, -60.98], name: 'Saint Lucia'},
{latLng: [6.91, 158.18], name: 'Federated States of Micronesia'},
{latLng: [1.3, 103.8], name: 'Singapore'},
{latLng: [1.46, 173.03], name: 'Kiribati'},
{latLng: [-21.13, -175.2], name: 'Tonga'},
{latLng: [15.3, -61.38], name: 'Dominica'},
{latLng: [-20.2, 57.5], name: 'Mauritius'},
{latLng: [26.02, 50.55], name: 'Bahrain'},
{latLng: [0.33, 6.73], name: 'São Tomé and Príncipe'}
]
});
/* SPARKLINE CHARTS
* ----------------
* Create a inline charts with spark line
*/
//-----------------
//- SPARKLINE BAR -
//-----------------
$('.sparkbar').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'bar',
height: $this.data('height') ? $this.data('height') : '30',
barColor: $this.data('color')
});
});
//-----------------
//- SPARKLINE PIE -
//-----------------
$('.sparkpie').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'pie',
height: $this.data('height') ? $this.data('height') : '90',
sliceColors: $this.data('color')
});
});
//------------------
//- SPARKLINE LINE -
//------------------
$('.sparkline').each(function () {
var $this = $(this);
$this.sparkline('html', {
type: 'line',
height: $this.data('height') ? $this.data('height') : '90',
width: '100%',
lineColor: $this.data('linecolor'),
fillColor: $this.data('fillcolor'),
spotColor: $this.data('spotcolor')
});
});
});
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* Copyright (c) 2016-present, Ali Najafizadeh
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule WebViewBridge
* @flow
*/
'use strict';
var React = require('react');
var PropTypes = require('prop-types');
var ReactNative = require('react-native');
var createReactClass = require('create-react-class');
var invariant = require('invariant');
var keyMirror = require('keymirror');
var resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource');
var WebView = require('react-native-webview');
var {
ActivityIndicator,
EdgeInsetsPropType,
StyleSheet,
Text,
View,
ViewPropTypes,
requireNativeComponent,
UIManager,
NativeModules: {
WebViewBridgeManager,
},
} = ReactNative;
var BGWASH = 'rgba(255,255,255,0.8)';
var RCT_WEBVIEWBRIDGE_REF = 'webviewbridge';
var RCTWebViewBridgeManager = WebViewBridgeManager;
var WebViewBridgeState = keyMirror({
IDLE: null,
LOADING: null,
ERROR: null,
});
var NavigationType = {
click: RCTWebViewBridgeManager.NavigationType.LinkClicked,
formsubmit: RCTWebViewBridgeManager.NavigationType.FormSubmitted,
backforward: RCTWebViewBridgeManager.NavigationType.BackForward,
reload: RCTWebViewBridgeManager.NavigationType.Reload,
formresubmit: RCTWebViewBridgeManager.NavigationType.FormResubmitted,
other: RCTWebViewBridgeManager.NavigationType.Other,
};
var JSNavigationScheme = RCTWebViewBridgeManager.JSNavigationScheme;
type ErrorEvent = {
domain: any;
code: any;
description: any;
}
type Event = Object;
var defaultRenderLoading = () => (
<View style={styles.loadingView}>
<ActivityIndicator />
</View>
);
var defaultRenderError = (errorDomain, errorCode, errorDesc) => (
<View style={styles.errorContainer}>
<Text style={styles.errorTextTitle}>
Error loading page
</Text>
<Text style={styles.errorText}>
{'Domain: ' + errorDomain}
</Text>
<Text style={styles.errorText}>
{'Error Code: ' + errorCode}
</Text>
<Text style={styles.errorText}>
{'Description: ' + errorDesc}
</Text>
</View>
);
/**
* Renders a native WebView.
*/
var WebViewBridge = createReactClass({
statics: {
JSNavigationScheme: JSNavigationScheme,
NavigationType: NavigationType,
},
propTypes: {
...WebView.propTypes,
/**
* Will be called once the message is being sent from webview
*/
onBridgeMessage: PropTypes.func,
hideKeyboardAccessoryView: PropTypes.bool,
keyboardDisplayRequiresUserAction: PropTypes.bool,
},
getInitialState: function () {
return {
viewState: WebViewBridgeState.IDLE,
lastErrorEvent: (null: ?ErrorEvent),
startInLoadingState: true,
};
},
componentWillMount: function() {
if (this.props.startInLoadingState) {
this.setState({ viewState: WebViewBridgeState.LOADING });
}
},
render: function() {
var otherView = null;
if (this.state.viewState === WebViewBridgeState.LOADING) {
otherView = (this.props.renderLoading || defaultRenderLoading)();
} else if (this.state.viewState === WebViewBridgeState.ERROR) {
var errorEvent = this.state.lastErrorEvent;
invariant(
errorEvent != null,
'lastErrorEvent expected to be non-null'
);
otherView = (this.props.renderError || defaultRenderError)(
errorEvent.domain,
errorEvent.code,
errorEvent.description
);
} else if (this.state.viewState !== WebViewBridgeState.IDLE) {
console.error(
'RCTWebViewBridge invalid state encountered: ' + this.state.loading
);
}
var webViewStyles = [styles.container, styles.webView, this.props.style];
if (this.state.viewState === WebViewBridgeState.LOADING ||
this.state.viewState === WebViewBridgeState.ERROR) {
// if we're in either LOADING or ERROR states, don't show the webView
webViewStyles.push(styles.hidden);
}
var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => {
var shouldStart = this.props.onShouldStartLoadWithRequest &&
this.props.onShouldStartLoadWithRequest(event.nativeEvent);
RCTWebViewBridgeManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
});
var { javaScriptEnabled, domStorageEnabled } = this.props;
if (this.props.javaScriptEnabledAndroid) {
console.warn('javaScriptEnabledAndroid is deprecated. Use javaScriptEnabled instead');
javaScriptEnabled = this.props.javaScriptEnabledAndroid;
}
if (this.props.domStorageEnabledAndroid) {
console.warn('domStorageEnabledAndroid is deprecated. Use domStorageEnabled instead');
domStorageEnabled = this.props.domStorageEnabledAndroid;
}
var onBridgeMessage = (event: Event) => {
const onBridgeMessageCallback = this.props.onBridgeMessage;
if (onBridgeMessageCallback) {
const messages = event.nativeEvent.messages;
if (messages && typeof messages.forEach === "function")
messages.forEach((message) => {
onBridgeMessageCallback(message);
});
}
};
let { source, ...props } = { ...this.props };
delete props.onBridgeMessage;
delete props.onShouldStartLoadWithRequest;
var webView =
<RCTWebViewBridge
ref={RCT_WEBVIEWBRIDGE_REF}
key="webViewKey"
{...props}
source={resolveAssetSource(source)}
style={webViewStyles}
onLoadingStart={this.onLoadingStart}
onLoadingFinish={this.onLoadingFinish}
onLoadingError={this.onLoadingError}
onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
onBridgeMessage={onBridgeMessage}
/>;
return (
<View style={styles.container}>
{webView}
{otherView}
</View>
);
},
goForward: function() {
UIManager.dispatchViewManagerCommand(
this.getWebViewBridgeHandle(),
UIManager.RCTWebViewBridge.Commands.goForward,
null
);
},
goBack: function() {
UIManager.dispatchViewManagerCommand(
this.getWebViewBridgeHandle(),
UIManager.RCTWebViewBridge.Commands.goBack,
null
);
},
reload: function() {
UIManager.dispatchViewManagerCommand(
this.getWebViewBridgeHandle(),
UIManager.RCTWebViewBridge.Commands.reload,
null
);
},
sendToBridge: function (message: string) {
WebViewBridgeManager.sendToBridge(this.getWebViewBridgeHandle(), message);
},
/**
* We return an event with a bunch of fields including:
* url, title, loading, canGoBack, canGoForward
*/
updateNavigationState: function(event: Event) {
if (this.props.onNavigationStateChange) {
this.props.onNavigationStateChange(event.nativeEvent);
}
},
getWebViewBridgeHandle: function(): any {
return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEWBRIDGE_REF]);
},
onLoadingStart: function(event: Event) {
var onLoadStart = this.props.onLoadStart;
onLoadStart && onLoadStart(event);
this.updateNavigationState(event);
},
onLoadingError: function(event: Event) {
event.persist(); // persist this event because we need to store it
var { onError, onLoadEnd } = this.props;
onError && onError(event);
onLoadEnd && onLoadEnd(event);
console.warn('Encountered an error loading page', event.nativeEvent);
this.setState({
lastErrorEvent: event.nativeEvent,
viewState: WebViewBridgeState.ERROR,
});
},
onLoadingFinish: function(event: Event) {
var { onLoad, onLoadEnd } = this.props;
onLoad && onLoad(event);
onLoadEnd && onLoadEnd(event);
this.setState({
viewState: WebViewBridgeState.IDLE,
});
this.updateNavigationState(event);
},
});
var RCTWebViewBridge = requireNativeComponent('RCTWebViewBridge', WebViewBridge, {
nativeOnly: {
onLoadingStart: true,
onLoadingError: true,
onLoadingFinish: true,
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
},
errorContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: BGWASH,
},
errorText: {
fontSize: 14,
textAlign: 'center',
marginBottom: 2,
},
errorTextTitle: {
fontSize: 15,
fontWeight: '500',
marginBottom: 10,
},
hidden: {
height: 0,
flex: 0, // disable 'flex:1' when hiding a View
},
loadingView: {
backgroundColor: BGWASH,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
webView: {
backgroundColor: '#ffffff',
},
});
module.exports = WebViewBridge;
|
/*
Hielo by TEMPLATED
templated.co @templatedco
Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
*/
var settings = {
banner: {
// Indicators (= the clickable dots at the bottom).
indicators: true,
// Transition speed (in ms)
// For timing purposes only. It *must* match the transition speed of "#banner > article".
speed: 1500,
// Transition delay (in ms)
delay: 5000,
// Parallax intensity (between 0 and 1; higher = more intense, lower = less intense; 0 = off)
parallax: 0.25
}
};
(function($) {
skel.breakpoints({
xlarge: '(max-width: 1680px)',
large: '(max-width: 1280px)',
medium: '(max-width: 980px)',
small: '(max-width: 736px)',
xsmall: '(max-width: 480px)'
});
/**
* Applies parallax scrolling to an element's background image.
* @return {jQuery} jQuery object.
*/
$.fn._parallax = (skel.vars.browser == 'ie' || skel.vars.mobile) ? function() { return $(this) } : function(intensity) {
var $window = $(window),
$this = $(this);
if (this.length == 0 || intensity === 0)
return $this;
if (this.length > 1) {
for (var i=0; i < this.length; i++)
$(this[i])._parallax(intensity);
return $this;
}
if (!intensity)
intensity = 0.25;
$this.each(function() {
var $t = $(this),
on, off;
on = function() {
$t.css('background-position', 'center 100%, center 100%, center 0px');
$window
.on('scroll._parallax', function() {
var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);
$t.css('background-position', 'center ' + (pos * (-1 * intensity)) + 'px');
});
};
off = function() {
$t
.css('background-position', '');
$window
.off('scroll._parallax');
};
skel.on('change', function() {
if (skel.breakpoint('medium').active)
(off)();
else
(on)();
});
});
$window
.off('load._parallax resize._parallax')
.on('load._parallax resize._parallax', function() {
$window.trigger('scroll');
});
return $(this);
};
/**
* Custom banner slider for Slate.
* @return {jQuery} jQuery object.
*/
$.fn._slider = function(options) {
var $window = $(window),
$this = $(this);
if (this.length == 0)
return $this;
if (this.length > 1) {
for (var i=0; i < this.length; i++)
$(this[i])._slider(options);
return $this;
}
// Vars.
var current = 0, pos = 0, lastPos = 0,
slides = [], indicators = [],
$indicators,
$slides = $this.children('article'),
intervalId,
isLocked = false,
i = 0;
// Turn off indicators if we only have one slide.
if ($slides.length == 1)
options.indicators = false;
// Functions.
$this._switchTo = function(x, stop) {
if (isLocked || pos == x)
return;
isLocked = true;
if (stop)
window.clearInterval(intervalId);
// Update positions.
lastPos = pos;
pos = x;
// Hide last slide.
slides[lastPos].removeClass('top');
if (options.indicators)
indicators[lastPos].removeClass('visible');
// Show new slide.
slides[pos].addClass('visible').addClass('top');
if (options.indicators)
indicators[pos].addClass('visible');
// Finish hiding last slide after a short delay.
window.setTimeout(function() {
slides[lastPos].addClass('instant').removeClass('visible');
window.setTimeout(function() {
slides[lastPos].removeClass('instant');
isLocked = false;
}, 100);
}, options.speed);
};
// Indicators.
if (options.indicators)
$indicators = $('<ul class="indicators"></ul>').appendTo($this);
// Slides.
$slides
.each(function() {
var $slide = $(this),
$img = $slide.find('img');
// Slide.
$slide
.css('background-image', 'url("' + $img.attr('src') + '")')
.css('background-position', ($slide.data('position') ? $slide.data('position') : 'center'));
// Add to slides.
slides.push($slide);
// Indicators.
if (options.indicators) {
var $indicator_li = $('<li>' + i + '</li>').appendTo($indicators);
// Indicator.
$indicator_li
.data('index', i)
.on('click', function() {
$this._switchTo($(this).data('index'), true);
});
// Add to indicators.
indicators.push($indicator_li);
}
i++;
})
._parallax(options.parallax);
// Initial slide.
slides[pos].addClass('visible').addClass('top');
if (options.indicators)
indicators[pos].addClass('visible');
// Bail if we only have a single slide.
if (slides.length == 1)
return;
// Main loop.
intervalId = window.setInterval(function() {
current++;
if (current >= slides.length)
current = 0;
$this._switchTo(current);
}, options.delay);
};
$(function() {
var $window = $(window),
$body = $('body'),
$header = $('#header'),
$banner = $('.banner');
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-loading');
}, 100);
});
// Prioritize "important" elements on medium.
skel.on('+medium -medium', function() {
$.prioritize(
'.important\\28 medium\\29',
skel.breakpoint('medium').active
);
});
// Banner.
$banner._slider(settings.banner);
// Menu.
$('#menu')
.append('<a href="#menu" class="close"></a>')
.appendTo($body)
.panel({
delay: 500,
hideOnClick: true,
hideOnSwipe: true,
resetScroll: true,
resetForms: true,
side: 'right'
});
// Header.
if (skel.vars.IEVersion < 9)
$header.removeClass('alt');
if ($banner.length > 0
&& $header.hasClass('alt')) {
$window.on('resize', function() { $window.trigger('scroll'); });
$banner.scrollex({
bottom: $header.outerHeight(),
terminate: function() { $header.removeClass('alt'); },
enter: function() { $header.addClass('alt'); },
leave: function() { $header.removeClass('alt'); $header.addClass('reveal'); }
});
}
});
})(jQuery);
|
//search controller
//importing elastic search client
const elasticController = require("./elasticController");
//importing logger
const logger = require("../config/dev-logger");
//handles search route using elasticsearch
const elasticSearch = async (req, res) => {
try {
var term;
//if query does not exists throw error
if (!req.query.term) {
throw "No query exists!";
} else {
//search
const search = await elasticController.elasticSearch(req.query.term);
//return result
return res.json(search);
}
} catch (error) {
logger.error(new Error(error), {
location: "./controller/searchController",
});
//returning error
res.status(400).send(error);
}
};
//filters by category with elasticsearch
const elasticFilter = async (req, res) => {
try {
if (!req.params.categoryname) {
throw "Categoryname does not exists";
}
//filter with elasticsearch
const filter = await elasticController.elasticFilter(
req.params.categoryname
);
//returning filter
res.send(filter);
} catch (error) {
logger.error(new Error(error), {
location: "./controller/searchController",
});
//returning error
res.status(400).send(error);
}
};
module.exports = { elasticSearch, elasticFilter };
|
import DOM from "./dom";
import { LitElement, html, customElement, property } from "lit-element";
@customElement("page-loader")
export default class PageLoader extends LitElement {
@property()
name;
@property()
route;
createRenderRoot() {
return this;
}
pageContent = null;
render() {
return html`
<div class="xl:col-start-2 xl:col-span-2 lg:col-start-1">
<main id="content" class="p-5">${this.pageContent}</main>
</div>
`;
}
async load(page, pages) {
let pageItem = pages.find(item => item.name === page);
if (!pageItem) {
return;
}
window.history.pushState(null, pageItem.title, pageItem.route);
if (pageItem == null) {
let pageName = location.href.split("/").pop();
if (pageName !== "") {
pageItem = pages.find(x => x.name == pageName);
} else {
pageItem = pages[0];
}
}
this.classList.add("relative", "grid", "xl:grid-cols-4", "lg:grid-cols-1");
this.setAttribute("style", "top: 70px");
try {
let pagePrefix = pageItem.name.substr(0, pageItem.name.indexOf('-')+1);
let modulePage = pageItem.name.replace(pagePrefix, ''); // Removes the module source
let suffix = '-page';
if (modulePage === 'dapp') {
await import(`../pages/${modulePage}.js`);
} else if (modulePage === 'harness') {
await import(`../harness/harness.js`);
} else if (modulePage === 'customizer') {
await import(`../components/customizer.js`);
} else if (modulePage.indexOf('-customizer') > -1) {
// Dynamically added
await import(`../harness/${modulePage}.js`);
suffix = '';
} else {
suffix = '-harness';
await import(`../harness/${modulePage}-harness.js`);
}
let pageName = modulePage.replace('_', '-') + suffix;
this.pageContent = DOM.create(pageName, {
title: pageItem.title,
description: pageItem.description,
category: pageItem.category
});
} catch (e) {
console.log(e);
this.pageContent = DOM.div(
`Error loading content page for "${pageItem.title}"`
);
}
this.requestUpdate();
}
}
|
const agent = require('superagent-promise')(require('superagent'), Promise);
const statusCode = require('http-status-codes');
const { expect } = require('chai');
describe('First Api Tests', () => {
it('Consume GET Service', () => {
return agent.get('https://httpbin.org/ip').then((response) => {
expect(response.status).to.equal(statusCode.OK);
expect(response.body).to.have.property('origin');
});
});
it('Consume GET Service with query parameters', () => {
const query = {
name: 'John',
age: '31',
city: 'New York'
};
return agent.get('https://httpbin.org/get')
.query(query)
.then((response) => {
expect(response.status).to.equal(statusCode.OK);
expect(response.body.args).to.eql(query);
});
});
});
|
/**
* @license
* Copyright (c) 2020 DigiByte Foundation NZ Limited
*
* 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.
*/
const { InternalError } = require('../errors');
const { AmountValue } = require('../utils');
const ANY = '*';
const POSITIVE = '+';
const NEGATIVE = '-';
/**
* Sign is used to represent possible signedness of an amount.
* @class
*/
class Sign {
/**
* @constructor
* @param {number|string} input
*/
constructor(input) {
if ([ANY, POSITIVE, NEGATIVE].includes(input)) {
this.type = input;
} else if (typeof input == 'number') {
switch(this.sign(input)) {
case -1: this.type = NEGATIVE; break;
case +1: this.type = POSITIVE; break;
case 0: this.type = POSITIVE; break;
}
} else {
throw new InternalError(`Sign's constructor doesn't allow '${input}'`);
}
}
/**
* Check is a positive or negative amount.
* @param {number} number - amount
* @returns {number}
*/
sign(number) {
if (typeof number !== 'number') {
throw new InternalError(`n in sign(n) must be a number`);
}
if (number > 0) return 1;
if (number < 0) return -1;
return 0;
}
/**
* Match returns a boolean indicating if an amount type has an amount sign.
* @param {Rosetta:Amount} amount - amount
* @returns {boolean} - indicating if an amount type has an amount sign
*/
match(amount) {
if (this.type == ANY) {
return true;
}
try {
const numeric = AmountValue(amount);
if (this.type == NEGATIVE && this.sign(numeric) == -1) {
return true;
}
if (this.type == POSITIVE && this.sign(numeric) == 1) {
return true;
}
} catch (e) {
console.error(`ERROR`, e);
return false;
}
}
/**
* Get description of an amount sign.
* @returns {string} - description of an amount sign
*/
toString() {
return this.type;
}
}
Sign.Positive = POSITIVE;
Sign.Negative = NEGATIVE;
Sign.Any = ANY;
module.exports = Sign;
|
import React from "react"
import { graphql } from "gatsby"
import { css } from "@emotion/core"
import { MDXRenderer } from "gatsby-plugin-mdx"
import ReadLink from "../components/read-link"
import DefaultLayout from "../components/default-layout"
export const query = graphql`
query($slug: String!) {
mdx(frontmatter: { slug: { eq: $slug } }) {
frontmatter {
title
author
}
body
}
}
`
const PostTemplate = ({ data: { mdx: post } }) => (
<DefaultLayout>
<h1>{post.frontmatter.title}</h1>
<p
css={css`
font-size: 0.75rem;
`}
>
by: {post.frontmatter.author}
</p>
<MDXRenderer>{post.body}</MDXRenderer>
<ReadLink to="/">← back to all posts</ReadLink>
</DefaultLayout>
)
export default PostTemplate
|
// Results container with weather and restaurants/events components
import React from 'react';
import Weather from '../components/Weather/Weather';
import Yelp from '../components/YelpResults/Yelp';
import { Redirect } from 'react-router';
const Results = ( {location} ) => {
// If no search term passed, return to home
if (!location.state) {
return <Redirect to="/"/>;
}
return (
<>
<Weather search={location.state.search}/>
<Yelp search={location.state.search}/>
</>
)
}
export default Results;
|
/*jshint laxbreak:true*/
var Q = require('q');
var fs = require('../util/fs');
var path = require('path');
var mout = require('mout');
var resolvers = require('./resolvers');
var createError = require('../util/createError');
var pluginResolverFactory = require('./resolvers/pluginResolverFactory');
function createInstance(decEndpoint, options, registryClient) {
decEndpoint = mout.object.pick(decEndpoint, ['name', 'target', 'source']);
options.version = require('../../package.json').version;
return getConstructor(decEndpoint, options, registryClient)
.spread(function (ConcreteResolver, decEndpoint) {
return new ConcreteResolver(decEndpoint, options.config, options.logger);
});
}
function getConstructor(decEndpoint, options, registryClient) {
var source = decEndpoint.source;
var config = options.config;
// Below we try a series of async tests to guess the type of resolver to use
// If a step was unable to guess the resolver, it returns undefined
// If a step can guess the resolver, it returns with construcotor of resolver
var promise = Q.resolve();
var addResolver = function (resolverFactory) {
promise = promise.then(function (result) {
if (result === undefined) {
return resolverFactory(decEndpoint, options);
} else {
return result;
}
});
};
// Plugin resolvers.
//
// It requires each resolver defined in config.resolvers and calls
// its "match" to check if given resolves supports given decEndpoint
addResolver(function () {
var selectedResolver;
var resolverNames;
if (Array.isArray(config.resolvers)) {
resolverNames = config.resolvers;
} else if (!!config.resolvers) {
resolverNames = config.resolvers.split(',');
} else {
resolverNames = [];
}
var resolverPromises = resolverNames.map(function (resolverName) {
var resolver = resolvers[resolverName]
|| pluginResolverFactory(require(resolverName), options);
return function () {
if (selectedResolver === undefined) {
var match = resolver.match.bind(resolver);
return Q.fcall(match, source).then(function (result) {
if (result) {
return selectedResolver = resolver;
}
});
} else {
return selectedResolver;
}
};
});
return resolverPromises.reduce(Q.when, new Q(undefined)).then(function (resolver) {
if (resolver) {
return Q.fcall(resolver.locate.bind(resolver), decEndpoint.source).then(function (result) {
if (result && result !== decEndpoint.source) {
decEndpoint.source = result;
decEndpoint.registry = true;
return getConstructor(decEndpoint, options, registryClient);
} else {
return [resolver, decEndpoint];
}
});
}
});
});
// Git case: git git+ssh, git+http, git+https
// .git at the end (probably ssh shorthand)
// git@ at the start
addResolver(function() {
if (/^git(\+(ssh|https?))?:\/\//i.test(source) || /\.git\/?$/i.test(source) || /^git@/i.test(source)) {
decEndpoint.source = source.replace(/^git\+/, '');
// If it's a GitHub repository, return the specialized resolver
if (resolvers.GitHub.getOrgRepoPair(source)) {
return [resolvers.GitHub, decEndpoint];
}
return [resolvers.GitRemote, decEndpoint];
}
});
// SVN case: svn, svn+ssh, svn+http, svn+https, svn+file
addResolver(function () {
if (/^svn(\+(ssh|https?|file))?:\/\//i.test(source)) {
return [resolvers.Svn, decEndpoint];
}
});
// URL case
addResolver(function () {
if (/^https?:\/\//i.exec(source)) {
return [resolvers.Url, decEndpoint];
}
});
// If source is ./ or ../ or an absolute path
addResolver(function () {
var absolutePath = path.resolve(config.cwd, source);
if (/^\.\.?[\/\\]/.test(source) || /^~\//.test(source) ||
path.normalize(source).replace(/[\/\\]+$/, '') === absolutePath
) {
return Q.nfcall(fs.stat, path.join(absolutePath, '.git'))
.then(function (stats) {
decEndpoint.source = absolutePath;
if (stats.isDirectory()) {
return Q.resolve([resolvers.GitFs, decEndpoint]);
}
throw new Error('Not a Git repository');
})
// If not, check if source is a valid Subversion repository
.fail(function () {
return Q.nfcall(fs.stat, path.join(absolutePath, '.svn'))
.then(function (stats) {
decEndpoint.source = absolutePath;
if (stats.isDirectory()) {
return Q.resolve([resolvers.Svn, decEndpoint]);
}
throw new Error('Not a Subversion repository');
});
})
// If not, check if source is a valid file/folder
.fail(function () {
return Q.nfcall(fs.stat, absolutePath)
.then(function () {
decEndpoint.source = absolutePath;
return Q.resolve([resolvers.Fs, decEndpoint]);
});
});
}
});
// Check if is a shorthand and expand it
addResolver(function () {
// Skip ssh and/or URL with auth
if (/[:@]/.test(source)) {
return;
}
// Ensure exactly only one "/"
var parts = source.split('/');
if (parts.length === 2) {
decEndpoint.source = mout.string.interpolate(config.shorthandResolver, {
shorthand: source,
owner: parts[0],
package: parts[1]
});
return getConstructor(decEndpoint, options, registryClient);
}
});
// As last resort, we try the registry
addResolver(function () {
if (!registryClient) {
return;
}
return Q.nfcall(registryClient.lookup.bind(registryClient), source)
.then(function (entry) {
if (!entry) {
throw createError('Package ' + source + ' not found', 'ENOTFOUND');
}
decEndpoint.registry = true;
if (!decEndpoint.name) {
decEndpoint.name = decEndpoint.source;
}
decEndpoint.source = entry.url;
return getConstructor(decEndpoint, options);
});
});
addResolver(function () {
throw createError('Could not find appropriate resolver for ' + source, 'ENORESOLVER');
});
return promise;
}
function clearRuntimeCache() {
mout.object.values(resolvers).forEach(function (ConcreteResolver) {
ConcreteResolver.clearRuntimeCache();
});
}
module.exports = createInstance;
module.exports.getConstructor = getConstructor;
module.exports.clearRuntimeCache = clearRuntimeCache;
|
"use strict";
/* this module solves active requests.
* it prepares data, session and parameters for pager.
*/
const conf=require("../conf");
const Path=require("path");
const Tools=require("./Tools");
const SessionPool=require("./SessionPool");
const fs=require("fs");
const Pager=require("./Pager");
const net=require("net");
function Sharer()
{//This is a class that can communicate with Sharer.js.
let counter=0;
let callbacks=new Object; //callback map.
let npl=-1;
let cache=new Buffer(0);
let socket=net.connect({host: "127.0.0.1",port: conf.sharerPort},function()
{//connect to share when starting.
socket.on("data",function(packet)
{
cache=Buffer.concat([cache,packet]); //buffer filling.
PacketReciever(); //buffer checking.
}).on("close",function()
{
cache=null;
});
});
socket.on("error",function(err)
{
console.log(err);
console.log("Connection error[Share]");
});
function PacketReciever()
{//Buffer checker, if there is a packet in buffer, pick it out, and solve it.
if (cache.length>=4)
{
npl=cache.readUInt32BE(0);
if (cache.length>=npl)
{
let tmp=cache.slice(0,npl);
cache=cache.slice(npl);
PacketProcessor(tmp); //solve the packet.
}
}
}
function PacketProcessor(pack)
{
let packet=pack.slice(4).toString("utf8");
packet=JSON.parse(packet);
let fn=callbacks[packet.stamp]; //pick out the callback of the packet with 'stamp' column in the packet.
if (typeof(fn)!="function")
{
return;
}
fn(packet); //pass packet to callback.
delete callbacks[packet.stamp]; //clear up.
}
function getStamp()
{//this function returns a stamp simply. The stamp must be unque.
let stamp=String(process.pid);
stamp+=String((new Date).getTime());
stamp+=String(counter++);
return stamp;
}
this.setKey=function(keyName,value,fn)
{//set a key/value to share.
let req={type: "operation", //request packet.
operation: "setKey",
request: {keyName: keyName,
keyValue: value,
dataType: typeof(value)}};
req.stamp=getStamp(); //load stamp.
if (typeof(value)=="object")
{//check if the value is a buffer. if it is, set dataType 'buffer', it will make share know that the value of the packet is a buffer.
if (value instanceof Buffer)
{
req.request.dataType="buffer";
}
else if (value instanceof Array)
{
req.request.dataType="array";
}
}
callbacks[req.stamp]=fn; //bind callback.
req=JSON.stringify(req);
let buff=new Buffer(req.length+4);
buff.write(req,4);
buff.writeUInt32BE(buff.length,0);
socket.write(buff);
};
this.getKey=function(keyName,fn)
{//get a key/value from share.
let req={type: "operation",
operation: "getKey",
request: {keyName: keyName}};
req.stamp=getStamp();
callbacks[req.stamp]=fn;
req=JSON.stringify(req);
let buff=new Buffer(req.length+4);
buff.write(req,4);
buff.writeUInt32BE(buff.length,0);
socket.write(buff);
};
}
var sharer=new Sharer;
var sessionPool=new SessionPool;
function Active(req,res)
{
if (typeof(req.headers["Host"])!="string")
{//if the Host header is not set, return.
return false;
}
let host=req.headers["Host"];
let siteConf;
try
{//get the environment of the domain.
siteConf=require("../"+conf.domains[host]+"/conf");
}
catch (e)
{
return false;
}
const home="./"+conf.domains[host];
const homeTemplates=home+"/Templates";
const homeActives=home+"/Activities";
const homeRequires=home+"/Plugs";
let reqPath=req.url.split("?")[0];
if (reqPath.substring(reqPath.length-1,reqPath.length)=="/")
{//check if the request url is root.
reqPath+=siteConf.defaultPage; //append default page to request url.
}
let ename=Path.extname(reqPath); //get extension name.
if (ename==("."+siteConf.template))
{//if the extension name is template type, return 404.
res.statusCode=404;
res.end("404 not found!");
return true;
}
if (ename!=("."+siteConf.active))
{//if the extionsion name is not for activity, return false and let static part solve with this.
return false;
}
res.headers["Content-Type"]=siteConf.contentTypes[ename] || "application/unknow";
//set content-type header of response.
let reqFile=reqPath.substring(0,reqPath.lastIndexOf("."));
function Prepare()
{//invoking preparer.
let sid=req.cookies["malache2SESSION"] || sessionPool.create();
if (!sessionPool.hasSession(sid))
{//if the session is not existing, create it.
sid=sessionPool.create();
}
let session=sessionPool.get(sid);
if (!session)
{//if the session is not available, recreate it.
sessionPool.create(sid);
session=sessionPool.get(sid);
}
fs.readFile(homeActives+reqFile+".js","utf8",function(err,jsCode)
{//read js code from active folder.
if (err)
{//not found.
console.log(err);
res.statusCode=404;
res.end("404 not found!");
return;
}
Pager.loadJsCode(req, //this is the start of execution.
res,
session,
sharer,
sid,
siteConf,
jsCode,
homeTemplates+reqFile+"."+siteConf.template,
home,
homeActives+reqFile+".js",
reqPath);
});
}
Tools.formatParameters(req,Prepare); //call the preparer after formatting parameters.
return true;
}
module.exports=Active;
|
/*
Base, version 1.0.2
Copyright 2006, Dean Edwards
License: http://creativecommons.org/licenses/LGPL/2.1/
*/
var Base = function() {
if (arguments.length) {
if (this == window) { // cast an object to this class
Base.prototype.extend.call(arguments[0], arguments.callee.prototype);
} else {
this.extend(arguments[0]);
}
}
};
Base.version = "1.0.2";
Base.prototype = {
extend: function(source, value) {
var extend = Base.prototype.extend;
if (arguments.length == 2) {
var ancestor = this[source];
var ancestorClass = this.constructor ? this.constructor.prototype : null;
// overriding?
if ((ancestor instanceof Function) && (value instanceof Function) &&
ancestor.valueOf() != value.valueOf() && /\bbase\b/.test(value)) {
var method = value;
// var _prototype = this.constructor.prototype;
// var fromPrototype = !Base._prototyping && _prototype[source] == ancestor;
value = function() {
var previous = this.base;
var previousClass = this;
// this.base = fromPrototype ? _prototype[source] : ancestor;
this.base = ancestor;
this.baseClass = ancestorClass;
var returnValue = method.apply(this, arguments);
this.base = previous;
this.baseClass = previousClass;
return returnValue;
};
// point to the underlying method
value.valueOf = function() {
return method;
};
value.toString = function() {
return String(method);
};
}
return this[source] = value;
} else if (source) {
var _prototype = {toSource: null};
// do the "toString" and other methods manually
var _protected = ["toString", "valueOf"];
// if we are prototyping then include the constructor
if (Base._prototyping) _protected[2] = "constructor";
for (var i = 0; (name = _protected[i]); i++) {
if (source[name] != _prototype[name]) {
extend.call(this, name, source[name]);
}
}
// copy each of the source object's properties to this object
for (var name in source) {
if (!_prototype[name]) {
extend.call(this, name, source[name]);
}
}
}
return this;
},
base: function() {
// call this method from any other method to invoke that method's ancestor
}
};
Base.extend = function(_instance, _static) {
var extend = Base.prototype.extend;
if (!_instance) _instance = {};
// build the prototype
Base._prototyping = true;
var _prototype = new this;
extend.call(_prototype, _instance);
var constructor = _prototype.constructor;
_prototype.constructor = this;
delete Base._prototyping;
// create the wrapper for the constructor function
var klass = function() {
if (!Base._prototyping) constructor.apply(this, arguments);
this.constructor = klass;
};
klass.prototype = _prototype;
// build the class interface
klass.extend = this.extend;
klass.implement = this.implement;
klass.create = this.create;
klass.getClassName = this.getClassName;
klass.toString = function() {
return String(constructor);
};
klass.isInstance = function(obj) {
/*
return (typeof obj != "undefined" && obj !== null &&
obj.constructor && obj.constructor.__ancestors &&
obj.constructor.__ancestors[klass.getClassName()]);
*/
return obj instanceof klass;
};
extend.call(klass, _static);
// single instance
var object = constructor ? klass : _prototype;
// class initialisation
if (object.init instanceof Function) object.init();
if (!klass.__ancestors) {
klass.__ancestors = {};
klass.__ancestors[klass.getClassName()] = true;
var chain = function(k) {
if (k.prototype && k.prototype.constructor && k.prototype.constructor.getClassName) {
klass.__ancestors[k.prototype.constructor.getClassName()] = true;
chain(k.prototype.constructor);
}
};
chain(klass);
}
if (klass.getClassName) {
// remember the class name
object.className = klass.getClassName();
}
return object;
};
Base.implement = function(_interface) {
if (_interface instanceof Function) _interface = _interface.prototype;
this.prototype.extend(_interface);
};
Base.create = function() {
};
Base.getClassName = function() {
return "Base";
};
Base.isInstance = function() {
};
|
(function () {
'use strict';
angular.module('ariaNg').factory('ariaNgCommonService', ['$location', '$timeout', 'base64', 'SweetAlert', '$translate', 'ariaNgConstants', function ($location, $timeout, base64, SweetAlert, $translate, ariaNgConstants) {
return {
generateUniqueId: function () {
var sourceId = ariaNgConstants.appPrefix + '_' + Math.round(new Date().getTime() / 1000) + '_' + Math.random();
var hashedId = base64.encode(sourceId);
return hashedId;
},
showDialog: function (title, text, type) {
$timeout(function () {
SweetAlert.swal({
title: $translate.instant(title),
text: $translate.instant(text),
type: type,
confirmButtonText: $translate.instant('OK')
});
}, 100);
},
showError: function (text) {
this.showDialog('Error', text, 'error');
},
showOperationSucceeded: function (text) {
this.showDialog('Operation Succeeded', text, 'success');
},
confirm: function (title, text, type, callback, notClose, extendSettings) {
var options = {
title: $translate.instant(title),
text: $translate.instant(text, (angular.isObject(extendSettings) ? extendSettings.textParams : null)),
type: type,
showCancelButton: true,
showLoaderOnConfirm: !!notClose,
closeOnConfirm: !notClose,
confirmButtonText: $translate.instant('OK'),
cancelButtonText: $translate.instant('Cancel')
};
if (type === 'warning') {
options.confirmButtonColor = '#F39C12';
}
SweetAlert.swal(options, function (isConfirm) {
if (!isConfirm) {
return;
}
if (callback) {
callback();
}
});
},
getFileExtension: function (filePath) {
if (!filePath || filePath.lastIndexOf('.') < 0) {
return filePath;
}
return filePath.substring(filePath.lastIndexOf('.'));
},
decodePercentEncodedString: function (s) {
if (!s) {
return s;
}
var ret = '';
for (var i = 0; i < s.length; i++) {
var ch = s.charAt(i);
if (ch === '%' && i < s.length - 2) {
var code = s.substring(i + 1, i + 3);
ret += String.fromCharCode(parseInt(code, 16));
i += 2;
} else {
ret += ch;
}
}
return ret;
},
extendArray: function (sourceArray, targetArray, keyProperty) {
if (!targetArray || !sourceArray || sourceArray.length !== targetArray.length) {
return false;
}
for (var i = 0; i < targetArray.length; i++) {
if (targetArray[i][keyProperty] === sourceArray[i][keyProperty]) {
angular.extend(targetArray[i], sourceArray[i]);
} else {
return false;
}
}
return true;
},
copyObjectTo: function (from, to) {
if (!to) {
return from;
}
for (var name in from) {
if (!from.hasOwnProperty(name)) {
continue;
}
var fromValue = from[name];
var toValue = to[name];
if (angular.isObject(fromValue) || angular.isArray(fromValue)) {
to[name] = this.copyObjectTo(from[name], to[name]);
} else {
if (fromValue !== toValue) {
to[name] = fromValue;
}
}
}
return to;
},
pushArrayTo: function (array, items) {
if (!angular.isArray(array)) {
array = [];
}
if (!angular.isArray(items) || items.length < 1) {
return array;
}
for (var i = 0; i < items.length; i++) {
array.push(items[i]);
}
return array;
},
combineArray: function () {
var result = [];
for (var i = 0; i < arguments.length; i++) {
if (angular.isArray(arguments[i])) {
this.pushArrayTo(result, arguments[i]);
} else {
result.push(arguments[i]);
}
}
return result;
},
countArray: function (array, value) {
if (!angular.isArray(array) || array.length < 1) {
return 0;
}
var count = 0;
for (var i = 0; i < array.length; i++) {
count += (array[i] === value ? 1 : 0);
}
return count;
},
parseOrderType: function (value) {
var values = value.split(':');
var obj = {
type: values[0],
order: values[1],
equals: function (obj) {
if (angular.isUndefined(obj.order)) {
return this.type === obj.type;
} else {
return this.type === obj.type && this.order === obj.order;
}
},
getValue: function () {
return this.type + ':' + this.order;
}
};
Object.defineProperty(obj, 'reverse', {
get: function () {
return this.order === 'desc';
},
set: function (value) {
this.order = (value ? 'desc' : 'asc');
}
});
return obj;
},
getTimeOptions: function (timeList, withDisabled) {
var options = [];
if (withDisabled) {
options.push({
name: 'Disabled',
value: 0,
optionValue: 0
});
}
if (!angular.isArray(timeList) || timeList.length < 1) {
return options;
}
for (var i = 0; i < timeList.length; i++) {
var time = timeList[i];
var name = '';
var value = time;
if (time < 1000) {
value = time;
name = (value === 1 ? 'format.time.millisecond' : 'format.time.milliseconds');
} else if (time < 1000 * 60) {
value = time / 1000;
name = (value === 1 ? 'format.time.second' : 'format.time.seconds');
} else if (time < 1000 * 60 * 24) {
value = time / 1000 / 60;
name = (value === 1 ? 'format.time.minute' : 'format.time.minutes');
} else {
value = time / 1000 / 60 / 24;
name = (value === 1 ? 'format.time.hour' : 'format.time.hours');
}
options.push({
name: name,
value: value,
optionValue: time
});
}
return options;
}
};
}]);
}());
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Hero
*/
'use strict';
var React = require('React');
var Hero = React.createClass({
render: function() {
return (
<div className="hero">
<div className="wrap">
<div className="text">{this.props.title}</div>
<div className="minitext">
{this.props.subtitle}
</div>
</div>
{this.props.children}
</div>
);
}
});
module.exports = Hero;
|
'use strict'
/**
* adonis-cache
*
* (c) Hany El Nokaly <hany.elnokaly@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const TaggableStore = require('./TaggableStore')
class NullStore extends TaggableStore {
/**
* Retrieve an item from the cache by key.
*
* @param {string} key
* @return {Promise<mixed>}
*/
async get (key) {
return null
}
/**
* Retrieve multiple items from the cache by key.
*
* Items not found in the cache will have a null value.
*
* @param {Array<string>} keys
* @return {Promise<object>}
*/
async many (keys) {
let mappedValues = {}
for (let key of keys) {
mappedValues[key] = null
}
return mappedValues
}
/**
* Store an item in the cache for a given number of minutes.
*
* @param {string} key
* @param {mixed} value
* @param {float|int} minutes
* @return {Promise<void>}
*/
async put (key, value, minutes) {
return undefined
}
/**
* Store multiple items in the cache for a given number of minutes.
*
* @param {object} object
* @param {int} minutes
* @return {Promise<void>}
*/
async putMany (object, minutes) {
return undefined
}
/**
* Increment the value of an item in the cache.
*
* @param {string} key
* @param {mixed} value
* @return {Promise<int|boolean>}
*/
async increment (key, value = 1) {
return false
}
/**
* Decrement the value of an item in the cache.
*
* @param {string} key
* @param {mixed} value
* @return {Promise<int|boolean>}
*/
async decrement (key, value = 1) {
return false
}
/**
* Store an item in the cache indefinitely.
*
* @param {string} key
* @param {mixed} value
* @return {Promise<void>}
*/
async forever (key, value) {
return undefined
}
/**
* Remove an item from the cache.
*
* @param {string} key
* @return {Promise<boolean>}
*/
async forget (key) {
return true
}
/**
* Remove all items from the cache.
*
* @return {Promise<void>}
*/
async flush () {
return undefined
}
/**
* Get the cache key prefix.
*
* @return {string}
*/
getPrefix () {
return ''
}
}
module.exports = NullStore
|
import Vue from 'vue'
import axios from 'axios'
import store from '../store/index.js'
var ax = axios;
var axiosx = axios.create({
baseURL: 'http://127.0.0.1:8000/' + ADMIN_API_ROUTE
})
Vue.prototype.$axiosx = axiosx;
Vue.prototype.$axios = ax;
axiosx.interceptors.request.use(function (config) {
store.commit('loading', true);
// const token = cookie.get(__TOKEN_KEY__);
// if (token != null) {
// config.headers.Authorization = Bearer ${token};
// }
return config;
}, function (err) {
return Promise.reject(err);
});
ax.interceptors.request.use(function (config) {
store.commit('loading', true);
// const token = cookie.get(__TOKEN_KEY__);
// if (token != null) {
// config.headers.Authorization = Bearer ${token};
// }
return config;
}, function (err) {
return Promise.reject(err);
});
axiosx.interceptors.response.use(function (res) {
console.log(res);
store.commit('loading', false);
var snacktext = null;
if (res.data && res.data.snackText) {
var snackText = res.data.snackText
}
if (snackText) {
store.commit('snackbar', { status: true, text: snackText });
}
// Do something with response data
return res;
}, function (error) {
store.commit('loading', false);
var res = error.response;
var errors = res.data.errors.name;
if (errors && errors[0]) {
store.commit('snackbar', {
status: true,
text: errors[0]
});
}
});
ax.interceptors.response.use(function (response) {
console.log(response);
store.commit('loading', false);
// Do something with response data
return response;
}, function (response) {
store.commit('loading', false);
var res = error.response;
console.log(res);
});
export default ax;
|
const os = require('os');
const pkg = require('../package.json');
exports.packageIdentifier = () => `${pkg.name.replace('/', ':')}/${pkg.version} ${os.platform()}/${os.release()} node/${process.version.replace('v', '')}`;
|
/* global Cleave */
document.addEventListener("spree:load", function() {
if ($('#new_payment').length) {
var cardCodeCleave;
var updateCardCodeCleave = function (length) {
if (cardCodeCleave) cardCodeCleave.destroy()
cardCodeCleave = new Cleave('.cardCode', {
numericOnly: true,
blocks: [length]
})
}
updateCardCodeCleave(3)
/* eslint-disable no-new */
new Cleave('.cardNumber', {
creditCard: true,
onCreditCardTypeChanged: function (type) {
$('.ccType').val(type)
if (type === 'amex') {
updateCardCodeCleave(4)
} else {
updateCardCodeCleave(3)
}
}
})
/* eslint-disable no-new */
new Cleave('.cardExpiry', {
date: true,
datePattern: ['m', 'Y']
})
$('.payment_methods_radios').click(
function () {
$('.payment-methods').hide()
$('.payment-methods :input').prop('disabled', true)
if (this.checked) {
$('#payment_method_' + this.value + ' :input').prop('disabled', false)
$('#payment_method_' + this.value).show()
}
}
)
$('.payment_methods_radios').each(
function () {
if (this.checked) {
$('#payment_method_' + this.value + ' :input').prop('disabled', false)
$('#payment_method_' + this.value).show()
} else {
$('#payment_method_' + this.value).hide()
$('#payment_method_' + this.value + ' :input').prop('disabled', true)
}
if ($('#card_new' + this.value).is('*')) {
$('#card_new' + this.value).radioControlsVisibilityOfElement('#card_form' + this.value)
}
}
)
}
})
|
'use strict';
let canvas, engine, scene, camera;
window.addEventListener('DOMContentLoaded', () => {
// il tag canvas che visualizza l'animazione
canvas = document.getElementById('c');
// la rotella del mouse serve per fare zoom e non per scrollare la pagina
canvas.addEventListener('wheel', evt => evt.preventDefault());
// engine & scene
engine = new BABYLON.Engine(canvas, true);
scene = new BABYLON.Scene(engine);
// camera
camera = new BABYLON.ArcRotateCamera('cam',
-Math.PI/2,0.7,
15,
new BABYLON.Vector3(0,0,0),
scene);
camera.attachControl(canvas,true);
camera.wheelPrecision = 50;
camera.lowerRadiusLimit = 3;
camera.upperRadiusLimit = 13*2;
// luce
let light1 = new BABYLON.PointLight('light1',new BABYLON.Vector3(0,1,0), scene);
light1.parent = camera;
// aggiungo i vari oggetti
populateScene(scene);
// main loop
engine.runRenderLoop(()=>scene.render());
// resize event
window.addEventListener("resize", () => engine.resize());
});
function populateScene() {
const u = 0.2;
let block = BABYLON.MeshBuilder.CreateBox('box', {
size:u*0.9
}, scene);
block.material = new BABYLON.StandardMaterial('mat',scene);
block.material.diffuseColor.set(0.8,0.4,0.1);
let blocks = [block];
let m = 50;
for(let i=1; i<m*m; i++) blocks.push(block.createInstance('b'+i));
for(let i=0;i<m;i++) {
for(let j=0;j<m;j++) {
let b = blocks[i*m+j];
b.position.x = u*(j-(m-1)/2);
b.position.z = u*(i-(m-1)/2);
}
}
scene.registerBeforeRender(() => {
let t = performance.now() * 0.001;
blocks.forEach(b => {
let x = b.position.x;
let z = b.position.z;
let r = Math.sqrt(x*x+z*z);
b.position.y = 0.3*Math.cos(2*r-t*2);
});
});
}
|
// CACHE DOM ELEMENTS
var generateBtn = document.querySelector('#generate');
var passwordText = document.querySelector('#password');
// EVENT LISTENERS
generateBtn.addEventListener('click', generatePassword);
// STORE CHARACTER SETS IN ARRAY FOR EACH TYPE IN GLOBAL SCOPE
var allLowChars = 'abcdefghijklmnopqrstuvwxyz'.split('');
var allUpChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var allNums = '0123456789'.split('');
var allSpcChars = ' !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'.split('');
// // PROMPT FOR PASSWORD LENGTH & VALIDATE RESPONSE
function generatePassword() {
var numChars = prompt(
'How many characters would you like in your password (Enter a value between 8 and 128)'
);
// allow user to cancel
if (numChars === null) return;
// coerce NaN if input is a text string that cannot be coerced to a number
numChars = parseInt(numChars);
// validate input
while (isNaN(numChars) || numChars < 8 || numChars > 128) {
if (numChars === null) return;
numChars = prompt('Invalid entry, please enter a NUMBER between 8 and 128');
}
selectChars(numChars);
}
// PROMPT FOR CHARACTER TYPES TO USE
function selectChars(numChars) {
var lowCase = confirm(
'Would you like to include LOWERCASE characters in password? (Click OK for YES)'
);
var upCase = confirm(
'Would you like to include UPPERCASE characters in password? (Click OK for YES)'
);
var nums = confirm(
'Would you like to include NUMBERS in your password? (Click OK for YES)'
);
var specials = confirm(
'Would you like to include SPECIAL CHARACTERS in your password? (Click OK for YES)'
);
if (lowCase === false && upCase === false && nums === false && specials === false) {
alert('You must choose at least one type of character to use for your password');
lowCase = confirm(
'Would you like to include LOWERCASE characters in password? (Click OK for YES)'
);
upCase = confirm(
'Would you like to include UPPERCASE characters in password? (Click OK for YES)'
);
nums = confirm(
'Would you like to include NUMBERS in your password? (Click OK for YES)'
);
specials = confirm(
'Would you like to include SPECIAL CHARACTERS in your password? (Click OK for YES)'
);
}
// build object for criteria config
var criteria = {
numChars : numChars,
lowCase : lowCase,
upCase : upCase,
nums : nums,
specials : specials
};
createPassword(criteria);
}
// UNTIL PW LENGTH IS FULFILLED, LOOP OVER ALL CHARACTER TYPES & (DEPENDING ON CRITERIA BOOLEAN) CALL SUBROUTINE TO GENERATE RANDO INDEX IN CHAR SET TO PUSH TO PW ARRAY
function createPassword(criteria) {
var passwordArr = [];
while (passwordArr.length < criteria.numChars) {
if (criteria.lowCase) {
passwordArr.push(allLowChars[genRanIdx(allLowChars)]);
}
if (criteria.upCase) {
passwordArr.push(allUpChars[genRanIdx(allUpChars)]);
}
if (criteria.nums) {
passwordArr.push(allNums[genRanIdx(allNums)]);
}
if (criteria.specials) {
passwordArr.push(allSpcChars[genRanIdx(allSpcChars)]);
}
}
var passWordStr = passwordArr.join('');
writePassword(passWordStr);
}
// GENERATE RANDOM INDEX FROM CHAR SETS
function genRanIdx(charSet) {
return Math.floor(Math.random() * charSet.length);
}
// Write password to the #password input
function writePassword(password) {
passwordText.value = password;
}
|
var sha1 = {
// SHA1
add(x, y) {
return((x & 0x7FFFFFFF) + (y & 0x7FFFFFFF)) ^ (x & 0x80000000) ^ (y & 0x80000000);
},
SHA1hex(num) {
var sHEXChars = "0123456789abcdef";
var str = "";
for(var j = 7; j >= 0; j--)
str += sHEXChars.charAt((num >> (j * 4)) & 0x0F);
return str;
},
AlignSHA1(sIn) {
var nblk = ((sIn.length + 8) >> 6) + 1,
blks = new Array(nblk * 16);
for(var i = 0; i < nblk * 16; i++) blks[i] = 0;
for(i = 0; i < sIn.length; i++)
blks[i >> 2] |= sIn.charCodeAt(i) << (24 - (i & 3) * 8);
blks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);
blks[nblk * 16 - 1] = sIn.length * 8;
return blks;
},
rol(num, cnt) {
return(num << cnt) | (num >>> (32 - cnt));
},
ft(t, b, c, d) {
if(t < 20) return(b & c) | ((~b) & d);
if(t < 40) return b ^ c ^ d;
if(t < 60) return(b & c) | (b & d) | (c & d);
return b ^ c ^ d;
},
kt(t) {
return(t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
(t < 60) ? -1894007588 : -899497514;
},
SHA1(sIn) {
var x = this.AlignSHA1(sIn);
var w = new Array(80);
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
var e = -1009589776;
for(var i = 0; i < x.length; i += 16) {
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
var olde = e;
for(var j = 0; j < 80; j++) {
if(j < 16) w[j] = x[i + j];
else w[j] = this.rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
var t = this.add(this.add(this.rol(a, 5), this.ft(j, b, c, d)), this.add(this.add(e, w[j]), this.kt(j)));
e = d;
d = c;
c = this.rol(b, 30);
b = a;
a = t;
}
a = this.add(a, olda);
b = this.add(b, oldb);
c = this.add(c, oldc);
d = this.add(d, oldd);
e = this.add(e, olde);
}
var SHA1Value = this.SHA1hex(a) + this.SHA1hex(b) + this.SHA1hex(c) + this.SHA1hex(d) + this.SHA1hex(e);
return SHA1Value.toUpperCase();
},
SHA2(sIn) {
return this.SHA1(sIn).toLowerCase();
}
}
module.exports = sha1;
|
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/license
*/
CKEDITOR.lang['en']={"editor":"Rich Text Editor","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"Press ALT 0 for help","browseServer":"Browse Server","url":"URL","protocol":"Protocol","upload":"Upload","uploadSubmit":"Send it to the Server","image":"Image","flash":"Flash","form":"Form","checkbox":"Checkbox","radio":"Radio Button","textField":"Text Field","textarea":"Textarea","hiddenField":"Hidden Field","button":"Button","select":"Selection Field","imageButton":"Image Button","notSet":"<not set>","id":"Id","name":"Name","langDir":"Language Direction","langDirLtr":"Left to Right (LTR)","langDirRtl":"Right to Left (RTL)","langCode":"Language Code","longDescr":"Long Description URL","cssClass":"Stylesheet Classes","advisoryTitle":"Advisory Title","cssStyle":"Style","ok":"OK","cancel":"Cancel","close":"Close","preview":"Preview","resize":"Resize","generalTab":"General","advancedTab":"Advanced","validateNumberFailed":"This value is not a number.","confirmNewPage":"Any unsaved changes to this content will be lost. Are you sure you want to load new page?","confirmCancel":"You have changed some options. Are you sure you want to close the dialog window?","options":"Options","target":"Target","targetNew":"New Window (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Same Window (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"Left to Right (LTR)","langDirRTL":"Right to Left (RTL)","styles":"Style","cssClasses":"Stylesheet Classes","width":"Width","height":"Height","align":"Alignment","left":"Left","right":"Right","center":"Center","justify":"Justify","alignLeft":"Align Left","alignRight":"Align Right","alignCenter":"Align Center","alignTop":"Top","alignMiddle":"Middle","alignBottom":"Bottom","alignNone":"None","invalidValue":"Invalid value.","invalidHeight":"Height must be a number.","invalidWidth":"Width must be a number.","invalidLength":"Value specified for the \"%1\" field must be a positive number with or without a valid measurement unit (%2).","invalidCssLength":"Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, unavailable</span>","keyboard":{"8":"Backspace","13":"Enter","16":"Shift","17":"Ctrl","18":"Alt","32":"Space","35":"End","36":"Home","46":"Delete","112":"F1","113":"F2","114":"F3","115":"F4","116":"F5","117":"F6","118":"F7","119":"F8","120":"F9","121":"F10","122":"F11","123":"F12","124":"F13","125":"F14","126":"F15","127":"F16","128":"F17","129":"F18","130":"F19","131":"F20","132":"F21","133":"F22","134":"F23","135":"F24","224":"Command"},"keyboardShortcut":"Keyboard shortcut","optionDefault":"Default"},"about":{"copy":"Copyright © $1. All rights reserved.","dlgTitle":"About CKEditor 4","moreInfo":"For licensing information please visit our web site:"},"basicstyles":{"bold":"Bold","italic":"Italic","strike":"Strikethrough","subscript":"Subscript","superscript":"Superscript","underline":"Underline"},"bidi":{"ltr":"Text direction from left to right","rtl":"Text direction from right to left"},"blockquote":{"toolbar":"Block Quote"},"notification":{"closed":"Notification closed."},"toolbar":{"toolbarCollapse":"Collapse Toolbar","toolbarExpand":"Expand Toolbar","toolbarGroups":{"document":"Document","clipboard":"Clipboard/Undo","editing":"Editing","forms":"Forms","basicstyles":"Basic Styles","paragraph":"Paragraph","links":"Links","insert":"Insert","styles":"Styles","colors":"Colors","tools":"Tools"},"toolbars":"Editor toolbars"},"clipboard":{"copy":"Copy","copyError":"Your browser security settings don't permit the editor to automatically execute copying operations. Please use the keyboard for that (Ctrl/Cmd+C).","cut":"Cut","cutError":"Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl/Cmd+X).","paste":"Paste","pasteNotification":"Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.","pasteArea":"Paste Area","pasteMsg":"Paste your content inside the area below and press OK."},"colorbutton":{"auto":"Automatic","bgColorTitle":"Background Color","colors":{"000":"Black","800000":"Maroon","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Dark Gray","B22222":"Fire Brick","A52A2A":"Brown","DAA520":"Golden Rod","006400":"Dark Green","40E0D0":"Turquoise","0000CD":"Medium Blue","800080":"Purple","808080":"Gray","F00":"Red","FF8C00":"Dark Orange","FFD700":"Gold","008000":"Green","0FF":"Cyan","00F":"Blue","EE82EE":"Violet","A9A9A9":"Dim Gray","FFA07A":"Light Salmon","FFA500":"Orange","FFFF00":"Yellow","00FF00":"Lime","AFEEEE":"Pale Turquoise","ADD8E6":"Light Blue","DDA0DD":"Plum","D3D3D3":"Light Grey","FFF0F5":"Lavender Blush","FAEBD7":"Antique White","FFFFE0":"Light Yellow","F0FFF0":"Honeydew","F0FFFF":"Azure","F0F8FF":"Alice Blue","E6E6FA":"Lavender","FFF":"White","1ABC9C":"Strong Cyan","2ECC71":"Emerald","3498DB":"Bright Blue","9B59B6":"Amethyst","4E5F70":"Grayish Blue","F1C40F":"Vivid Yellow","16A085":"Dark Cyan","27AE60":"Dark Emerald","2980B9":"Strong Blue","8E44AD":"Dark Violet","2C3E50":"Desaturated Blue","F39C12":"Orange","E67E22":"Carrot","E74C3C":"Pale Red","ECF0F1":"Bright Silver","95A5A6":"Light Grayish Cyan","DDD":"Light Gray","D35400":"Pumpkin","C0392B":"Strong Red","BDC3C7":"Silver","7F8C8D":"Grayish Cyan","999":"Dark Gray"},"more":"More Colors...","panelTitle":"Colors","textColorTitle":"Text Color"},"colordialog":{"clear":"Clear","highlight":"Highlight","options":"Color Options","selected":"Selected Color","title":"Select color"},"templates":{"button":"Templates","emptyListMsg":"(No templates defined)","insertOption":"Replace actual contents","options":"Template Options","selectPromptMsg":"Please select the template to open in the editor","title":"Content Templates"},"contextmenu":{"options":"Context Menu Options"},"copyformatting":{"label":"Copy Formatting","notification":{"copied":"Formatting copied","applied":"Formatting applied","canceled":"Formatting canceled","failed":"Formatting failed. You cannot apply styles without copying them first."}},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Advisory Title","cssClassInputLabel":"Stylesheet Classes","edit":"Edit Div","inlineStyleInputLabel":"Inline Style","langDirLTRLabel":"Left to Right (LTR)","langDirLabel":"Language Direction","langDirRTLLabel":"Right to Left (RTL)","languageCodeInputLabel":" Language Code","remove":"Remove Div","styleSelectLabel":"Style","title":"Create Div Container","toolbar":"Create Div Container"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"exportpdf":{"documentReady":"Document is ready!","error":"Error occurred.","processingDocument":"Processing PDF document...","toolbar":"Export to PDF"},"filetools":{"loadError":"Error occurred during file read.","networkError":"Network error occurred during file upload.","httpError404":"HTTP error occurred during file upload (404: File not found).","httpError403":"HTTP error occurred during file upload (403: Forbidden).","httpError":"HTTP error occurred during file upload (error status: %1).","noUrlError":"Upload URL is not defined.","responseError":"Incorrect server response."},"find":{"find":"Find","findOptions":"Find Options","findWhat":"Find what:","matchCase":"Match case","matchCyclic":"Match cyclic","matchWord":"Match whole word","notFoundMsg":"The specified text was not found.","replace":"Replace","replaceAll":"Replace All","replaceSuccessMsg":"%1 occurrence(s) replaced.","replaceWith":"Replace with:","title":"Find and Replace"},"fakeobjects":{"anchor":"Anchor","flash":"Flash Animation","hiddenfield":"Hidden Field","iframe":"IFrame","unknown":"Unknown Object"},"flash":{"access":"Script Access","accessAlways":"Always","accessNever":"Never","accessSameDomain":"Same domain","alignAbsBottom":"Abs Bottom","alignAbsMiddle":"Abs Middle","alignBaseline":"Baseline","alignTextTop":"Text Top","bgcolor":"Background color","chkFull":"Allow Fullscreen","chkLoop":"Loop","chkMenu":"Enable Flash Menu","chkPlay":"Auto Play","flashvars":"Variables for Flash","hSpace":"HSpace","properties":"Flash Properties","propertiesTab":"Properties","quality":"Quality","qualityAutoHigh":"Auto High","qualityAutoLow":"Auto Low","qualityBest":"Best","qualityHigh":"High","qualityLow":"Low","qualityMedium":"Medium","scale":"Scale","scaleAll":"Show all","scaleFit":"Exact Fit","scaleNoBorder":"No Border","title":"Flash Properties","vSpace":"VSpace","validateHSpace":"HSpace must be a number.","validateSrc":"URL must not be empty.","validateVSpace":"VSpace must be a number.","windowMode":"Window mode","windowModeOpaque":"Opaque","windowModeTransparent":"Transparent","windowModeWindow":"Window"},"font":{"fontSize":{"label":"Size","voiceLabel":"Font Size","panelTitle":"Font Size"},"label":"Font","panelTitle":"Font Name","voiceLabel":"Font"},"forms":{"button":{"title":"Button Properties","text":"Text (Value)","type":"Type","typeBtn":"Button","typeSbm":"Submit","typeRst":"Reset"},"checkboxAndRadio":{"checkboxTitle":"Checkbox Properties","radioTitle":"Radio Button Properties","value":"Value","selected":"Selected","required":"Required"},"form":{"title":"Form Properties","menu":"Form Properties","action":"Action","method":"Method","encoding":"Encoding"},"hidden":{"title":"Hidden Field Properties","name":"Name","value":"Value"},"select":{"title":"Selection Field Properties","selectInfo":"Select Info","opAvail":"Available Options","value":"Value","size":"Size","lines":"lines","chkMulti":"Allow multiple selections","required":"Required","opText":"Text","opValue":"Value","btnAdd":"Add","btnModify":"Modify","btnUp":"Up","btnDown":"Down","btnSetValue":"Set as selected value","btnDelete":"Delete"},"textarea":{"title":"Textarea Properties","cols":"Columns","rows":"Rows"},"textfield":{"title":"Text Field Properties","name":"Name","value":"Value","charWidth":"Character Width","maxChars":"Maximum Characters","required":"Required","type":"Type","typeText":"Text","typePass":"Password","typeEmail":"Email","typeSearch":"Search","typeTel":"Telephone Number","typeUrl":"URL"}},"format":{"label":"Format","panelTitle":"Paragraph Format","tag_address":"Address","tag_div":"Normal (DIV)","tag_h1":"Heading 1","tag_h2":"Heading 2","tag_h3":"Heading 3","tag_h4":"Heading 4","tag_h5":"Heading 5","tag_h6":"Heading 6","tag_p":"Normal","tag_pre":"Formatted"},"horizontalrule":{"toolbar":"Insert Horizontal Line"},"iframe":{"border":"Show frame border","noUrl":"Please type the iframe URL","scrolling":"Enable scrollbars","title":"IFrame Properties","toolbar":"IFrame","tabindex":"Remove from tabindex"},"image":{"alt":"Alternative Text","border":"Border","btnUpload":"Send it to the Server","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"HSpace","img2Button":"Do you want to transform the selected image on a image button?","infoTab":"Image Info","linkTab":"Link","lockRatio":"Lock Ratio","menu":"Image Properties","resetSize":"Reset Size","title":"Image Properties","titleButton":"Image Button Properties","upload":"Upload","urlMissing":"Image source URL is missing.","vSpace":"VSpace","validateBorder":"Border must be a whole number.","validateHSpace":"HSpace must be a whole number.","validateVSpace":"VSpace must be a whole number."},"indent":{"indent":"Increase Indent","outdent":"Decrease Indent"},"smiley":{"options":"Smiley Options","title":"Insert a Smiley","toolbar":"Smiley"},"language":{"button":"Set language","remove":"Remove language"},"link":{"acccessKey":"Access Key","advanced":"Advanced","advisoryContentType":"Advisory Content Type","advisoryTitle":"Advisory Title","anchor":{"toolbar":"Anchor","menu":"Edit Anchor","title":"Anchor Properties","name":"Anchor Name","errorName":"Please type the anchor name","remove":"Remove Anchor"},"anchorId":"By Element Id","anchorName":"By Anchor Name","charset":"Linked Resource Charset","cssClasses":"Stylesheet Classes","download":"Force Download","displayText":"Display Text","emailAddress":"E-Mail Address","emailBody":"Message Body","emailSubject":"Message Subject","id":"Id","info":"Link Info","langCode":"Language Code","langDir":"Language Direction","langDirLTR":"Left to Right (LTR)","langDirRTL":"Right to Left (RTL)","menu":"Edit Link","name":"Name","noAnchors":"(No anchors available in the document)","noEmail":"Please type the e-mail address","noUrl":"Please type the link URL","noTel":"Please type the phone number","other":"<other>","phoneNumber":"Phone number","popupDependent":"Dependent (Netscape)","popupFeatures":"Popup Window Features","popupFullScreen":"Full Screen (IE)","popupLeft":"Left Position","popupLocationBar":"Location Bar","popupMenuBar":"Menu Bar","popupResizable":"Resizable","popupScrollBars":"Scroll Bars","popupStatusBar":"Status Bar","popupToolbar":"Toolbar","popupTop":"Top Position","rel":"Relationship","selectAnchor":"Select an Anchor","styles":"Style","tabIndex":"Tab Index","target":"Target","targetFrame":"<frame>","targetFrameName":"Target Frame Name","targetPopup":"<popup window>","targetPopupName":"Popup Window Name","title":"Link","toAnchor":"Link to anchor in the text","toEmail":"E-mail","toUrl":"URL","toPhone":"Phone","toolbar":"Link","type":"Link Type","unlink":"Unlink","upload":"Upload"},"list":{"bulletedlist":"Insert/Remove Bulleted List","numberedlist":"Insert/Remove Numbered List"},"liststyle":{"bulletedTitle":"Bulleted List Properties","circle":"Circle","decimal":"Decimal (1, 2, 3, etc.)","disc":"Disc","lowerAlpha":"Lower Alpha (a, b, c, d, e, etc.)","lowerRoman":"Lower Roman (i, ii, iii, iv, v, etc.)","none":"None","notset":"<not set>","numberedTitle":"Numbered List Properties","square":"Square","start":"Start","type":"Type","upperAlpha":"Upper Alpha (A, B, C, D, E, etc.)","upperRoman":"Upper Roman (I, II, III, IV, V, etc.)","validateStartNumber":"List start number must be a whole number."},"magicline":{"title":"Insert paragraph here"},"maximize":{"maximize":"Maximize","minimize":"Minimize"},"newpage":{"toolbar":"New Page"},"pagebreak":{"alt":"Page Break","toolbar":"Insert Page Break for Printing"},"pastetext":{"button":"Paste as plain text","pasteNotification":"Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.","title":"Paste as Plain Text"},"pastefromword":{"confirmCleanup":"The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?","error":"It was not possible to clean up the pasted data due to an internal error","title":"Paste from Word","toolbar":"Paste from Word"},"preview":{"preview":"Preview"},"print":{"toolbar":"Print"},"removeformat":{"toolbar":"Remove Format"},"save":{"toolbar":"Save"},"selectall":{"toolbar":"Select All"},"showblocks":{"toolbar":"Show Blocks"},"sourcearea":{"toolbar":"Source"},"specialchar":{"options":"Special Character Options","title":"Select Special Character","toolbar":"Insert Special Character"},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"stylescombo":{"label":"Styles","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"Border size","caption":"Caption","cell":{"menu":"Cell","insertBefore":"Insert Cell Before","insertAfter":"Insert Cell After","deleteCell":"Delete Cells","merge":"Merge Cells","mergeRight":"Merge Right","mergeDown":"Merge Down","splitHorizontal":"Split Cell Horizontally","splitVertical":"Split Cell Vertically","title":"Cell Properties","cellType":"Cell Type","rowSpan":"Rows Span","colSpan":"Columns Span","wordWrap":"Word Wrap","hAlign":"Horizontal Alignment","vAlign":"Vertical Alignment","alignBaseline":"Baseline","bgColor":"Background Color","borderColor":"Border Color","data":"Data","header":"Header","yes":"Yes","no":"No","invalidWidth":"Cell width must be a number.","invalidHeight":"Cell height must be a number.","invalidRowSpan":"Rows span must be a whole number.","invalidColSpan":"Columns span must be a whole number.","chooseColor":"Choose"},"cellPad":"Cell padding","cellSpace":"Cell spacing","column":{"menu":"Column","insertBefore":"Insert Column Before","insertAfter":"Insert Column After","deleteColumn":"Delete Columns"},"columns":"Columns","deleteTable":"Delete Table","headers":"Headers","headersBoth":"Both","headersColumn":"First column","headersNone":"None","headersRow":"First Row","heightUnit":"height unit","invalidBorder":"Border size must be a number.","invalidCellPadding":"Cell padding must be a positive number.","invalidCellSpacing":"Cell spacing must be a positive number.","invalidCols":"Number of columns must be a number greater than 0.","invalidHeight":"Table height must be a number.","invalidRows":"Number of rows must be a number greater than 0.","invalidWidth":"Table width must be a number.","menu":"Table Properties","row":{"menu":"Row","insertBefore":"Insert Row Before","insertAfter":"Insert Row After","deleteRow":"Delete Rows"},"rows":"Rows","summary":"Summary","title":"Table Properties","toolbar":"Table","widthPc":"percent","widthPx":"pixels","widthUnit":"width unit"},"undo":{"redo":"Redo","undo":"Undo"},"widget":{"move":"Click and drag to move","label":"%1 widget"},"uploadwidget":{"abort":"Upload aborted by the user.","doneOne":"File successfully uploaded.","doneMany":"Successfully uploaded %1 files.","uploadOne":"Uploading file ({percentage}%)...","uploadMany":"Uploading files, {current} of {max} done ({percentage}%)..."},"youtube":{"button":"Embed YouTube Video","title":"Embed YouTube Video","txtEmbed":"Paste Embed Code Here","txtUrl":"Paste YouTube Video URL","txtWidth":"Width","txtHeight":"Height","chkRelated":"Show suggested videos at the video's end","txtStartAt":"Start at (ss or mm:ss or hh:mm:ss)","chkPrivacy":"Enable privacy-enhanced mode","chkOlderCode":"Use old embed code","chkAutoplay":"Autoplay","chkControls":"Show player controls","noCode":"You must input an embed code or URL","invalidEmbed":"The embed code you've entered doesn't appear to be valid","invalidUrl":"The URL you've entered doesn't appear to be valid","or":"or","noWidth":"You must inform the width","invalidWidth":"Inform a valid width","noHeight":"You must inform the height","invalidHeight":"Inform a valid height","invalidTime":"Inform a valid start time","txtResponsive":"Make Responsive (ignore width and height, fit to width)","txtNoEmbed":"Video image and link only"},"video":{"button":"Video","title":"Video properties","emptySrc":"URL must not be empty.","controls":"Enable controls","mutedLoopingAutoplay":"Muted looping autoplay","preview":"Preview","invalidSrc":"URL is invalid or video is not playable."}};
|
// Copyright 2015 The Oppia 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 node module that automate tasks.
*/
var fs = require('fs');
var yargs = require('yargs');
var argv = yargs
.usage('Usage: $0 <command> [<options>]')
.example('$0 build --minify=True')
.command('build', 'generate optimimized third party library for production',
function(yargs) {
argv = yargs
.usage('Usage: $0 build [--minify]')
.option('minify', {
describe: 'Whether to minify third-party dependencies'
}).argv;
})
.command('start_devserver', 'start GAE development server',
function(yargs) {
argv = yargs
.usage('Usage: $0 start_devserver [--gae_devserver_path]' +
'[--clear_datastore] [--enable_sendmail]')
.option('gae_devserver_path', {
describe: 'A path to app engine'
})
.option('enable_sendmail', {
describe: 'Whether to send emails'
})
.option('clear_datastore', {
describe: 'Whether to clear all data storage'
})
.demand(['gae_devserver_path'])
.argv;
}).argv;
var concat = require('gulp-concat');
var gulp = require('gulp');
var gulpStartGae = require('./scripts/gulp-start-gae-devserver');
var gulpUtil = require('gulp-util');
var manifest = require('./manifest.json');
var cleanCss = require('gulp-clean-css');
var path = require('path');
var sourcemaps = require('gulp-sourcemaps');
var minify = require('gulp-minify');
var gaeDevserverPath = argv.gae_devserver_path;
var params = {
admin_host: '0.0.0.0',
admin_port: 8000,
host: '0.0.0.0',
port: 8181,
skip_sdk_update_check: true
};
if (argv.clear_datastore) {
params.clear_datastore = true;
}
if (argv.enable_sendmail) {
params.enable_sendmail = argv.enable_sendmail;
}
// Check if path to the file to be minified and/or concatenated does exist.
// If not, raise a warning and terminate the program.
// This will help to check spelling errors in manifest.json.
var requireFilesExist = function(filePaths) {
filePaths.forEach(function(filePath) {
if (!fs.lstatSync(filePath).isFile()) {
console.log(filePath + ' is not a valid filepath, check spelling');
process.exit();
}
});
};
// Check if there are enough commands/actions/tasks to run gulp.
var checkCommands = function(yargs, argv, numRequired) {
if (argv._.length < numRequired) {
// Display help(usage) message.
console.log(yargs.help());
// Stop gulp and exit.
process.exit();
}
};
// There should atleast be minimum of one defined task.
checkCommands(yargs, argv, 1);
var isMinificationNeeded = (argv.minify == 'True');
var frontendDependencies = manifest.dependencies.frontend;
var cssFilePaths = [];
var jsFilePaths = [];
var fontFolderPaths = [];
var cssBackgroundFilepaths = [];
var generatedTargetDir = path.join(
'third_party', 'generated',
isMinificationNeeded ? 'prod' : 'dev');
var generatedCssTargetDir = path.join(generatedTargetDir, 'css');
var generatedJsTargetDir = path.join(generatedTargetDir, 'js');
gulp.task('collectDependencyFilepaths', function() {
for (var dependencyId in frontendDependencies) {
var dependency = frontendDependencies[dependencyId];
var dependencyDir = dependency.targetDirPrefix + dependency.version;
if (dependency.hasOwnProperty('bundle')) {
if (dependency.bundle.hasOwnProperty('css')) {
dependency.bundle.css.forEach(function(cssFiles) {
cssFilePaths.push(path.join(
'third_party', 'static', dependencyDir, cssFiles));
});
}
if (dependency.bundle.hasOwnProperty('js')) {
dependency.bundle.js.forEach(function(jsFiles) {
jsFilePaths.push(path.join(
'third_party', 'static', dependencyDir, jsFiles));
});
}
if (dependency.bundle.hasOwnProperty('fontsPath')) {
var fontPrefix = '*.{eot,woff2,ttf,woff,eof,svg}';
fontFolderPaths.push(path.join('third_party', 'static', dependencyDir,
dependency.bundle.fontsPath, fontPrefix));
}
if (dependency.bundle.hasOwnProperty('cssBackgroundImage')) {
dependency.bundle.cssBackgroundImage.forEach(function(imagePath) {
cssBackgroundFilepaths.push(path.join(
'third_party', 'static', dependencyDir, imagePath));
});
}
}
}
});
gulp.task('generateCss', function() {
requireFilesExist(cssFilePaths);
gulp.src(cssFilePaths)
.pipe(isMinificationNeeded ? cleanCss({}) : gulpUtil.noop())
.pipe(concat('third_party.css'))
.pipe(gulp.dest(generatedCssTargetDir));
});
gulp.task('generateJs', function() {
requireFilesExist(jsFilePaths);
gulp.src(jsFilePaths)
.pipe(sourcemaps.init())
.pipe(concat('third_party.js'))
.pipe(isMinificationNeeded ? minify({
ext: {
src: '.js',
min: '.min.js'
}
}) : gulpUtil.noop())
// This maps a combined/minified file back to an unbuilt state by holding
// information about original files. When you query a certain line and
// column number in your generated JavaScript, you can do a lookup in the
// source map which returns the original location.
// http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
.pipe(sourcemaps.write())
.pipe(gulp.dest(generatedJsTargetDir));
});
// This task is used to copy all fonts which are used by
// Bootstrap and font-Awesome to one folder
gulp.task('copyFonts', function() {
gulp.src(fontFolderPaths)
.pipe(gulp.dest(path.join(
'third_party', 'generated',
isMinificationNeeded ? 'prod' : 'dev', 'fonts')));
});
// This is a task which copies background image used by css.
// TODO(Barnabas) find a way of removing this task. It is a bit of a hack,
// because it depends on the relative location of the CSS background images
// of a third-party library with respect to the CSS file that uses them.
// The currently-affected libraries include select2.css.
gulp.task('copyCssBackgroundImages', function() {
requireFilesExist(cssBackgroundFilepaths);
gulp.src(cssBackgroundFilepaths)
.pipe(gulp.dest(generatedCssTargetDir));
});
gulp.task('gulpStartGae', function() {
gulp.src('app.yaml')
.pipe(gulpStartGae(gaeDevserverPath, [], params));
});
// This takes all functions that are required for the build
// e.g css, Js and Images
gulp.task('build', [
'collectDependencyFilepaths', 'generateCss', 'copyFonts',
'copyCssBackgroundImages', 'generateJs']);
gulp.slurped = false;
gulp.task('watch', function() {
if (!gulp.slurped) {
gulp.watch('gulpfile.js', ['build']);
gulp.watch(cssFilePaths, ['generateCss']);
gulp.watch(jsFilePaths, ['generateJs']);
gulp.watch('manifest.json', ['build']);
gulp.slurped = true;
}
});
// This task starts google app engine development server.
// TODO(Barnabas Makonda): check if files are already generated and if so
// do not build.
gulp.task('start_devserver', ['build', 'gulpStartGae', 'watch']);
|
define("maq-metadata-dojo/dojox/grid/TreeGridCreateTool", [
"dojo/_base/declare",
"davinci/ve/tools/CreateTool",
"davinci/ve/widget",
"davinci/commands/CompoundCommand",
"davinci/ve/commands/AddCommand",
"davinci/ve/commands/MoveCommand",
"davinci/ve/commands/ResizeCommand",
"davinci/ve/commands/StyleCommand",
"dojo/promise/all"
], function(
declare,
CreateTool,
Widget,
CompoundCommand,
AddCommand,
MoveCommand,
ResizeCommand,
StyleCommand,
all
) {
return declare(CreateTool, {
constructor: function(data) {
this._resizable = "both";
},
_create: function(args) {
if(this._data.length !== 2){
return;
}
var storeData = this._data[0],
dataGridData = this._data[1];
all([
this._context.loadRequires(storeData.type,true), /*|| !this._context.loadRequires(modelData.type,true)*/
this._context.loadRequires(dataGridData.type,true)
]).then(function() {
var storeId = Widget.getUniqueObjectId(storeData.type, this._context.getDocument());
if(!storeData.properties){
storeData.properties = {};
}
storeData.properties.jsId = storeId;
storeData.properties.id = storeId;
storeData.context = this._context;
var data = storeData.properties.data;
var items = data.items;
// Kludge to workaround lack of support for frames in dojo's ItemFileReadStore
// Replaces objects and arrays in metadata that were created with the top context with ones created in the frame context
var copyUsingFrameObject = dojo.hitch(this, function (items) {
var win = this._context.getGlobal();
var copyOfItems = win.eval("[]");
for (var i = 0; i < items.length; i++) {
var item = items[i];
var object = win.eval("new Object()");
var copy = this._context.getDojo().mixin(object, item);
copyOfItems.push(copy);
if (copy.children) {
copy.children = copyUsingFrameObject(copy.children);
}
}
return copyOfItems;
});
data.items = copyUsingFrameObject(items);
var dataGridId = Widget.getUniqueObjectId(dataGridData.type, this._context.getDocument());
if(!dataGridData.properties){
dataGridData.properties = { };
}
// <hack> Added to make new ve code happy, Widget.createWidget requires id in properties or context on data, but id didn't work when dragging second tree onto canvas so switched to context:
// node.id= (data.properties && data.properties.id) || data.context.getUniqueID(srcElement);
//treeData.properties.id = treeId;
dataGridData.context = this._context;
// </hack>
var store,
dataGrid;
var dj = this._context.getDojo();
dojo.withDoc(this._context.getDocument(), function(){
store = Widget.createWidget(storeData);
dataGridData.properties.store = dj.getObject(storeId);
dataGrid = Widget.createWidget(dataGridData);
});
if(!store || !dataGrid){
return;
}
var command = new CompoundCommand();
var index = args.index;
command.add(new AddCommand(store, args.parent, index));
index = (index !== undefined && index >= 0 ? index + 1 : undefined);
command.add(new AddCommand(dataGrid, args.parent, index));
if(args.position){
var absoluteWidgetsZindex = this._context.getPreference('absoluteWidgetsZindex');
command.add(new StyleCommand(dataGrid, [{position:'absolute'},{'z-index':absoluteWidgetsZindex}]));
command.add(new MoveCommand(dataGrid, args.position.x, args.position.y));
}
args.size = this._getInitialSize(dataGrid, args);
if(args.size){
command.add(new ResizeCommand(dataGrid, args.size.w, args.size.h));
}
this._context.getCommandStack().execute(command);
this._select(dataGrid);
}.bind(this));
}
});
});
|
cmsApp.controller('alterarPostCtrl', ['$scope', '$http', 'Upload', '$timeout', function($scope, $http, Upload, $timeout){
$scope.processandoSalvar = false;
//ALTERAR/////////////////////////////
$scope.tinymceOptions = tinymceOptions;
$scope.mostrarForm = false;
$scope.removerImagem = 0;
$scope.removerArquivo = 0;
$scope.stringToDate = stringToDate;
$scope.alterar = function (file, arquivo){
$scope.progress = 0;
$scope.processandoSalvar = true;
$scope.mensagemSalvar = "";
if(file==null && arquivo==null){
//console.log($scope.post);
$http.post("cms/alterar-post/"+$scope.id, {
'post': $scope.post,
'removerImagem': $scope.removerImagem,
'removerArquivo': $scope.removerArquivo,
'integrante_post': $scope.integrante_post,
}).success(function (data){
//console.log(data);
$scope.processandoSalvar = false;
$scope.mensagemSalvar = "Gravado com Sucesso";
$scope.removerImagem = false;
}).error(function(data){
//console.log(data);
$scope.mensagemSalvar = "Ocorreu um erro: "+data;
$scope.processandoSalvar = false;
});
}else{
var data1 = {
post: $scope.post,
'removerImagem': $scope.removerImagem,
'removerArquivo': $scope.removerArquivo,
'integrante_post': $scope.integrante_post,
};
if(file!=null){
data1.file = file;
}
if(arquivo!=null){
data1.arquivo = arquivo;
}
Upload.upload({
url: 'cms/alterar-post/'+$scope.id,
data: data1
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
$scope.picFile = null;//limpa o file
//$scope.fileArquivo = null;//limpa o file
$scope.mensagemSalvar = "Gravado com sucesso!";
$scope.removerImagem = false;
$scope.imagemBD = '/imagens/posts/'+response.data;
$scope.processandoSalvar = false;
}, function (response) {
if (response.status > 0){
$scope.errorMsg = response.status + ': ' + response.data;
$scope.processandoSalvar = false;
}
}, function (evt) {
//console.log(evt);
// Math.min is to fix IE which reports 200% sometimes
$scope.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
};
$scope.limparImagem = function(){
$scope.picFile = null;
$scope.imagemBD = null;
$scope.removerImagem = 1;
};
$scope.limparArquivo= function(){
$scope.fileArquivo = null;
$scope.arquivoBD = null;
$scope.removerArquivo = 1;
};
$scope.carregaImagem = function(img, arquivo) {
if(img!=''){
$scope.imagemBD = 'imagens/posts/xs-'+img;
//console.log($scope.imagemBD);
}
if(arquivo!=''){
$scope.arquivoBD = arquivo;
//console.log($scope.baseBD);
}
};
$scope.validar = function(valor) {
if(valor===undefined && $scope.form.$dirty){
return "campo-obrigatorio";
}
return "";
};
/////////////////////////////////
}]);
|
zipdata({"4730921":[23,"豊田市","高丘新町"],"4730903":[23,"豊田市","西田町"],"4730915":[23,"豊田市","若林東町中外根"],"4730939":[23,"豊田市","堤本町"],"4730905":[23,"豊田市","住吉町"],"4730937":[23,"豊田市","西岡町星ケ丘"],"4738501":[23,"豊田市","高丘新町","天王1"],"4730938":[23,"豊田市","本田町"],"4730918":[23,"豊田市","高美町"],"4730913":[23,"豊田市","竹元町"],"4730912":[23,"豊田市","広田町"],"4730928":[23,"豊田市","生駒町"],"4730908":[23,"豊田市","宝町"],"4730927":[23,"豊田市","中田町"],"4730917":[23,"豊田市","若林西町"],"4730907":[23,"豊田市","竜神町"],"4730925":[23,"豊田市","駒場町"],"4730934":[23,"豊田市","前林町"],"4730931":[23,"豊田市","上丘町"],"4730923":[23,"豊田市","中根町"],"4730914":[23,"豊田市","若林東町"],"4730904":[23,"豊田市","中町"],"4730901":[23,"豊田市","御幸本町"],"4730902":[23,"豊田市","大林町"],"4730936":[23,"豊田市","西岡町"],"4730932":[23,"豊田市","堤町"],"4730911":[23,"豊田市","本町"],"4730916":[23,"豊田市","吉原町"],"4730926":[23,"豊田市","駒新町"],"4730906":[23,"豊田市","竹町"],"4730933":[23,"豊田市","高岡町"],"4738511":[23,"豊田市","吉原町","平子26"],"4730922":[23,"豊田市","高岡本町"],"4730924":[23,"豊田市","花園町"],"4730935":[23,"豊田市","大島町"]}
);
|
/** @format */
/**
* External dependencies
*/
import React from 'react';
export default function ScreenReaderText( { children } ) {
return <span className="screen-reader-text">{ children }</span>;
}
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[26],{"02t3":function(e,t,n){"use strict";n.r(t);var i=n("ofXK"),a=n("tyNb"),r=n("wd/R"),o=n("PSD3"),s=n.n(o),l=n("fXoL"),d=n("2Rin"),c=n("H+bZ"),p=n("dbUT"),g=n("3Pt+");function m(e,t){if(1&e){var n=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"a",11),l["\u0275\u0275listener"]("keyup.enter",(function(){return l["\u0275\u0275restoreView"](n),l["\u0275\u0275nextContext"](3),l["\u0275\u0275reference"](1).previous()}))("click",(function(){return l["\u0275\u0275restoreView"](n),l["\u0275\u0275nextContext"](3),l["\u0275\u0275reference"](1).previous()})),l["\u0275\u0275text"](1),l["\u0275\u0275elementStart"](2,"span",12),l["\u0275\u0275text"](3),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){var i=l["\u0275\u0275nextContext"](3);l["\u0275\u0275attribute"]("aria-label",i.previousLabel+" "+i.screenReaderPageLabel),l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",i.previousLabel," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](i.screenReaderPageLabel)}}function u(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementStart"](2,"span",12),l["\u0275\u0275text"](3),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){var n=l["\u0275\u0275nextContext"](3);l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",n.previousLabel," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](n.screenReaderPageLabel)}}function h(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"li",8),l["\u0275\u0275template"](1,m,4,3,"a",9),l["\u0275\u0275template"](2,u,4,2,"span",10),l["\u0275\u0275elementEnd"]()),2&e){l["\u0275\u0275nextContext"](2);var n=l["\u0275\u0275reference"](1);l["\u0275\u0275classProp"]("disabled",n.isFirstPage()),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",1<n.getCurrent()),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",n.isFirstPage())}}function f(e,t){if(1&e){var n=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"a",11),l["\u0275\u0275listener"]("keyup.enter",(function(){l["\u0275\u0275restoreView"](n);var e=l["\u0275\u0275nextContext"]().$implicit;return l["\u0275\u0275nextContext"](2),l["\u0275\u0275reference"](1).setCurrent(e.value)}))("click",(function(){l["\u0275\u0275restoreView"](n);var e=l["\u0275\u0275nextContext"]().$implicit;return l["\u0275\u0275nextContext"](2),l["\u0275\u0275reference"](1).setCurrent(e.value)})),l["\u0275\u0275elementStart"](1,"span",12),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"span"),l["\u0275\u0275text"](4),l["\u0275\u0275pipe"](5,"number"),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){var i=l["\u0275\u0275nextContext"]().$implicit,a=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",a.screenReaderPageLabel," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"]("..."===i.label?i.label:l["\u0275\u0275pipeBind2"](5,2,i.label,""))}}function v(e,t){if(1&e&&(l["\u0275\u0275elementContainerStart"](0),l["\u0275\u0275elementStart"](1,"span",12),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"span"),l["\u0275\u0275text"](4),l["\u0275\u0275pipe"](5,"number"),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementContainerEnd"]()),2&e){var n=l["\u0275\u0275nextContext"]().$implicit,i=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",i.screenReaderCurrentLabel," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"]("..."===n.label?n.label:l["\u0275\u0275pipeBind2"](5,2,n.label,""))}}function x(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"li"),l["\u0275\u0275template"](1,f,6,5,"a",9),l["\u0275\u0275template"](2,v,6,5,"ng-container",10),l["\u0275\u0275elementEnd"]()),2&e){var n=t.$implicit;l["\u0275\u0275nextContext"](2);var i=l["\u0275\u0275reference"](1);l["\u0275\u0275classProp"]("current",i.getCurrent()===n.value)("ellipsis","..."===n.label),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",i.getCurrent()!==n.value),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",i.getCurrent()===n.value)}}function C(e,t){if(1&e){var n=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"a",11),l["\u0275\u0275listener"]("keyup.enter",(function(){return l["\u0275\u0275restoreView"](n),l["\u0275\u0275nextContext"](3),l["\u0275\u0275reference"](1).next()}))("click",(function(){return l["\u0275\u0275restoreView"](n),l["\u0275\u0275nextContext"](3),l["\u0275\u0275reference"](1).next()})),l["\u0275\u0275text"](1),l["\u0275\u0275elementStart"](2,"span",12),l["\u0275\u0275text"](3),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){var i=l["\u0275\u0275nextContext"](3);l["\u0275\u0275attribute"]("aria-label",i.nextLabel+" "+i.screenReaderPageLabel),l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",i.nextLabel," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](i.screenReaderPageLabel)}}function b(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementStart"](2,"span",12),l["\u0275\u0275text"](3),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){var n=l["\u0275\u0275nextContext"](3);l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",n.nextLabel," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](n.screenReaderPageLabel)}}function _(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"li",13),l["\u0275\u0275template"](1,C,4,3,"a",9),l["\u0275\u0275template"](2,b,4,2,"span",10),l["\u0275\u0275elementEnd"]()),2&e){l["\u0275\u0275nextContext"](2);var n=l["\u0275\u0275reference"](1);l["\u0275\u0275classProp"]("disabled",n.isLastPage()),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",!n.isLastPage()),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",n.isLastPage())}}function y(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"ul",3),l["\u0275\u0275template"](1,h,3,4,"li",4),l["\u0275\u0275elementStart"](2,"li",5),l["\u0275\u0275text"](3),l["\u0275\u0275elementEnd"](),l["\u0275\u0275template"](4,x,3,6,"li",6),l["\u0275\u0275template"](5,_,3,4,"li",7),l["\u0275\u0275elementEnd"]()),2&e){var n=l["\u0275\u0275nextContext"](),i=l["\u0275\u0275reference"](1);l["\u0275\u0275classProp"]("responsive",n.responsive),l["\u0275\u0275attribute"]("aria-label",n.screenReaderPaginationLabel),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",n.directionLinks),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate2"](" ",i.getCurrent()," / ",i.getLastPage()," "),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngForOf",i.pages),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",n.directionLinks)}}var P=function(){function e(){this.change=new l.EventEmitter,this.instances={},this.DEFAULT_ID="DEFAULT_PAGINATION_ID"}return e.prototype.defaultId=function(){return this.DEFAULT_ID},e.prototype.register=function(e){return null==e.id&&(e.id=this.DEFAULT_ID),this.instances[e.id]?this.updateInstance(e):(this.instances[e.id]=e,!0)},e.prototype.updateInstance=function(e){var t=!1;for(var n in this.instances[e.id])e[n]!==this.instances[e.id][n]&&(this.instances[e.id][n]=e[n],t=!0);return t},e.prototype.getCurrentPage=function(e){if(this.instances[e])return this.instances[e].currentPage},e.prototype.setCurrentPage=function(e,t){if(this.instances[e]){var n=this.instances[e];t<=Math.ceil(n.totalItems/n.itemsPerPage)&&1<=t&&(this.instances[e].currentPage=t,this.change.emit(e))}},e.prototype.setTotalItems=function(e,t){this.instances[e]&&0<=t&&(this.instances[e].totalItems=t,this.change.emit(e))},e.prototype.setItemsPerPage=function(e,t){this.instances[e]&&(this.instances[e].itemsPerPage=t,this.change.emit(e))},e.prototype.getInstance=function(e){return void 0===e&&(e=this.DEFAULT_ID),this.instances[e]?this.clone(this.instances[e]):{}},e.prototype.clone=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t},e.\u0275fac=function(t){return new(t||e)},e.\u0275prov=l["\u0275\u0275defineInjectable"]({token:e,factory:function(t){return e.\u0275fac(t)}}),e}(),M=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},I=Number.MAX_SAFE_INTEGER,O=function(){function e(e){this.service=e,this.state={}}return e.prototype.transform=function(e,t){if(!(e instanceof Array)){var n=t.id||this.service.defaultId();return this.state[n]?this.state[n].slice:e}var i,a,r=t.totalItems&&t.totalItems!==e.length,o=this.createInstance(e,t),s=o.id,l=o.itemsPerPage,d=this.service.register(o);if(!r&&e instanceof Array){if(this.stateIsIdentical(s,e,i=(o.currentPage-1)*(l=+l||I),a=i+l))return this.state[s].slice;var c=e.slice(i,a);return this.saveState(s,e,c,i,a),this.service.change.emit(s),c}return d&&this.service.change.emit(s),this.saveState(s,e,e,i,a),e},e.prototype.createInstance=function(e,t){return this.checkConfig(t),{id:null!=t.id?t.id:this.service.defaultId(),itemsPerPage:+t.itemsPerPage||0,currentPage:+t.currentPage||1,totalItems:+t.totalItems||e.length}},e.prototype.checkConfig=function(e){var t=["itemsPerPage","currentPage"].filter((function(t){return!(t in e)}));if(0<t.length)throw new Error("PaginatePipe: Argument is missing the following required properties: "+t.join(", "))},e.prototype.saveState=function(e,t,n,i,a){this.state[e]={collection:t,size:t.length,slice:n,start:i,end:a}},e.prototype.stateIsIdentical=function(e,t,n,i){var a=this.state[e];return!!a&&!(a.size!==t.length||a.start!==n||a.end!==i)&&a.slice.every((function(e,i){return e===t[n+i]}))},(e=function(e,t,n,i){var a,r=arguments.length,o=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(a=e[s])&&(o=(r<3?a(o):r>3?a(t,n,o):a(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o}([M("design:paramtypes",[P])],e)).\u0275fac=function(t){return new(t||e)(l["\u0275\u0275directiveInject"](P))},e.\u0275pipe=l["\u0275\u0275definePipe"]({name:"paginate",type:e,pure:!1}),e}(),S=function(e,t,n,i){var a,r=arguments.length,o=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(a=e[s])&&(o=(r<3?a(o):r>3?a(t,n,o):a(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o},E=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};function w(e){return!!e&&"false"!==e}var k=function(){function e(){this.maxSize=7,this.previousLabel="Previous",this.nextLabel="Next",this.screenReaderPaginationLabel="Pagination",this.screenReaderPageLabel="page",this.screenReaderCurrentLabel="You're on page",this.pageChange=new l.EventEmitter,this.pageBoundsCorrection=new l.EventEmitter,this._directionLinks=!0,this._autoHide=!1,this._responsive=!1}return Object.defineProperty(e.prototype,"directionLinks",{get:function(){return this._directionLinks},set:function(e){this._directionLinks=w(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"autoHide",{get:function(){return this._autoHide},set:function(e){this._autoHide=w(e)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"responsive",{get:function(){return this._responsive},set:function(e){this._responsive=w(e)},enumerable:!0,configurable:!0}),S([Object(l.Input)(),E("design:type",String)],e.prototype,"id",void 0),S([Object(l.Input)(),E("design:type",Number)],e.prototype,"maxSize",void 0),S([Object(l.Input)(),E("design:type",Boolean),E("design:paramtypes",[Boolean])],e.prototype,"directionLinks",null),S([Object(l.Input)(),E("design:type",Boolean),E("design:paramtypes",[Boolean])],e.prototype,"autoHide",null),S([Object(l.Input)(),E("design:type",Boolean),E("design:paramtypes",[Boolean])],e.prototype,"responsive",null),S([Object(l.Input)(),E("design:type",String)],e.prototype,"previousLabel",void 0),S([Object(l.Input)(),E("design:type",String)],e.prototype,"nextLabel",void 0),S([Object(l.Input)(),E("design:type",String)],e.prototype,"screenReaderPaginationLabel",void 0),S([Object(l.Input)(),E("design:type",String)],e.prototype,"screenReaderPageLabel",void 0),S([Object(l.Input)(),E("design:type",String)],e.prototype,"screenReaderCurrentLabel",void 0),S([Object(l.Output)(),E("design:type",l.EventEmitter)],e.prototype,"pageChange",void 0),S([Object(l.Output)(),E("design:type",l.EventEmitter)],e.prototype,"pageBoundsCorrection",void 0),e.\u0275fac=function(t){return new(t||e)},e.\u0275cmp=l["\u0275\u0275defineComponent"]({type:e,selectors:[["pagination-controls"]],inputs:{maxSize:"maxSize",previousLabel:"previousLabel",nextLabel:"nextLabel",screenReaderPaginationLabel:"screenReaderPaginationLabel",screenReaderPageLabel:"screenReaderPageLabel",screenReaderCurrentLabel:"screenReaderCurrentLabel",directionLinks:"directionLinks",autoHide:"autoHide",responsive:"responsive",id:"id"},outputs:{pageChange:"pageChange",pageBoundsCorrection:"pageBoundsCorrection"},decls:3,vars:3,consts:[[3,"id","maxSize","pageChange","pageBoundsCorrection"],["p","paginationApi"],["class","ngx-pagination","role","navigation",3,"responsive",4,"ngIf"],["role","navigation",1,"ngx-pagination"],["class","pagination-previous",3,"disabled",4,"ngIf"],[1,"small-screen"],[3,"current","ellipsis",4,"ngFor","ngForOf"],["class","pagination-next",3,"disabled",4,"ngIf"],[1,"pagination-previous"],["tabindex","0",3,"keyup.enter","click",4,"ngIf"],[4,"ngIf"],["tabindex","0",3,"keyup.enter","click"],[1,"show-for-sr"],[1,"pagination-next"]],template:function(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"pagination-template",0,1),l["\u0275\u0275listener"]("pageChange",(function(e){return t.pageChange.emit(e)}))("pageBoundsCorrection",(function(e){return t.pageBoundsCorrection.emit(e)})),l["\u0275\u0275template"](2,y,6,8,"ul",2),l["\u0275\u0275elementEnd"]()),2&e){var n=l["\u0275\u0275reference"](1);l["\u0275\u0275property"]("id",t.id)("maxSize",t.maxSize),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngIf",!(t.autoHide&&n.pages.length<=1))}},directives:function(){return[F,i.NgIf,i.NgForOf]},pipes:function(){return[i.DecimalPipe]},styles:["\n.ngx-pagination {\n margin-left: 0;\n margin-bottom: 1rem; }\n .ngx-pagination::before, .ngx-pagination::after {\n content: ' ';\n display: table; }\n .ngx-pagination::after {\n clear: both; }\n .ngx-pagination li {\n -moz-user-select: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n margin-right: 0.0625rem;\n border-radius: 0; }\n .ngx-pagination li {\n display: inline-block; }\n .ngx-pagination a,\n .ngx-pagination button {\n color: #0a0a0a; \n display: block;\n padding: 0.1875rem 0.625rem;\n border-radius: 0; }\n .ngx-pagination a:hover,\n .ngx-pagination button:hover {\n background: #e6e6e6; }\n .ngx-pagination .current {\n padding: 0.1875rem 0.625rem;\n background: #2199e8;\n color: #fefefe;\n cursor: default; }\n .ngx-pagination .disabled {\n padding: 0.1875rem 0.625rem;\n color: #cacaca;\n cursor: default; } \n .ngx-pagination .disabled:hover {\n background: transparent; }\n .ngx-pagination a, .ngx-pagination button {\n cursor: pointer; }\n\n.ngx-pagination .pagination-previous a::before,\n.ngx-pagination .pagination-previous.disabled::before { \n content: '\xab';\n display: inline-block;\n margin-right: 0.5rem; }\n\n.ngx-pagination .pagination-next a::after,\n.ngx-pagination .pagination-next.disabled::after {\n content: '\xbb';\n display: inline-block;\n margin-left: 0.5rem; }\n\n.ngx-pagination .show-for-sr {\n position: absolute !important;\n width: 1px;\n height: 1px;\n overflow: hidden;\n clip: rect(0, 0, 0, 0); }\n.ngx-pagination .small-screen {\n display: none; }\n@media screen and (max-width: 601px) {\n .ngx-pagination.responsive .small-screen {\n display: inline-block; } \n .ngx-pagination.responsive li:not(.small-screen):not(.pagination-previous):not(.pagination-next) {\n display: none; }\n}\n "],encapsulation:2,changeDetection:0}),e}(),L=function(e,t,n,i){var a,r=arguments.length,o=r<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,i);else for(var s=e.length-1;s>=0;s--)(a=e[s])&&(o=(r<3?a(o):r>3?a(t,n,o):a(t,n))||o);return r>3&&o&&Object.defineProperty(t,n,o),o},A=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},F=function(){function e(e,t){var n=this;this.service=e,this.changeDetectorRef=t,this.maxSize=7,this.pageChange=new l.EventEmitter,this.pageBoundsCorrection=new l.EventEmitter,this.pages=[],this.changeSub=this.service.change.subscribe((function(e){n.id===e&&(n.updatePageLinks(),n.changeDetectorRef.markForCheck(),n.changeDetectorRef.detectChanges())}))}return e.prototype.ngOnInit=function(){void 0===this.id&&(this.id=this.service.defaultId()),this.updatePageLinks()},e.prototype.ngOnChanges=function(e){this.updatePageLinks()},e.prototype.ngOnDestroy=function(){this.changeSub.unsubscribe()},e.prototype.previous=function(){this.checkValidId(),this.setCurrent(this.getCurrent()-1)},e.prototype.next=function(){this.checkValidId(),this.setCurrent(this.getCurrent()+1)},e.prototype.isFirstPage=function(){return 1===this.getCurrent()},e.prototype.isLastPage=function(){return this.getLastPage()===this.getCurrent()},e.prototype.setCurrent=function(e){this.pageChange.emit(e)},e.prototype.getCurrent=function(){return this.service.getCurrentPage(this.id)},e.prototype.getLastPage=function(){var e=this.service.getInstance(this.id);return e.totalItems<1?1:Math.ceil(e.totalItems/e.itemsPerPage)},e.prototype.getTotalItems=function(){return this.service.getInstance(this.id).totalItems},e.prototype.checkValidId=function(){null==this.service.getInstance(this.id).id&&console.warn('PaginationControlsDirective: the specified id "'+this.id+'" does not match any registered PaginationInstance')},e.prototype.updatePageLinks=function(){var e=this,t=this.service.getInstance(this.id),n=this.outOfBoundCorrection(t);n!==t.currentPage?setTimeout((function(){e.pageBoundsCorrection.emit(n),e.pages=e.createPageArray(t.currentPage,t.itemsPerPage,t.totalItems,e.maxSize)})):this.pages=this.createPageArray(t.currentPage,t.itemsPerPage,t.totalItems,this.maxSize)},e.prototype.outOfBoundCorrection=function(e){var t=Math.ceil(e.totalItems/e.itemsPerPage);return t<e.currentPage&&0<t?t:e.currentPage<1?1:e.currentPage},e.prototype.createPageArray=function(e,t,n,i){i=+i;for(var a=[],r=Math.ceil(n/t),o=Math.ceil(i/2),s=e<=o,l=r-o<e,d=!s&&!l,c=i<r,p=1;p<=r&&p<=i;){var g=this.calculatePageNumber(p,e,i,r);a.push({label:c&&(2===p&&(d||l)||p===i-1&&(d||s))?"...":g,value:g}),p++}return a},e.prototype.calculatePageNumber=function(e,t,n,i){var a=Math.ceil(n/2);return e===n?i:1===e?e:n<i?i-a<t?i-n+e:a<t?t-a+e:e:e},L([Object(l.Input)(),A("design:type",String)],e.prototype,"id",void 0),L([Object(l.Input)(),A("design:type",Number)],e.prototype,"maxSize",void 0),L([Object(l.Output)(),A("design:type",l.EventEmitter)],e.prototype,"pageChange",void 0),L([Object(l.Output)(),A("design:type",l.EventEmitter)],e.prototype,"pageBoundsCorrection",void 0),(e=L([A("design:paramtypes",[P,l.ChangeDetectorRef])],e)).\u0275fac=function(t){return new(t||e)(l["\u0275\u0275directiveInject"](P),l["\u0275\u0275directiveInject"](l.ChangeDetectorRef))},e.\u0275dir=l["\u0275\u0275defineDirective"]({type:e,selectors:[["pagination-template"],["","pagination-template",""]],inputs:{maxSize:"maxSize",id:"id"},outputs:{pageChange:"pageChange",pageBoundsCorrection:"pageBoundsCorrection"},exportAs:["paginationApi"],features:[l["\u0275\u0275NgOnChangesFeature"]]}),e}(),R=function(){function e(){}return e.\u0275mod=l["\u0275\u0275defineNgModule"]({type:e}),e.\u0275inj=l["\u0275\u0275defineInjector"]({factory:function(t){return new(t||e)},providers:[P],imports:[[i.CommonModule]]}),e}(),j=n("xJkR");const V=["addressFromMap"],z=["map"],B=["changedPlace"];function T(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div"),l["\u0275\u0275elementStart"](1,"div",22),l["\u0275\u0275elementStart"](2,"input",32),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().house=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"label",33),l["\u0275\u0275text"](4),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"div",22),l["\u0275\u0275elementStart"](6,"input",34),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().landmark=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](7,"label",35),l["\u0275\u0275text"](8),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](9,"div",22),l["\u0275\u0275elementStart"](10,"input",36),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().pincode=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](11,"label",37),l["\u0275\u0275text"](12),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](13,"div",22),l["\u0275\u0275elementStart"](14,"select",38),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().title=t})),l["\u0275\u0275elementStart"](15,"option",39),l["\u0275\u0275text"](16),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](17,"option",40),l["\u0275\u0275text"](18),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](19,"option",41),l["\u0275\u0275text"](20),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngModel",e.house),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("HOUSE / FLAT NO")," "),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngModel",e.landmark),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("LANDMARK")," "),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngModel",e.pincode),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Pincode")," "),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngModel",e.title),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("HOME")," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("WORK")," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("OTHER")," ")}}function D(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"a",42),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().chooseFromMaps()})),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Confirm and Proceed")," ")}}function N(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"a",42),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().addAddress()})),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Add Address")," ")}}function $(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"a",42),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().editMyAddress()})),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Edit")," ")}}function q(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",43),l["\u0275\u0275listener"]("click",(function(){l["\u0275\u0275restoreView"](e);const n=t.$implicit;return l["\u0275\u0275nextContext"]().selectSearchResult1(n)})),l["\u0275\u0275element"](1,"mdb-icon",44),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"]()}if(2&e){const e=t.$implicit;l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.description," ")}}function H(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div",52),l["\u0275\u0275elementStart"](1,"label",53),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"label",54),l["\u0275\u0275text"](4),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"label",54),l["\u0275\u0275text"](6),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",e.util.userInfo.first_name+" "+e.util.userInfo.last_name," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",e.util.userInfo.email," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",e.util.userInfo.country_code+" "+e.util.userInfo.mobile," ")}}const U=function(e){return{"background-image":e}};function G(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",45),l["\u0275\u0275elementStart"](1,"div",46),l["\u0275\u0275elementStart"](2,"div",47),l["\u0275\u0275element"](3,"div",48),l["\u0275\u0275template"](4,H,7,3,"div",49),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"div",50),l["\u0275\u0275elementStart"](6,"div",51),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().editProfileClick=!0})),l["\u0275\u0275text"](7),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275styleProp"]("background-image"," url(assets/imgs/food8.jpg) ",l["\u0275\u0275defaultStyleSanitizer"]),l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("ngStyle",l["\u0275\u0275pureFunction1"](5,U,"url("+e.getProfile()+"),url(assets/icon.png)")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",e.util.userInfo),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Edit Profile")," ")}}function W(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",55),l["\u0275\u0275elementStart"](1,"p",56),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"div",57),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().openLink("profile")})),l["\u0275\u0275text"](4),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"div",57),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().openLink("order")})),l["\u0275\u0275text"](6),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](7,"div",57),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().openLink("address")})),l["\u0275\u0275text"](8),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](e.util.translate("Activity")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngClass","profile"===e.tabId?"active_btn":"normal_btn"),l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Profile"),""),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngClass","order"===e.tabId?"active_btn":"normal_btn"),l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Order History"),""),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngClass","address"===e.tabId?"active_btn":"normal_btn"),l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("My addresses"),"")}}function Q(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"p",53),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate"](e.util.translate("User Informations"))}}function K(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"p",53),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate"](e.util.translate("Order History"))}}function X(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"p",53),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate"](e.util.translate("My addresses"))}}function Y(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",75),l["\u0275\u0275elementStart"](1,"button",76),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](3).updateProfile()})),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"](3);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](e.util.translate("Save"))}}function J(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",60),l["\u0275\u0275elementStart"](1,"div",62),l["\u0275\u0275elementStart"](2,"label",63),l["\u0275\u0275element"](3,"mdb-icon",64),l["\u0275\u0275elementStart"](4,"input",65),l["\u0275\u0275listener"]("change",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](2).preview_banner(t.target.files)})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"label",66),l["\u0275\u0275text"](6),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](7,"div",28),l["\u0275\u0275elementStart"](8,"div",67),l["\u0275\u0275elementStart"](9,"label",68),l["\u0275\u0275text"](10),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](11,"input",69),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](2).first_name=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](12,"div",67),l["\u0275\u0275elementStart"](13,"label",68),l["\u0275\u0275text"](14),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](15,"input",69),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](2).last_name=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](16,"div",67),l["\u0275\u0275elementStart"](17,"label",68),l["\u0275\u0275text"](18),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](19,"select",70),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](2).gender=t})),l["\u0275\u0275elementStart"](20,"option",71),l["\u0275\u0275text"](21),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](22,"option",72),l["\u0275\u0275text"](23),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](24,"option",73),l["\u0275\u0275text"](25),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](26,"div",67),l["\u0275\u0275elementStart"](27,"label",68),l["\u0275\u0275text"](28),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](29,"input",69),l["\u0275\u0275listener"]("ngModelChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](2).mobile=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275template"](30,Y,3,1,"div",74),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngStyle",l["\u0275\u0275pureFunction1"](18,U,"url("+e.getProfile()+"),url(assets/icon.png)")),l["\u0275\u0275advance"](5),l["\u0275\u0275textInterpolate"](e.util.userInfo.first_name+" "+e.util.userInfo.last_name),l["\u0275\u0275advance"](4),l["\u0275\u0275textInterpolate"](e.util.translate("First Name")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("disabled",!e.editProfileClick)("ngModel",e.first_name),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate"](e.util.translate("Last Name")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("disabled",!e.editProfileClick)("ngModel",e.last_name),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate"](e.util.translate("Gender")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngModel",e.gender)("disabled",!e.editProfileClick),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Male"),""),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Female")," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Others")," "),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate"](e.util.translate("Phone Number")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("disabled",!e.editProfileClick)("ngModel",e.mobile),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",e.editProfileClick)}}function Z(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div"),l["\u0275\u0275elementStart"](1,"div",58),l["\u0275\u0275elementStart"](2,"div",28),l["\u0275\u0275element"](3,"div",59),l["\u0275\u0275elementStart"](4,"div",60),l["\u0275\u0275elementStart"](5,"div",28),l["\u0275\u0275template"](6,J,31,20,"div",61),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275element"](7,"div",59),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](6),l["\u0275\u0275property"]("ngIf",e.util.userInfo)}}function ee(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]().$implicit;l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate1"](" - ",e.variations[0].items[e.variant].title," ")}}function te(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"p",92),l["\u0275\u0275elementStart"](1,"span"),l["\u0275\u0275text"](2),l["\u0275\u0275template"](3,ee,2,1,"span",11),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](4,"span"),l["\u0275\u0275text"](5),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=t.$implicit;l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",e.name," "),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","1"===e.size),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("X ",e.quantiy,"")}}function ne(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"](2).$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate2"](" ",t.util.currecny,"",e.grand_total," ")}}function ie(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"](2).$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate2"]("",e.grand_total," ",t.util.currecny," ")}}function ae(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div",89),l["\u0275\u0275template"](1,te,6,3,"p",90),l["\u0275\u0275elementStart"](2,"p",91),l["\u0275\u0275elementStart"](3,"span"),l["\u0275\u0275text"](4,"Total"),l["\u0275\u0275elementEnd"](),l["\u0275\u0275template"](5,ne,2,2,"span",11),l["\u0275\u0275template"](6,ie,2,2,"span",11),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]().$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngForOf",e.orders),l["\u0275\u0275advance"](4),l["\u0275\u0275property"]("ngIf","left"===t.util.cside),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","right"===t.util.cside)}}function re(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]().$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate2"](" ",t.util.currecny,"",e.grand_total," ")}}function oe(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"span"),l["\u0275\u0275text"](1),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]().$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](1),l["\u0275\u0275textInterpolate2"]("",e.grand_total," ",t.util.currecny," ")}}function se(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div",93),l["\u0275\u0275elementStart"](1,"div",94),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"](3);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",e.util.translate("Delivered")," ")}}function le(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div",93),l["\u0275\u0275elementStart"](1,"div",94),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]().$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate2"](" ",t.util.translate("Your Order is")," ",e.status," ")}}function de(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div",93),l["\u0275\u0275elementStart"](1,"div",94),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"div",95),l["\u0275\u0275element"](4,"mdb-icon",96),l["\u0275\u0275text"](5),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]().$implicit,t=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate2"](" ",t.util.translate("Your Order is")," ",e.status," "),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate1"](" ",t.util.translate("Track Order")," ")}}function ce(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",80),l["\u0275\u0275listener"]("click",(function(){l["\u0275\u0275restoreView"](e);const n=t.$implicit;return l["\u0275\u0275nextContext"](2).goToHistoryDetail(n.id)})),l["\u0275\u0275elementStart"](1,"div",81),l["\u0275\u0275element"](2,"div",82),l["\u0275\u0275elementEnd"](),l["\u0275\u0275element"](3,"div",83),l["\u0275\u0275elementStart"](4,"div",84),l["\u0275\u0275elementStart"](5,"label",85),l["\u0275\u0275text"](6),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](7,"div",86),l["\u0275\u0275template"](8,ae,7,3,"div",87),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](9,"label",85),l["\u0275\u0275text"](10),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](11,"label",86),l["\u0275\u0275text"](12),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](13,"label",85),l["\u0275\u0275text"](14),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](15,"label",86),l["\u0275\u0275template"](16,re,2,2,"span",11),l["\u0275\u0275template"](17,oe,2,2,"span",11),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275element"](18,"div",83),l["\u0275\u0275template"](19,se,3,1,"div",88),l["\u0275\u0275template"](20,le,3,2,"div",88),l["\u0275\u0275template"](21,de,6,3,"div",88),l["\u0275\u0275elementEnd"]()}if(2&e){const e=t.$implicit,n=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngStyle",l["\u0275\u0275pureFunction1"](11,U,"url("+n.api.mediaURL+e.orders[0].cover+"),url(assets/placeholder.png)")),l["\u0275\u0275advance"](4),l["\u0275\u0275textInterpolate"](n.util.translate("ITEMS")),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngIf",null==e.orders?null:e.orders.length),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](n.util.translate("ORDERED ON")),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",n.getDate(e.time)," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](n.util.translate("TOTAL AMOUNT")),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngIf","left"===n.util.cside),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","right"===n.util.cside),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngIf","completed"==e.status||"delivered"==e.status),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","rejected"==e.status||"cancel"==e.status),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","created"==e.status||"ongoing"==e.status||"accepted"===e.status)}}function pe(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",97),l["\u0275\u0275elementStart"](1,"pagination-controls",98),l["\u0275\u0275listener"]("pageChange",(function(t){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"](2).page=t})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}}const ge=function(){return{"border-radius":"5px",height:"50px",width:"100%"}},me=function(){return{height:"20px",width:"120px"}},ue=function(){return{height:"20px",width:"70px"}};function he(e,t){1&e&&(l["\u0275\u0275elementStart"](0,"div",99),l["\u0275\u0275elementStart"](1,"div",81),l["\u0275\u0275elementStart"](2,"div",100),l["\u0275\u0275element"](3,"ngx-skeleton-loader",101),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](4,"div",102),l["\u0275\u0275elementStart"](5,"label",103),l["\u0275\u0275element"](6,"ngx-skeleton-loader",104),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](7,"label",105),l["\u0275\u0275element"](8,"ngx-skeleton-loader",104),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e&&(l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](3,ge)),l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](4,me)),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](5,ue)))}const fe=function(e){return{id:"pagin1",itemsPerPage:5,currentPage:e}};function ve(e,t){if(1&e&&(l["\u0275\u0275elementStart"](0,"div"),l["\u0275\u0275template"](1,ce,22,13,"div",77),l["\u0275\u0275pipe"](2,"paginate"),l["\u0275\u0275template"](3,pe,2,0,"div",78),l["\u0275\u0275template"](4,he,9,6,"div",79),l["\u0275\u0275elementEnd"]()),2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngForOf",l["\u0275\u0275pipeBind2"](2,3,e.myOrders,l["\u0275\u0275pureFunction1"](6,fe,e.page))),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngIf",null==e.myOrders?null:e.myOrders.length),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngForOf",e.dummy)}}function xe(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",110),l["\u0275\u0275elementStart"](1,"p",111),l["\u0275\u0275text"](2),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"p",112),l["\u0275\u0275text"](4),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"div",113),l["\u0275\u0275elementStart"](6,"label",114),l["\u0275\u0275listener"]("click",(function(){l["\u0275\u0275restoreView"](e);const n=t.$implicit;return l["\u0275\u0275nextContext"](2).editAddress(n)})),l["\u0275\u0275text"](7),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](8,"label",115),l["\u0275\u0275listener"]("click",(function(){l["\u0275\u0275restoreView"](e);const n=t.$implicit;return l["\u0275\u0275nextContext"](2).deleteAddress(n)})),l["\u0275\u0275text"](9),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=t.$implicit,n=l["\u0275\u0275nextContext"](2);l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"]("",e.title," "),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate3"]("",e.house," ",e.landmark," ",e.address,""),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate"](n.util.translate("Edit")),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](n.util.translate("Delete"))}}const Ce=function(){return{height:"20px",width:"160px"}};function be(e,t){1&e&&(l["\u0275\u0275elementStart"](0,"div",110),l["\u0275\u0275elementStart"](1,"p",111),l["\u0275\u0275element"](2,"ngx-skeleton-loader",104),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](3,"p",112),l["\u0275\u0275element"](4,"ngx-skeleton-loader",104),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](5,"div",113),l["\u0275\u0275elementStart"](6,"label",116),l["\u0275\u0275element"](7,"ngx-skeleton-loader",104),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](8,"label",117),l["\u0275\u0275element"](9,"ngx-skeleton-loader",104),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()),2&e&&(l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](4,ue)),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](5,Ce)),l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](6,ue)),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("theme",l["\u0275\u0275pureFunction0"](7,ue)))}function _e(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div"),l["\u0275\u0275elementStart"](1,"div",28),l["\u0275\u0275elementStart"](2,"div",106),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275nextContext"]().addNewAddress()})),l["\u0275\u0275element"](3,"i",107),l["\u0275\u0275elementStart"](4,"label",108),l["\u0275\u0275text"](5),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275template"](6,xe,10,6,"div",109),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](7,"div",28),l["\u0275\u0275template"](8,be,10,8,"div",109),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}if(2&e){const e=l["\u0275\u0275nextContext"]();l["\u0275\u0275advance"](5),l["\u0275\u0275textInterpolate"](e.util.translate("Add New")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngForOf",e.myaddress),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngForOf",e.dummyAddress)}}const ye=[{path:"",component:(()=>{class e{constructor(e,t,n,i,r){if(this.route=e,this.util=t,this.api=n,this.router=i,this.chmod=r,this.tabId="profile",this.haveItems=!1,this.myOrders=[],this.dummy=Array(10),this.dummyAddress=Array(10),this.myaddress=[],this.page=1,this.address="",this.house="",this.landmark="",this.title="home",this.pincode="",this.query="",this.autocompleteItems1=[],this.first_name="",this.last_name="",this.route.snapshot.paramMap.get("id")&&this.route.snapshot.paramMap.get("from")){const e=this.route.snapshot.paramMap.get("id");console.log(e),this.tabId=this.route.snapshot.paramMap.get("from"),this.GoogleAutocomplete=new google.maps.places.AutocompleteService,this.geocoder=new google.maps.Geocoder,this.query="",this.gender=this.util.userInfo.gender,this.first_name=this.util.userInfo.first_name,this.last_name=this.util.userInfo.last_name,this.mobile=this.util.userInfo.mobile,this.autocompleteItems1=[],this.addressSelected=!1,this.editProfileClick=!0,"order"===this.tabId?this.getMyOrders("",!1):"address"===this.tabId&&this.getAddress()}else this.router.navigate([""]);this.router.events.subscribe(e=>{e instanceof a.c&&(this.tabId=this.route.snapshot.paramMap.get("from"),console.log("router event",this.tabId),"order"===this.tabId?this.getMyOrders("",!1):"address"===this.tabId&&this.getAddress())})}ngOnInit(){}changeTab(e){this.tabId=e}getProfile(){return this.util.userInfo&&this.util.userInfo.cover?this.api.mediaURL+this.util.userInfo.cover:""}openLink(e){const t=(this.util.userInfo.first_name+"-"+this.util.userInfo.last_name).toLowerCase();this.tabId=e,"order"===this.tabId&&this.getMyOrders("",!1),"address"===this.tabId&&this.getAddress(),this.router.navigate(["user",t,e]),this.chmod.detectChanges()}doRefresh(e){console.log(e),this.getMyOrders(e,!0)}getMyOrders(e,t){const n={id:localStorage.getItem("uid")};this.api.post("orders/getByUid",n).then(n=>{this.dummy=[],console.log(n),n&&200===n.status&&n.data.length?(this.haveItems=!0,n.data.forEach(e=>{e.orders=JSON.parse(e.orders)}),this.myOrders=n.data):this.haveItems=!1,this.chmod.detectChanges(),t&&e.target.complete()},e=>{console.log(e),this.dummy=[],this.util.errorMessage(this.util.translate("Something went wrong"))}).catch(e=>{console.log(e),this.dummy=[],this.util.errorMessage(this.util.translate("Something went wrong"))})}getCart(){this.router.navigate(["/tabs"])}goToHistoryDetail(e){console.log(e),this.router.navigate(["/order-detail"],{queryParams:{id:e}})}getDate(e){return r(e).format("llll")}getAddress(){const e={id:localStorage.getItem("uid")};this.api.post("address/getByUid",e).then(e=>{console.log(e),this.dummyAddress=[],e&&200===e.status&&e.data.length>0&&(this.myaddress=e.data,this.chmod.detectChanges())},e=>{console.log(e),this.dummyAddress=[],this.util.errorMessage(this.util.translate("Something went wrong"))}).catch(e=>{console.log(e),this.dummyAddress=[],this.util.errorMessage(this.util.translate("Something went wrong"))})}addNewAddress(){this.editClicked=!1,window.navigator&&window.navigator.geolocation&&window.navigator.geolocation.getCurrentPosition(e=>{console.log(e),this.addressSelected=!1,this.addressFromMap.show(),this.getAddressFromMaps(e.coords.latitude,e.coords.longitude)},e=>{switch(e.code){case 1:console.log("Permission Denied"),this.util.errorMessage(this.util.translate("Location Permission Denied"));break;case 2:console.log("Position Unavailable"),this.util.errorMessage(this.util.translate("Position Unavailable"));break;case 3:console.log("Timeout"),this.util.errorMessage(this.util.translate("Failed to fetch location"))}})}getAddressFromMaps(e,t){const n=new google.maps.Geocoder,i=new google.maps.LatLng(e,t);n.geocode({location:i},(n,i)=>{console.log(n),console.log("status",i),n&&n.length&&(this.address=n[0].formatted_address,this.chmod.detectChanges(),this.loadMap(e,t))})}loadMap(e,t){const n=new google.maps.LatLng(e,t),i={zoom:16,scaleControl:!1,streetViewControl:!1,zoomControl:!1,overviewMapControl:!1,center:n,mapTypeControl:!1,mapTypeControlOptions:{mapTypeIds:[google.maps.MapTypeId.ROADMAP,"Foodies"]}};this.map=new google.maps.Map(this.mapElement.nativeElement,i);const a=new google.maps.StyledMapType([{featureType:"all",elementType:"all",stylers:[{saturation:-100}]}],{name:"Grayscale"});this.map.mapTypes.set("Foodies",a),this.map.setMapTypeId("Foodies"),this.chmod.detectChanges(),this.addMarker(n)}addMarker(e){const t={url:"assets/map-marker.png",scaledSize:new google.maps.Size(50,50)};this.marker=new google.maps.Marker({position:e,map:this.map,icon:t})}changeAddress(){this.addressFromMap.hide(),this.changedPlace.show()}deleteAddress(e){s.a.fire({title:this.util.translate("Are you sure?"),text:this.util.translate("to delete this address"),icon:"question",confirmButtonText:this.util.translate("Yes"),backdrop:!1,background:"white",showCancelButton:!0,showConfirmButton:!0,cancelButtonText:this.util.translate("cancel")}).then(t=>{console.log(t),t&&t.value&&(this.util.start(),this.api.post("address/deleteList",{id:e.id}).then(e=>{console.log(e),this.util.stop(),this.getAddress()},e=>{console.log(e),this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong"))}).catch(e=>{console.log(e),this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong"))}))})}chooseFromMaps(){this.addressSelected=!0,document.getElementById("map").style.height="150px"}addAddress(){if(this.addressFromMap.hide(),""===this.address||""===this.landmark||""===this.house||""===this.pincode)return this.util.errorMessage(this.util.translate("All Fields are required")),!1;const e=new google.maps.Geocoder;this.util.start(),e.geocode({address:this.house+" "+this.landmark+" "+this.address+" "+this.pincode},(e,t)=>{if(console.log(e,t),"OK"!==t||!e||!e.length)return this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong")),!1;{this.lat=e[0].geometry.location.lat(),this.lng=e[0].geometry.location.lng(),console.log("-----\x3e",this.lat,this.lng),console.log("call api");const t={uid:localStorage.getItem("uid"),address:this.address,lat:this.lat,lng:this.lng,title:this.title,house:this.house,landmark:this.landmark,pincode:this.pincode};this.api.post("address/save",t).then(e=>{this.util.stop(),e&&200===e.status?(this.getAddress(),s.a.mixin({toast:!0,position:"bottom-end",showConfirmButton:!1,timer:3e3,timerProgressBar:!0,onOpen:e=>{e.addEventListener("mouseenter",s.a.stopTimer),e.addEventListener("mouseleave",s.a.resumeTimer)}}).fire({icon:"success",title:this.util.translate("Address added")})):this.util.errorMessage(this.util.translate("Something went wrong"))},e=>{console.log(e),this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong"))})}})}onSearchChange(e){if(console.log(e),""===this.query)return void(this.autocompleteItems1=[]);const t=localStorage.getItem("addsSelected");t&&null!=t?localStorage.removeItem("addsSelected"):this.GoogleAutocomplete.getPlacePredictions({input:this.query},(e,t)=>{console.log(e),e&&e.length>0&&(this.autocompleteItems1=e,console.log(this.autocompleteItems1))})}selectSearchResult1(e){console.log("select",e),localStorage.setItem("addsSelected","true"),this.autocompleteItems1=[],this.query=e.description,this.geocoder.geocode({placeId:e.place_id},(e,t)=>{"OK"===t&&e[0]&&(console.log(t),this.address=this.query,this.lat=e[0].geometry.location.lat(),this.lng=e[0].geometry.location.lng(),this.changedPlace.hide(),this.addressFromMap.show(),this.chmod.detectChanges(),this.loadMap(this.lat,this.lng))})}editAddress(e){console.log(e),this.editClicked=!0,this.address=e.address,this.lat=e.lat,this.lng=e.lng,this.pincode=e.pincode,this.landmark=e.landmark,this.house=e.house,this.title=e.title,this.address_id=e.id,this.addressFromMap.show(),this.getAddressFromMaps(this.lat,this.lng),this.chooseFromMaps()}editMyAddress(){if(this.addressFromMap.hide(),""===this.address||""===this.landmark||""===this.house||!this.pincode||""===this.pincode)return this.util.errorMessage(this.util.translate("All Fields are required")),!1;const e=new google.maps.Geocoder;this.util.start(),e.geocode({address:this.house+" "+this.landmark+" "+this.address+" "+this.pincode},(e,t)=>{if(console.log(e,t),"OK"!==t||!e||!e.length)return this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong")),!1;{this.lat=e[0].geometry.location.lat(),this.lng=e[0].geometry.location.lng(),console.log("-----\x3e",this.lat,this.lng);const t={id:this.address_id,uid:localStorage.getItem("uid"),address:this.address,lat:this.lat,lng:this.lng,title:this.title,house:this.house,landmark:this.landmark,pincode:this.pincode};this.api.post("address/editList",t).then(e=>{this.util.stop(),this.chmod.detectChanges(),e&&200===e.status?(this.getAddress(),s.a.mixin({toast:!0,position:"bottom-end",showConfirmButton:!1,timer:3e3,timerProgressBar:!0,onOpen:e=>{e.addEventListener("mouseenter",s.a.stopTimer),e.addEventListener("mouseleave",s.a.resumeTimer)}}).fire({icon:"success",title:this.util.translate("Address updated")})):this.util.errorMessage(this.util.translate("Something went wrong"))},e=>{console.log(e),this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong"))})}})}updateProfile(){if(!this.first_name||""===this.first_name||!this.last_name||""===this.last_name||!this.mobile||""===this.mobile)return this.util.errorMessage(this.util.translate("All Fields are required")),!1;const e={first_name:this.first_name,last_name:this.last_name,gender:this.gender,mobile:this.mobile,id:localStorage.getItem("uid")};this.util.start(),this.api.post("users/edit_profile",e).then(e=>{this.util.stop(),console.log(e),this.getProfileInfo()},e=>{this.util.stop(),console.log(e),this.util.errorMessage(this.util.translate("Something went wrong"))})}getProfileInfo(){const e={id:localStorage.getItem("uid")};this.util.start(),this.api.post("users/getById",e).then(e=>{this.util.stop(),console.log("user info=>",e),e&&200===e.status&&e.data&&e.data.length&&(this.util.userInfo=e.data[0])},e=>{console.log(e),this.util.stop(),this.util.errorMessage(this.util.translate("Something went wrong"))})}preview_banner(e){console.log("fle",e),0!==e.length&&null!=e[0].type.match(/image\/*/)&&(e?(console.log("ok"),this.util.start(),this.api.uploadFile(e).subscribe(e=>{if(console.log("==>>",e),this.util.stop(),e&&200===e.status&&e.data){const t={cover:e.data,id:localStorage.getItem("uid")};this.util.start(),this.api.post("users/edit_profile",t).then(e=>{this.util.stop(),console.log(e),this.getProfileInfo()},e=>{this.util.stop(),console.log(e),this.util.errorMessage(this.util.translate("Something went wrong"))})}},e=>{console.log(e),this.util.stop()})):console.log("no"))}}return e.\u0275fac=function(t){return new(t||e)(l["\u0275\u0275directiveInject"](a.a),l["\u0275\u0275directiveInject"](d.a),l["\u0275\u0275directiveInject"](c.a),l["\u0275\u0275directiveInject"](a.f),l["\u0275\u0275directiveInject"](l.ChangeDetectorRef))},e.\u0275cmp=l["\u0275\u0275defineComponent"]({type:e,selectors:[["app-settings"]],viewQuery:function(e,t){var n;1&e&&(l["\u0275\u0275viewQuery"](V,!0),l["\u0275\u0275staticViewQuery"](z,!0),l["\u0275\u0275viewQuery"](B,!0)),2&e&&(l["\u0275\u0275queryRefresh"](n=l["\u0275\u0275loadQuery"]())&&(t.addressFromMap=n.first),l["\u0275\u0275queryRefresh"](n=l["\u0275\u0275loadQuery"]())&&(t.mapElement=n.first),l["\u0275\u0275queryRefresh"](n=l["\u0275\u0275loadQuery"]())&&(t.changedPlace=n.first))},decls:51,vars:25,consts:[["mdbModal","","id","frameModalTop","tabindex","-1","role","dialog","aria-labelledby","myModalLabel","aria-hidden","true",1,"modal","fade","center",2,"z-index","99999","overflow-y","auto"],["addressFromMap","mdbModal"],["role","document",1,"modal-dialog","modal-notify","modal-success"],[1,"modal-content"],[1,"modal-body",2,"padding","10px"],["id","map",1,"map"],["map",""],[1,"borders"],[1,"address"],["fas","","icon","check-circle","color","primary"],["mdbWavesEffect","",1,"changeBtn",3,"click"],[4,"ngIf"],[1,"modal-footer","justify-content-center"],["type","button","mdbBtn","","color","danger","class","waves-light","mdbWavesEffect","",3,"click",4,"ngIf"],["type","button","mdbBtn","","color","danger","outline","true","mdbWavesEffect","","data-dismiss","modal",1,"waves-light",3,"click"],["mdbModal","","id","frameModalTop","tabindex","-1","role","dialog","aria-labelledby","myModalLabel","aria-hidden","true",1,"modal","fade","center",2,"z-index","99999"],["changedPlace","mdbModal"],["role","document",1,"modal-dialog","modal-lg"],[1,"modal-body"],[1,"headers"],[1,"text"],["fas","","mdbWavesEffect","","icon","times-circle",3,"click"],[1,"md-form"],["id","cnum","type","text","mdbInput","",1,"form-control",2,"height","auto !important",3,"ngModel","placeholder","ngModelChange"],[1,"addressList"],["class","select_addr",3,"click",4,"ngFor","ngForOf"],["class","container back_image",3,"backgroundImage",4,"ngIf"],[1,"container","main_div"],[1,"row"],["class","col-md-3 col-sm-6 col-xs-12",4,"ngIf"],[1,"col-md-9","col-sm-6","col-xs-12"],["class","header",4,"ngIf"],["id","house","type","text","mdbInput","",1,"form-control",2,"height","auto !important",3,"ngModel","ngModelChange"],["for","house"],["id","landmark","type","text","mdbInput","",1,"form-control",2,"height","auto !important",3,"ngModel","ngModelChange"],["for","landmark"],["id","pincode","type","text","mdbInput","",1,"form-control",2,"height","auto !important",3,"ngModel","ngModelChange"],["for","pincode"],[1,"browser-default","custom-select",3,"ngModel","ngModelChange"],["value","home"],["value","work"],["value","other"],["type","button","mdbBtn","","color","danger","mdbWavesEffect","",1,"waves-light",3,"click"],[1,"select_addr",3,"click"],["fas","","icon","map-marker-alt",2,"color","gray","margin-right","10px"],[1,"container","back_image"],[1,"overlay"],[1,"profiles"],[1,"cover",3,"ngStyle"],["class","user_details",4,"ngIf"],[1,"more_section"],["mdbWavesEffect","",1,"btn",3,"click"],[1,"user_details"],[1,"header"],[1,"details"],[1,"col-md-3","col-sm-6","col-xs-12"],[1,"head"],[3,"ngClass","click"],[1,"edit_profile"],[1,"col-lg-2"],[1,"col-lg-12"],["class","col-lg-12",4,"ngIf"],[1,"round_image",3,"ngStyle"],["for","file-input",1,"green_box"],["fas","","icon","pencil-alt",1,"pencil_icn"],["id","file-input","type","file",3,"change"],[1,"title_text"],[1,"col-lg-6"],[1,"hint_lbl"],["mdbInput","","type","text","id","form1",1,"form-control",3,"disabled","ngModel","ngModelChange"],["type","text","required","",2,"border","1px solid lightgray","width","100%",3,"ngModel","disabled","ngModelChange"],["value","1"],["value","0"],["value","2"],["class","col-lg-12","style","text-align: center;",4,"ngIf"],[1,"col-lg-12",2,"text-align","center"],["mdbBtn","","type","button","mdbWavesEffect","",1,"round_btn",3,"click"],["class","card_div",3,"click",4,"ngFor","ngForOf"],["class","has-text-centered",4,"ngIf"],["class","card_div",4,"ngFor","ngForOf"],[1,"card_div",3,"click"],[1,"resto_detail"],[1,"back_image",3,"ngStyle"],[1,"line_div"],[1,"order_detail"],[1,"head_gray"],[1,"small_lbl"],["class","border_bottom",4,"ngIf"],["class","status_detail",4,"ngIf"],[1,"border_bottom"],["class","items",4,"ngFor","ngForOf"],[1,"itemss"],[1,"items"],[1,"status_detail"],[1,"deliver_div"],[1,"repeat_div",2,"color","green"],["fas","","icon","location-arrow","color","primary"],[1,"has-text-centered"],["id","pagin1",3,"pageChange"],[1,"card_div"],[1,"back_image"],["appearance","circle",3,"theme"],[2,"margin-left","20px","display","flex","flex-direction","column"],[1,"res_name",2,"margin","0px"],["appearance","line",3,"theme"],[1,"res_location",2,"margin","0px"],[1,"col-md-4","col-sm-6","col-xs-12","newAddress_card",3,"click"],[1,"fas","fa-plus-circle"],[1,"lbl"],["class","col-md-4 col-sm-6 col-xs-12 address_card",4,"ngFor","ngForOf"],[1,"col-md-4","col-sm-6","col-xs-12","address_card"],[1,"title"],[1,"full_address"],[1,"btns"],["mdbWavesEffect","",1,"editBtn",3,"click"],["mdbWavesEffect","",1,"delete",3,"click"],["mdbWavesEffect","",1,"editBtn"],["mdbWavesEffect","",1,"delete"]],template:function(e,t){if(1&e){const e=l["\u0275\u0275getCurrentView"]();l["\u0275\u0275elementStart"](0,"div",0,1),l["\u0275\u0275elementStart"](2,"div",2),l["\u0275\u0275elementStart"](3,"div",3),l["\u0275\u0275elementStart"](4,"div",4),l["\u0275\u0275element"](5,"div",5,6),l["\u0275\u0275elementStart"](7,"div"),l["\u0275\u0275elementStart"](8,"h4"),l["\u0275\u0275text"](9),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](10,"p"),l["\u0275\u0275text"](11),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](12,"div",7),l["\u0275\u0275elementStart"](13,"p",8),l["\u0275\u0275element"](14,"mdb-icon",9),l["\u0275\u0275text"](15),l["\u0275\u0275pipe"](16,"slice"),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](17,"p",10),l["\u0275\u0275listener"]("click",(function(){return t.changeAddress()})),l["\u0275\u0275text"](18),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275template"](19,T,21,10,"div",11),l["\u0275\u0275elementEnd"](),l["\u0275\u0275element"](20,"div"),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](21,"div",12),l["\u0275\u0275template"](22,D,2,1,"a",13),l["\u0275\u0275template"](23,N,2,1,"a",13),l["\u0275\u0275template"](24,$,2,1,"a",13),l["\u0275\u0275elementStart"](25,"a",14),l["\u0275\u0275listener"]("click",(function(){return l["\u0275\u0275restoreView"](e),l["\u0275\u0275reference"](1).hide()})),l["\u0275\u0275text"](26),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](27,"div",15,16),l["\u0275\u0275elementStart"](29,"div",17),l["\u0275\u0275elementStart"](30,"div",3),l["\u0275\u0275elementStart"](31,"div",18),l["\u0275\u0275elementStart"](32,"div",19),l["\u0275\u0275elementStart"](33,"p",20),l["\u0275\u0275text"](34),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](35,"mdb-icon",21),l["\u0275\u0275listener"]("click",(function(){l["\u0275\u0275restoreView"](e);const t=l["\u0275\u0275reference"](28),n=l["\u0275\u0275reference"](1);return t.hide(),n.show()})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](36,"div",22),l["\u0275\u0275elementStart"](37,"input",23),l["\u0275\u0275listener"]("ngModelChange",(function(e){return t.query=e}))("ngModelChange",(function(e){return t.onSearchChange(e)})),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementStart"](38,"div",24),l["\u0275\u0275template"](39,q,3,1,"div",25),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275template"](40,G,8,7,"div",26),l["\u0275\u0275elementStart"](41,"div",27),l["\u0275\u0275elementStart"](42,"div",28),l["\u0275\u0275template"](43,W,9,7,"div",29),l["\u0275\u0275elementStart"](44,"div",30),l["\u0275\u0275template"](45,Q,2,1,"p",31),l["\u0275\u0275template"](46,K,2,1,"p",31),l["\u0275\u0275template"](47,X,2,1,"p",31),l["\u0275\u0275template"](48,Z,8,1,"div",11),l["\u0275\u0275template"](49,ve,5,8,"div",11),l["\u0275\u0275template"](50,_e,9,3,"div",11),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"](),l["\u0275\u0275elementEnd"]()}2&e&&(l["\u0275\u0275advance"](9),l["\u0275\u0275textInterpolate"](t.util.translate("Set your delivery location")),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate"](t.util.translate("DELIVERY AREA")),l["\u0275\u0275advance"](4),l["\u0275\u0275textInterpolate1"](" ",t.address.length>50?l["\u0275\u0275pipeBind3"](16,21,t.address,0,50)+"..":t.address," "),l["\u0275\u0275advance"](3),l["\u0275\u0275textInterpolate"](t.util.translate("Change")),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",!0===t.addressSelected),l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("ngIf",!1===t.addressSelected),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",!0===t.addressSelected&&!1===t.editClicked),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf",!0===t.editClicked),l["\u0275\u0275advance"](2),l["\u0275\u0275textInterpolate1"](" ",t.util.translate("Cancel")," "),l["\u0275\u0275advance"](8),l["\u0275\u0275textInterpolate"](t.util.translate("Search Location")),l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("ngModel",t.query)("placeholder",t.util.translate("Search")),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngForOf",t.autocompleteItems1),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","desktop"===t.util.deviceType),l["\u0275\u0275advance"](3),l["\u0275\u0275property"]("ngIf","desktop"===t.util.deviceType),l["\u0275\u0275advance"](2),l["\u0275\u0275property"]("ngIf","profile"===t.tabId),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","order"===t.tabId),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","address"===t.tabId),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","profile"===t.tabId),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","order"===t.tabId),l["\u0275\u0275advance"](1),l["\u0275\u0275property"]("ngIf","address"===t.tabId))},directives:[p.r,p.o,p.j,p.v,i.NgIf,p.n,g.a,p.p,g.i,g.l,i.NgForOf,g.s,g.m,g.t,i.NgStyle,i.NgClass,g.r,k,j.a],pipes:[i.SlicePipe,O],styles:["label[_ngcontent-%COMP%]{display:block;margin:0}#map[_ngcontent-%COMP%]{width:100%;height:250px}.headers[_ngcontent-%COMP%]{display:flex;flex-direction:row;align-items:center;justify-content:space-between}.headers[_ngcontent-%COMP%] .text[_ngcontent-%COMP%]{margin:0;font-size:28px}.headers[_ngcontent-%COMP%] mdb-icon[_ngcontent-%COMP%]{color:#6f0;cursor:pointer}.addressList[_ngcontent-%COMP%]{background:#fff}.addressList[_ngcontent-%COMP%] .select_addr[_ngcontent-%COMP%]{display:flex;flex-direction:row;margin:10px;border-bottom:1px dashed #d3d3d3;align-items:center;padding:5px;z-index:9999;overflow:visible;cursor:pointer}.addressList[_ngcontent-%COMP%] .select_addr[_ngcontent-%COMP%]:hover{background:#f2f2f2}.borders[_ngcontent-%COMP%]{display:flex;flex-direction:row;border:1px solid #d3d3d3;border-radius:5px;align-items:center;padding:5px;justify-content:space-between}.borders[_ngcontent-%COMP%] .address[_ngcontent-%COMP%]{font-size:15px;margin:0}.borders[_ngcontent-%COMP%] .changeBtn[_ngcontent-%COMP%]{color:#6f0;font-weight:700;cursor:pointer;margin:0}.back_image[_ngcontent-%COMP%]{width:100%;height:250px;background-repeat:no-repeat;background-size:cover;background-position:50%}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%]{height:100%;width:100%;background:rgba(0,0,0,.5)}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%], .back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%] .profiles[_ngcontent-%COMP%]{display:flex;flex-direction:row;justify-content:space-between;align-items:center}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%] .profiles[_ngcontent-%COMP%] .cover[_ngcontent-%COMP%]{height:120px;width:120px;border-radius:50%;background-repeat:no-repeat;background-size:cover;background-position:50%;border:5px solid #fff;margin-left:20px}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%] .profiles[_ngcontent-%COMP%] .user_details[_ngcontent-%COMP%]{margin-left:20px}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%] .profiles[_ngcontent-%COMP%] .user_details[_ngcontent-%COMP%] .header[_ngcontent-%COMP%]{font-size:16px;font-weight:700;color:#fff}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%] .profiles[_ngcontent-%COMP%] .user_details[_ngcontent-%COMP%] .details[_ngcontent-%COMP%]{font-size:14px;color:#fff}.back_image[_ngcontent-%COMP%] .overlay[_ngcontent-%COMP%] .more_section[_ngcontent-%COMP%] .btn[_ngcontent-%COMP%]{background-color:#6f0;color:#fff}.main_div[_ngcontent-%COMP%]{margin-top:20px}.main_div[_ngcontent-%COMP%] .head[_ngcontent-%COMP%]{font-size:16px;font-weight:700;color:grey;text-transform:uppercase}.main_div[_ngcontent-%COMP%] .active_btn[_ngcontent-%COMP%]{color:#6f0;font-size:14px;padding:10px 5px;cursor:pointer;background:rgba(0,0,0,.5);background:rgba(195,217,208,.5);border-left:2px solid;font-weight:700}.main_div[_ngcontent-%COMP%] .normal_btn[_ngcontent-%COMP%]{color:#000;font-size:14px;padding:10px 0;cursor:pointer}.main_div[_ngcontent-%COMP%] .header[_ngcontent-%COMP%]{font-size:18px;font-weight:700;color:#000}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%]{width:100%;box-shadow:0 1px 3px rgba(0,0,0,.2);border-radius:10px;padding:15px;margin-bottom:20px;border:.5px solid #d3d3d3}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .line_div[_ngcontent-%COMP%]{height:1px;width:100%;background:#d3d3d3;margin-top:10px;margin-bottom:10px}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .resto_detail[_ngcontent-%COMP%]{display:flex;flex-direction:row;align-items:center}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .resto_detail[_ngcontent-%COMP%] .back_image[_ngcontent-%COMP%]{height:50px;width:50px;background-position:50%;background-size:cover;background-repeat:no-repeat;border-radius:5px;min-width:50px}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .resto_detail[_ngcontent-%COMP%] .res_name[_ngcontent-%COMP%]{font-weight:600}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .resto_detail[_ngcontent-%COMP%] .res_location[_ngcontent-%COMP%]{color:#d3d3d3;font-size:14px}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .head_gray[_ngcontent-%COMP%]{color:#d3d3d3;font-size:13px;margin-top:10px;display:block;margin-bottom:0}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .small_lbl[_ngcontent-%COMP%]{font-size:12px;font-weight:600;display:block;margin-bottom:0}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .border_bottom[_ngcontent-%COMP%]{border-bottom:1px dashed #d3d3d3;padding:5px 0;font-size:15px;font-weight:700}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .subNames[_ngcontent-%COMP%]{border-bottom:1px dashed #d3d3d3;padding-bottom:5px}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .subNames[_ngcontent-%COMP%] .food_title[_ngcontent-%COMP%]{font-size:15px;font-weight:700}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .subNames[_ngcontent-%COMP%] .flex_titles[_ngcontent-%COMP%]{display:flex;flex-direction:row;justify-content:space-between}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .order_detail[_ngcontent-%COMP%] .subNames[_ngcontent-%COMP%] .flex_titles[_ngcontent-%COMP%] .sub_name[_ngcontent-%COMP%]{margin:0;color:#000;font-size:12px}.main_div[_ngcontent-%COMP%] .card_div[_ngcontent-%COMP%] .status_detail[_ngcontent-%COMP%]{display:flex;flex-direction:row;justify-content:space-between;color:#d3d3d3;font-size:14px}.main_div[_ngcontent-%COMP%] .newAddress_card[_ngcontent-%COMP%]{padding:10px;display:flex;flex-direction:column;justify-content:center;align-items:center;cursor:pointer}.main_div[_ngcontent-%COMP%] .newAddress_card[_ngcontent-%COMP%]:hover{background:#f2f2f2}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%]{margin-bottom:40px}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .title_text[_ngcontent-%COMP%]{font-size:22px;font-weight:700;text-align:center;margin-top:20px;margin-bottom:5px}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .round_image[_ngcontent-%COMP%]{height:90px;width:90px;border-radius:50%;position:relative;margin-top:30px!important;background-repeat:no-repeat;background-size:cover;background-position:50%;margin:auto}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .round_image[_ngcontent-%COMP%] .user_icn[_ngcontent-%COMP%]{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#93959f;font-size:30px}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .round_image[_ngcontent-%COMP%] .green_box[_ngcontent-%COMP%]{width:35px;height:35px;border-radius:50%;background:#6f0;position:absolute;bottom:0;right:0}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .round_image[_ngcontent-%COMP%] .green_box[_ngcontent-%COMP%] .pencil_icn[_ngcontent-%COMP%]{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);color:#fff}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .round_image[_ngcontent-%COMP%] .green_box[_ngcontent-%COMP%] > input[_ngcontent-%COMP%]{display:none}.main_div[_ngcontent-%COMP%] .edit_profile[_ngcontent-%COMP%] .round_btn[_ngcontent-%COMP%]{background:#6f0;color:#fff;font-size:18px;margin:50px 0 0;letter-spacing:1px}.main_div[_ngcontent-%COMP%] .address_card[_ngcontent-%COMP%]{padding:10px}.main_div[_ngcontent-%COMP%] .address_card[_ngcontent-%COMP%] .title[_ngcontent-%COMP%]{font-size:16px;font-weight:700;margin:0;text-transform:uppercase}.main_div[_ngcontent-%COMP%] .address_card[_ngcontent-%COMP%] .full_address[_ngcontent-%COMP%]{font-size:14px;margin:0}.main_div[_ngcontent-%COMP%] .address_card[_ngcontent-%COMP%] .btns[_ngcontent-%COMP%]{display:flex;flex-direction:row;align-items:center}.main_div[_ngcontent-%COMP%] .address_card[_ngcontent-%COMP%] .btns[_ngcontent-%COMP%] .editBtn[_ngcontent-%COMP%]{color:#6f0;font-weight:700;font-size:14px;cursor:pointer;padding:5px}.main_div[_ngcontent-%COMP%] .address_card[_ngcontent-%COMP%] .btns[_ngcontent-%COMP%] .delete[_ngcontent-%COMP%]{color:grey;font-weight:700;font-size:14px;margin:0 15px;cursor:pointer;padding:5px}"]}),e})()}];let Pe=(()=>{class e{}return e.\u0275mod=l["\u0275\u0275defineNgModule"]({type:e}),e.\u0275inj=l["\u0275\u0275defineInjector"]({factory:function(t){return new(t||e)},imports:[[a.h.forChild(ye)],a.h]}),e})();n("jtHE"),n("XNiG"),n("pLZG"),n("1G5W"),n("R0Ic");let Me=(()=>{let e=class{};return e.\u0275mod=l["\u0275\u0275defineNgModule"]({type:e}),e.\u0275inj=l["\u0275\u0275defineInjector"]({factory:function(t){return new(t||e)},imports:[[i.CommonModule]]}),e})();var Ie=n("PCNd");n.d(t,"SettingsModule",(function(){return Oe}));let Oe=(()=>{class e{}return e.\u0275mod=l["\u0275\u0275defineNgModule"]({type:e}),e.\u0275inj=l["\u0275\u0275defineInjector"]({factory:function(t){return new(t||e)},imports:[[i.CommonModule,Pe,p.m.forRoot(),Me,R,g.e,Ie.a]]}),e})()}}]);
|
/*===================================================================================*/
/* GLOBAL HELPER FUNCTIONS
/*===================================================================================*/
// Get Breakpoint set in main.css (at the end)
function getCSSBreakpoint() {
return window.getComputedStyle(document.querySelector('body'), ':before')
.getPropertyValue('content')
.replace(/\"/g, '');
}
// Checks if selected Breakpoint matches current
function cssBreakpoint(bp) {
return getCSSBreakpoint() === bp && true;
}
// Checks if Breakpoint has switched e.g. on Resize
var switchedBreakpoint = (function () {
var lastBreakpoint;
return function () {
if (getCSSBreakpoint() !== lastBreakpoint) {
lastBreakpoint = getCSSBreakpoint();
return true;
}
else return false;
}
})();
// Debounce/Delay Window Resize Function for better Resize Performance
function debounce(func, wait, immediate) {
var timeout,
wait = wait || 100; // Default Delay 100ms
return function() {
var context = this,
args = arguments,
later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
},
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
}
}
// Call Resize Function
//$(window).resize(debounce(function() { ... })); // Without custom Delay (Default is 100ms)
//$(window).on('resize', debounce(function() { ... }, 250)); // With custom Delay of 250ms and 'on' Event Handler e.g.
/*===================================================================================*/
/* FIXED NAVIGATION (BOOTSTRAP AFFIX)
/*===================================================================================*/
$(document).ready(function() {
var affixElementDesktop = '.navbar-collapse',
affixElementDesktopHeight = affixElementDesktop,
affixElementDesktopOffset = '.navbar-header',
affixElementMobile = '.navbar',
affixElementMobileHeight = '.navbar-header',
affixElementMobileNav = '.navbar-nav',
affixElementMobileNavBtn = '.navbar-toggler',
bodyScrollDisableClass = 'body-scroll-disabled';
function affixNav(el, elHeight, elOffset) {
$(window).off('.affix');
$('.affix, .affix-top').unwrap();
$(affixElementDesktop + ', ' + affixElementMobile)
.removeData('bs.affix')
.removeClass('affix affix-top');
$(el).affix({ offset: { top: $(elOffset).outerHeight(true) || 0 } });
$('.affix, .affix-top')
.wrap('<div class="affix-wrapper"></div>')
.parent().css('min-height', $(elHeight).outerHeight(true) || 0);
}
$(window).resize(debounce(function () {
if (cssBreakpoint('md')) {
if (switchedBreakpoint()) {
$(affixElementMobileNav).css('height', '');
affixNav(affixElementDesktop, affixElementDesktopHeight, affixElementDesktopOffset);
if ($(affixElementDesktop).hasClass('show')) {
enableSelectedScroll(false, affixElementMobileNav);
$('html').removeClass(bodyScrollDisableClass);
}
}
}
else if (cssBreakpoint('xs')) {
if (switchedBreakpoint()) {
affixNav(affixElementMobile, affixElementMobileHeight);
if ($(affixElementDesktop).hasClass('show')) {
enableSelectedScroll(true, affixElementMobileNav);
$('html').addClass(bodyScrollDisableClass);
}
}
$(affixElementMobileNav).css('height', window.innerHeight - $(affixElementMobileHeight).outerHeight(true) || 0);
}
})).resize();
$(affixElementDesktop).on('show.bs.collapse', function(){
enableSelectedScroll(true, affixElementMobileNav);
$('html').addClass(bodyScrollDisableClass);
});
$(affixElementDesktop).on('hide.bs.collapse', function(){
enableSelectedScroll(false, affixElementMobileNav);
$('html').removeClass(bodyScrollDisableClass);
});
});
/*===================================================================================*/
/* HEADER RESIZE
/*===================================================================================*/
$(document).ready(function() {
// Settings
var topHeaderHeight = $('.navbar-header').outerHeight(true), // ------- Get Height of Element that is not fixed and not being changed — used for Delay before Element starts changing
objectStyles = {
navbarPadTop : { // -------------------------------------------- Custom Element/Object Name — type what you want
element : '.navbar .navbar-collapse', // ------------------ CSS Class of Element that is being changed
style : 'padding-top', // ------------------------------- CSS Style that is being changed
start : 'currentValueFromCSS', // ----------------------- Change from e.g. 30 (Pixels) — if a String/Text is entered then the current Value from CSS File is being taken
end : 0, // ------------------------------------------- Change to e.g. 0 (Pixels)
distance : 300, // ----------------------------------------- Element is being resized for e.g. 300 (Pixels) scrolled
delay : topHeaderHeight // ------------------------------ Delay before Element starts changing e.g. 50 (Pixels)
},
navbarPadBot : {
element : '.navbar .navbar-collapse',
style : 'padding-bottom',
start : 'currentValueFromCSS',
end : 0,
distance : 300,
delay : topHeaderHeight
},
navbarLogoH : {
element : '.navbar-brand img',
style : 'height',
start : 'currentValueFromCSS',
end : 20,
distance : 300,
delay : topHeaderHeight
}
},
scrolledFromTop = 0,
running = false;
function initialize() {
$.each(objectStyles, function(obj, prop) {
prop.start = typeof prop.start === 'string' ? parseInt($(prop.element).css(prop.style), 10) : prop.start;
prop.maxChange = prop.start - prop.end;
prop.scrollRatio = prop.maxChange / prop.distance;
prop.animTriggered = false;
prop.animFinished = false;
$(prop.element).addClass('animate');
});
}
function destroy() {
$.each(objectStyles, function(obj, prop) {
$(prop.element)
.css(prop.style, '')
.removeClass('animate animate-after');
});
}
function resizeHeader() {
scrolledFromTop = $(document).scrollTop();
running = false;
$.each(objectStyles, function(obj, prop) {
if (scrolledFromTop > prop.delay) {
if (!prop.animTriggered) prop.animTriggered = true;
prop.scrolled = scrolledFromTop - prop.delay;
if (prop.scrolled <= prop.distance) {
prop.currentChange = prop.start - prop.scrolled * prop.scrollRatio.toFixed(2);
$(prop.element).css(prop.style, prop.currentChange + 'px');
if (prop.animFinished) {
prop.animFinished = false;
$(prop.element).removeClass('animate-after');
}
}
else if (!prop.animFinished) {
prop.animFinished = true;
$(prop.element)
.css(prop.style, prop.end + 'px')
.addClass('animate-after');
}
}
else if (prop.animTriggered) {
prop.animTriggered = false;
$(prop.element).css(prop.style, prop.start + 'px');
}
});
}
if (cssBreakpoint('md')) {
initialize();
var initialized = true;
}
else var initialized = false;
$(window).resize(debounce(function () {
if (cssBreakpoint('md') && !initialized) {
initialize();
resizeHeader();
initialized = true;
}
else if (cssBreakpoint('xs') && initialized) {
destroy();
initialized = false;
}
}));
$(window).scroll(function () {
if (cssBreakpoint('md') && !running) window.requestAnimationFrame(resizeHeader);
running = true;
});
});
/*===================================================================================*/
/* DROPDOWN ON HOVER (NAVIGATION)
/*===================================================================================*/
$(document).ready(function () {
function dropdownHover() {
$('.dropdown, .dropdown-submenu').addClass('hover');
$(document).on({
mouseenter: function () {
$('.open').removeClass('open');
$(this).addClass('open').find('.dropdown-toggle').removeAttr('data-toggle');
},
mouseleave: function () {
$(this).removeClass('open').find('.dropdown-toggle').attr('data-toggle', 'dropdown');
}
}, '.dropdown.hover');
$(document).on({
mouseleave: function () {
$(this).removeClass('open');
}
}, '.dropdown-submenu.hover.open');
}
function dropdownPress() {
$('.dropdown, .dropdown-submenu').removeClass('hover');
}
$('.dropdown-submenu [data-toggle=dropdown]').click(function(event) {
$(this).parent()
.siblings('.open').removeClass('open')
.find('.open').removeClass('open');
$(this).parent()
.toggleClass('open')
.find('.open').removeClass('open');
event.preventDefault();
event.stopPropagation();
});
if (cssBreakpoint('md')) {
dropdownHover();
var dropdownHoverActive = true;
}
else var dropdownHoverActive = false;
$(window).resize(debounce(function () {
if (cssBreakpoint('md') && !dropdownHoverActive) {
dropdownHover();
dropdownHoverActive = true;
}
else if (cssBreakpoint('xs') && dropdownHoverActive) {
dropdownPress();
dropdownHoverActive = false;
}
}));
});
/*===================================================================================*/
/* SMOOTH MAIN CONTENT REVEAL
/*===================================================================================*/
$(document).ready(function () {
$('main').addClass('js-reveal');
});
/*===================================================================================*/
/* AOS — ANIMATE ON SCROLL
/*===================================================================================*/
$(document).ready(function () {
// Settings
var aosEnable = true, // ------------------------------------------------ Turn on/off AOS
aosMobileDisable = false, // ----------------------------------------------- Turn on/off AOS on Mobile
aosContainer = 'main', // ---------------------------------------------- Container (e.g. 'body' [with Footer] or '#main'/'main' [without Footer])
aosItems = '[class*="col-"], .isotope .item, .posts .post', // ----- Add/remove Elements to be animated
aosAnimation = 'fade-up'; // ------------------------------------------- Animation type (More on: https://github.com/michalsnik/aos)
AOS.init({
offset: 120, // ----------------------------------------------------------- Default: 120
duration: 500, // ----------------------------------------------------------- Default: 400
easing: 'ease-out-cubic', // ---------------------------------------------- Default: 'ease'
delay: 0, // ------------------------------------------------------------- Default: 0
once: true, // ---------------------------------------------------------- Default: false
disable: !aosEnable, // ---------------------------------------------------- Default: false (Set above)
startEvent: 'DOMContentLoaded' // --------------------------------------------- Default: 'DOMContentLoaded'
});
function enableAOS() {
$(aosContainer + ' ' + aosItems).attr({
'data-aos' : aosAnimation
});
disableAOS($(aosContainer + ' .collapsed').parents(aosContainer + ' > *').next().find(aosItems), true);
aosEnabled = true;
}
function disableAOS(aosItem, stayEnabled) {
aosItem.removeAttr('data-aos');
aosEnabled = stayEnabled || false;
}
if (aosEnable && (!aosMobileDisable || cssBreakpoint('md')))
enableAOS();
else
aosEnabled = false;
$(window).resize(debounce(function () {
if (aosEnable && !aosEnabled && (!aosMobileDisable || cssBreakpoint('md'))) {
enableAOS();
$(aosContainer + ' ' + aosItems).addClass('aos-animate');
}
else if (aosEnabled && aosMobileDisable && cssBreakpoint('xs'))
disableAOS($(aosItems));
}));
$('a[data-filter]').click(function () {
if(aosEnabled)
disableAOS($(aosItems));
});
});
/*===================================================================================*/
/* OWL CAROUSEL
/*===================================================================================*/
$(document).ready(function () {
var dragging = true;
var owlElementID = "#owl-main";
function fadeInReset() {
if (!dragging) {
$(owlElementID + " .caption .fadeIn-1, " + owlElementID + " .caption .fadeIn-2, " + owlElementID + " .caption .fadeIn-3").stop().delay(800).animate({ opacity: 0 }, { duration: 400, easing: "easeInCubic" });
}
else {
$(owlElementID + " .caption .fadeIn-1, " + owlElementID + " .caption .fadeIn-2, " + owlElementID + " .caption .fadeIn-3").css({ opacity: 0 });
}
}
function fadeInDownReset() {
if (!dragging) {
$(owlElementID + " .caption .fadeInDown-1, " + owlElementID + " .caption .fadeInDown-2, " + owlElementID + " .caption .fadeInDown-3").stop().delay(800).animate({ opacity: 0, top: "-15px" }, { duration: 400, easing: "easeInCubic" });
}
else {
$(owlElementID + " .caption .fadeInDown-1, " + owlElementID + " .caption .fadeInDown-2, " + owlElementID + " .caption .fadeInDown-3").css({ opacity: 0, top: "-15px" });
}
}
function fadeInUpReset() {
if (!dragging) {
$(owlElementID + " .caption .fadeInUp-1, " + owlElementID + " .caption .fadeInUp-2, " + owlElementID + " .caption .fadeInUp-3").stop().delay(800).animate({ opacity: 0, top: "15px" }, { duration: 400, easing: "easeInCubic" });
}
else {
$(owlElementID + " .caption .fadeInUp-1, " + owlElementID + " .caption .fadeInUp-2, " + owlElementID + " .caption .fadeInUp-3").css({ opacity: 0, top: "15px" });
}
}
function fadeInLeftReset() {
if (!dragging) {
$(owlElementID + " .caption .fadeInLeft-1, " + owlElementID + " .caption .fadeInLeft-2, " + owlElementID + " .caption .fadeInLeft-3").stop().delay(800).animate({ opacity: 0, left: "15px" }, { duration: 400, easing: "easeInCubic" });
}
else {
$(owlElementID + " .caption .fadeInLeft-1, " + owlElementID + " .caption .fadeInLeft-2, " + owlElementID + " .caption .fadeInLeft-3").css({ opacity: 0, left: "15px" });
}
}
function fadeInRightReset() {
if (!dragging) {
$(owlElementID + " .caption .fadeInRight-1, " + owlElementID + " .caption .fadeInRight-2, " + owlElementID + " .caption .fadeInRight-3").stop().delay(800).animate({ opacity: 0, left: "-15px" }, { duration: 400, easing: "easeInCubic" });
}
else {
$(owlElementID + " .caption .fadeInRight-1, " + owlElementID + " .caption .fadeInRight-2, " + owlElementID + " .caption .fadeInRight-3").css({ opacity: 0, left: "-15px" });
}
}
function fadeIn() {
$(owlElementID + " .active .caption .fadeIn-1").stop().delay(500).animate({ opacity: 1 }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeIn-2").stop().delay(700).animate({ opacity: 1 }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeIn-3").stop().delay(1000).animate({ opacity: 1 }, { duration: 800, easing: "easeOutCubic" });
}
function fadeInDown() {
$(owlElementID + " .active .caption .fadeInDown-1").stop().delay(500).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInDown-2").stop().delay(700).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInDown-3").stop().delay(1000).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
}
function fadeInUp() {
$(owlElementID + " .active .caption .fadeInUp-1").stop().delay(500).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInUp-2").stop().delay(700).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInUp-3").stop().delay(1000).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
}
function fadeInLeft() {
$(owlElementID + " .active .caption .fadeInLeft-1").stop().delay(500).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInLeft-2").stop().delay(700).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInLeft-3").stop().delay(1000).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
}
function fadeInRight() {
$(owlElementID + " .active .caption .fadeInRight-1").stop().delay(500).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInRight-2").stop().delay(700).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
$(owlElementID + " .active .caption .fadeInRight-3").stop().delay(1000).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
}
$(owlElementID).owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
singleItem: true,
addClassActive: true,
transitionStyle: "fade",
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"],
afterInit: function() {
fadeIn();
fadeInDown();
fadeInUp();
fadeInLeft();
fadeInRight();
},
afterMove: function() {
fadeIn();
fadeInDown();
fadeInUp();
fadeInLeft();
fadeInRight();
},
afterUpdate: function() {
fadeIn();
fadeInDown();
fadeInUp();
fadeInLeft();
fadeInRight();
},
startDragging: function() {
dragging = true;
},
afterAction: function() {
fadeInReset();
fadeInDownReset();
fadeInUpReset();
fadeInLeftReset();
fadeInRightReset();
dragging = false;
}
});
if ($(owlElementID).hasClass("owl-one-item")) {
$(owlElementID + ".owl-one-item").data('owlCarousel').destroy();
}
$(owlElementID + ".owl-one-item").owlCarousel({
singleItem: true,
navigation: false,
pagination: false
});
$('#transitionType li a').click(function () {
$('#transitionType li a').removeClass('active');
$(this).addClass('active');
var newValue = $(this).attr('data-transition-type');
$(owlElementID).data("owlCarousel").transitionTypes(newValue);
$(owlElementID).trigger("owl.next");
return false;
});
$("#owl-testimonials").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
singleItem: true,
addClassActive: true,
autoHeight: true,
transitionStyle: "fadeInAfterOut",
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-projects").owlCarousel({
navigation: false,
autoHeight: true,
slideSpeed: 300,
paginationSpeed: 400,
rewindNav: false,
singleItem: true,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-latest-works").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
items: 4,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-videos").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
items: 5,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-audio").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
items: 5,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-popular-posts").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
items: 5,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-related-posts").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
items: 2,
itemsDesktopSmall: [1199, 2],
itemsTablet: [977, 2],
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-featured-works").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
singleItem: true,
transitionStyle: "goDown",
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-work-samples").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
items: 3,
itemsDesktopSmall: [1199, 3],
itemsTablet: [977, 2],
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-work-samples-big").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
singleItem: true,
transitionStyle: "fadeUp",
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-work, [id*='owl-work-modal']").owlCarousel({
autoPlay: 5000,
slideSpeed: 200,
paginationSpeed: 600,
rewindSpeed: 800,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
singleItem: true,
autoHeight: true,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-office").owlCarousel({
autoPlay: 5000,
slideSpeed: 200,
paginationSpeed: 600,
rewindSpeed: 800,
stopOnHover: true,
navigation: true,
pagination: true,
rewindNav: true,
singleItem: true,
autoHeight: true,
transitionStyle: "fade",
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$("#owl-clients").owlCarousel({
autoPlay: 5000,
stopOnHover: true,
rewindNav: true,
items: 4,
itemsDesktopSmall: [1199, 4],
itemsTablet: [977, 3],
navigation: true,
pagination: true,
navigationText: ["<i class='icon-left-open-mini'></i>", "<i class='icon-right-open-mini'></i>"]
});
$(".slider-next").click(function () {
owl.trigger('owl.next');
})
$(".slider-prev").click(function () {
owl.trigger('owl.prev');
})
});
/*===================================================================================*/
/* ISOTOPE PORTFOLIO
/*===================================================================================*/
$(document).ready(function () {
var $container = $('.items');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.item'
});
});
var resizeTimer;
function resizeFunction() {
$container.isotope();
}
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeFunction, 100);
});
$('a.panel-toggle.collapsed').click(function () {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeFunction, 100);
});
$('.portfolio .filter li a').click(function () {
$('.portfolio .filter li a').removeClass('active');
$(this).addClass('active');
var selector = $(this).attr('data-filter');
$container.isotope({
filter: selector
});
return false;
});
});
/*===================================================================================*/
/* ISOTOPE BLOG
/*===================================================================================*/
$(document).ready(function () {
var $container = $('.posts');
$container.imagesLoaded(function () {
$container.isotope({
itemSelector: '.post'
});
});
var resizeTimer;
function resizeFunction() {
$container.isotope();
}
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(resizeFunction, 100);
});
$('.format-filter li a, .format-wrapper a').click(function () {
var selector = $(this).attr('data-filter');
$container.isotope({
filter: selector
});
$('.format-filter li a').removeClass('active');
$('.format-filter li a[data-filter="'+selector+'"]').addClass('active');
$('html, body').animate({
scrollTop: $('.format-filter').offset().top -130
}, 600);
return false;
});
});
/*===================================================================================*/
/* TABS
/*===================================================================================*/
$(document).ready(function () {
$('.tabs.tabs-reasons').easytabs({
cycle: 1500
});
$('.tabs.tabs-top, .tabs.tabs-circle-top, .tabs.tabs-2-big-top, .tabs.tabs-side').easytabs({
animationSpeed: 200,
updateHash: false
});
});
/*===================================================================================*/
/* ACCORDION (FOR ISOTOPE HEIGHT CALCULATION)
/*===================================================================================*/
$(document).ready(function () {
if ($('.panel-group .portfolio').length > 0) {
$('.panel-group .collapse.show').collapse({
toggle: true
});
}
});
/*===================================================================================*/
/* GO TO TOP / SCROLL UP
/*===================================================================================*/
! function (a, b, c) {
a.fn.scrollUp = function (b) {
a.data(c.body, "scrollUp") || (a.data(c.body, "scrollUp", !0), a.fn.scrollUp.init(b))
}, a.fn.scrollUp.init = function (d) {
var e = a.fn.scrollUp.settings = a.extend({}, a.fn.scrollUp.defaults, d),
f = e.scrollTitle ? e.scrollTitle : e.scrollText,
g = a("<a/>", {
id: e.scrollName,
href: "#top"/*,
title: f*/
}).appendTo("body");
e.scrollImg || g.html(e.scrollText), g.css({
display: "none",
position: "fixed",
zIndex: e.zIndex
}), e.activeOverlay && a("<div/>", {
id: e.scrollName + "-active"
}).css({
position: "absolute",
top: e.scrollDistance + "px",
width: "100%",
borderTop: "1px dotted" + e.activeOverlay,
zIndex: e.zIndex
}).appendTo("body"), scrollEvent = a(b).scroll(function () {
switch (scrollDis = "top" === e.scrollFrom ? e.scrollDistance : a(c).height() - a(b).height() - e.scrollDistance, e.animation) {
case "fade":
a(a(b).scrollTop() > scrollDis ? g.fadeIn(e.animationInSpeed) : g.fadeOut(e.animationOutSpeed));
break;
case "slide":
a(a(b).scrollTop() > scrollDis ? g.slideDown(e.animationInSpeed) : g.slideUp(e.animationOutSpeed));
break;
default:
a(a(b).scrollTop() > scrollDis ? g.show(0) : g.hide(0))
}
}), g.click(function (b) {
b.preventDefault(), a("html, body").animate({
scrollTop: 0
}, e.scrollSpeed, e.easingType)
})
}, a.fn.scrollUp.defaults = {
scrollName: "scrollUp",
scrollDistance: 300,
scrollFrom: "top",
scrollSpeed: 300,
easingType: "linear",
animation: "fade",
animationInSpeed: 200,
animationOutSpeed: 200,
scrollText: "Scroll to top",
scrollTitle: !1,
scrollImg: !1,
activeOverlay: !1,
zIndex: 2147483647
}, a.fn.scrollUp.destroy = function (d) {
a.removeData(c.body, "scrollUp"), a("#" + a.fn.scrollUp.settings.scrollName).remove(), a("#" + a.fn.scrollUp.settings.scrollName + "-active").remove(), a.fn.jquery.split(".")[1] >= 7 ? a(b).off("scroll", d) : a(b).unbind("scroll", d)
}, a.scrollUp = a.fn.scrollUp
}(jQuery, window, document);
$(document).ready(function () {
$.scrollUp({
scrollName: "scrollUp", // Element ID
scrollDistance: 700, // Distance from top/bottom before showing element (px)
scrollFrom: "top", // "top" or "bottom"
scrollSpeed: 1000, // Speed back to top (ms)
easingType: "easeInOutCubic", // Scroll to top easing (see http://easings.net/)
animation: "fade", // Fade, slide, none
animationInSpeed: 200, // Animation in speed (ms)
animationOutSpeed: 200, // Animation out speed (ms)
scrollText: "<i class='icon-up-open-mini'></i>", // Text for element, can contain HTML
scrollTitle: " ", // Set a custom <a> title if required. Defaults to scrollText
scrollImg: 0, // Set true to use image
activeOverlay: 0, // Set CSS color to display scrollUp active point, e.g "#00FFFF"
zIndex: 1001 // Z-Index for the overlay
});
});
/*===================================================================================*/
/* ANIMATED / SMOOTH SCROLL TO ANCHOR
/*===================================================================================*/
$(document).ready(function() {
$("a.scroll-to").click(function() {
if ($(window).width() > 1024) {
var navbarHeight = 45;
}
else {
var navbarHeight = 0;
}
if ($(this).attr('data-anchor-offset') !== undefined) {
var anchorOffset = $(this).attr('data-anchor-offset');
}
else {
var anchorOffset = 0;
}
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top - navbarHeight - anchorOffset + "px"
}, {
duration: 1000,
easing: "easeInOutCubic"
});
return false;
});
// Close/collapse mobile navbar accordion if anchor link inside is pressed
$(".navbar-nav").find(".scroll-to").on("click", function(event){
event.stopPropagation();
event.stopImmediatePropagation();
$(".navbar-collapse.show").collapse("hide");
});
});
/*===================================================================================*/
/* SCROLL SPY
/*===================================================================================*/
$(document).ready(function () {
$('body').scrollspy({
target: '.navbar-collapse',
offset: 50
})
});
/*===================================================================================*/
/* IMAGE HOVER
/*===================================================================================*/
$(document).ready(function () {
$('.icon-overlay a').prepend('<span class="icn-more"></span>');
});
/*===================================================================================*/
/* MODALS
/*===================================================================================*/
$('.modal').on('hidden.bs.modal', function () {
$('.video-container iframe').attr("src", $(".video-container iframe").attr("src"));
});
/*===================================================================================*/
/* DATA REL
/*===================================================================================*/
$(document).ready(function () {
$('a[data-rel]').each(function () {
$(this).attr('rel', $(this).data('rel'));
});
});
/*===================================================================================*/
/* TOOLTIP
/*===================================================================================*/
$(document).ready(function () {
if ($("[rel=tooltip]").length) {
$("[rel=tooltip]").tooltip();
}
});
/*===================================================================================*/
/* CONVERTING iOS SAFARI VIEWPORT UNITS (BUGGY) INTO PIXELS
/*===================================================================================*/
$(document).ready(function () {
window.viewportUnitsBuggyfill.init();
});
/*===================================================================================*/
/* FORM VALIDATION
/*===================================================================================*/
$(document).ready(function() {
$('#contactform, #commentform').validate({
errorPlacement: function(error, element) {
$(element).attr({
'placeholder' : error.html()
});
},
focusInvalid: false,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
},
messages: {
name: {
required: 'Please enter your name!',
minlength: 'Name requires at least 2 characters!'
},
email: {
required: 'Please enter your email!',
email: 'Please enter a valid email!'
},
message: {
required: 'Please enter a message!',
minlength: 'Message requires at least 10 characters!'
}
},
submitHandler: function(form) {
$('#contactform .btn-submit').html('Sending message ...');
$('#commentform .btn-submit').html('Sending comment ...');
$(form).ajaxSubmit({
success: function(responseText, statusText, xhr, $form) {
$(form).delay(1300).slideUp('fast');
$('#response').html(responseText).hide().delay(1300).slideDown('fast');
}
});
return false;
}
});
});
|
const merge = require('webpack-merge')
const path = require('path')
const webpackBaseConfig = require('./webpack.base.conf.js')
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin')
// const CopyWebpackPlugin = require('copy-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const isProd = process.env.NODE_ENV === 'production'
var config = {}
if (isProd) {
config = merge(webpackBaseConfig, {
entry: {
'jigsaw': path.join(__dirname, '../src/index.js')
},
output: {
path: path.join(__dirname, '../dist'),
filename: 'jigsaw.min.js',
library: 'jigasw',
libraryTarget: 'umd',
umdNamedDefine: true
},
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextWebpackPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader'
},
'postcss-loader'
]
})
},
{
test: /\.(less)$/,
use: ExtractTextWebpackPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader'
},
{
loader: 'postcss-loader',
options: {
minimize: true
}
},
'less-loader'
]
})
}
]
},
plugins: [
// new CopyWebpackPlugin([
// {
// from: path.resolve(__dirname, '../assets'),
// to: 'dist',
// ignore: ['.*']
// }
// ]),
new ExtractTextWebpackPlugin('index.css'),
new UglifyJsPlugin({
parallel: true,
sourceMap: true
})
]
})
}
module.exports = config
|
var structframework_1_1utility_1_1base_connection_data =
[
[ "baseConnectionData", "structframework_1_1utility_1_1base_connection_data.html#a31f609095ef57c0190a135e5e8f44576", null ],
[ "baseConnectionData", "structframework_1_1utility_1_1base_connection_data.html#ab843e706869b77830ac5a5f278518a31", null ],
[ "~baseConnectionData", "structframework_1_1utility_1_1base_connection_data.html#a739bfaf144b34bdcb85fa96fd50d914b", null ],
[ "ip", "structframework_1_1utility_1_1base_connection_data.html#a373dfc28409d2d31c1f7b8a50083ea21", null ],
[ "port", "structframework_1_1utility_1_1base_connection_data.html#a41b24b8c75baa0cbab79d5a29b83ac69", null ]
];
|
/*************************************************************
*
* MathJax/localization/vi/MathMenu.js
*
* Copyright (c) 2009-2019 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("vi","MathMenu",{
version: "2.7.7",
isLoaded: true,
strings: {
Show: "Xem To\u00E1n D\u01B0\u1EDBi d\u1EA1ng",
MathMLcode: "M\u00E3 ngu\u1ED3n MathML",
OriginalMathML: "MathML G\u1ED1c",
TeXCommands: "L\u1EC7nh TeX",
AsciiMathInput: "\u0110\u1EA7u v\u00E0o AsciiMathML",
Original: "H\u00ECnh th\u1EE9c G\u1ED1c",
ErrorMessage: "Th\u00F4ng b\u00E1o L\u1ED7i",
Annotation: "Ch\u00FA th\u00EDch",
TeX: "TeX",
StarMath: "StarMath",
Maple: "Maple",
ContentMathML: "MathML N\u1ED9i dung",
OpenMath: "OpenMath",
texHints: "Xem g\u1EE3i \u00FD TeX trong MathML",
Settings: "T\u00F9y ch\u1ECDn To\u00E1n",
ZoomTrigger: "H\u00E0nh \u0111\u1ED9ng Ph\u00F3ng to",
Hover: "R\u00EA chu\u1ED9t",
Click: "Nh\u1EA5n chu\u1ED9t",
DoubleClick: "Nh\u1EA5n \u0111\u00FAp chu\u1ED9t",
NoZoom: "Kh\u00F4ng ph\u00F3ng to",
TriggerRequires: "Ch\u1EC9 khi B\u1EA5m gi\u1EEF:",
Option: "Option",
Alt: "Alt",
Command: "Command",
Control: "Control",
Shift: "Shift",
ZoomFactor: "T\u1EF7 l\u1EC7 Ph\u00F3ng to",
Renderer: "Ki\u1EC3u K\u1EBFt xu\u1EA5t To\u00E1n",
MPHandles: "Cho ph\u00E9p MathPlayer X\u1EED l\u00FD:",
MenuEvents: "S\u1EF1 ki\u1EC7n Tr\u00ECnh \u0111\u01A1n",
MouseEvents: "S\u1EF1 ki\u1EC7n Chu\u1ED9t",
MenuAndMouse: "S\u1EF1 ki\u1EC7n Chu\u1ED9t v\u00E0 Tr\u00ECnh \u0111\u01A1n",
FontPrefs: "T\u00F9y ch\u1ECDn Ph\u00F4ng ch\u1EEF",
ForHTMLCSS: "Cho HTML+CSS:",
Auto: "T\u1EF1 \u0111\u1ED9ng",
TeXLocal: "TeX (tr\u00EAn m\u00E1y)",
TeXWeb: "TeX (tr\u00EAn Web)",
TeXImage: "TeX (h\u00ECnh \u1EA3nh)",
STIXLocal: "STIX (tr\u00EAn m\u00E1y)",
STIXWeb: "STIX (tr\u00EAn Web)",
AsanaMathWeb: "Asana Math (tr\u00EAn Web)",
GyrePagellaWeb: "Gyre Pagella (tr\u00EAn Web)",
GyreTermesWeb: "Gyre Termes (tr\u00EAn Web)",
LatinModernWeb: "Latinh Modern (tr\u00EAn Web)",
NeoEulerWeb: "Neo Euler (tr\u00EAn Web)",
ContextMenu: "Tr\u00ECnh \u0111\u01A1n Ng\u1EEF c\u1EA3nh",
Browser: "Tr\u00ECnh duy\u1EC7t",
Scale: "Ph\u00F3ng to T\u1EA5t c\u1EA3 To\u00E1n\u2026",
Discoverable: "T\u00F4 s\u00E1ng khi R\u00EA chu\u1ED9t",
Locale: "Ng\u00F4n ng\u1EEF",
LoadLocale: "T\u1EA3i t\u1EEB URL\u2026",
About: "Gi\u1EDBi thi\u1EC7u v\u1EC1 MathJax",
Help: "Tr\u1EE3 gi\u00FAp MathJax",
localTeXfonts: "d\u00F9ng c\u00E1c ph\u00F4ng ch\u1EEF TeX tr\u00EAn m\u00E1y",
webTeXfonts: "d\u00F9ng ph\u00F4ng ch\u1EEF TeX tr\u00EAn Web",
imagefonts: "d\u00F9ng c\u00E1c ph\u00F4ng ch\u1EEF h\u00ECnh \u1EA3nh",
localSTIXfonts: "d\u00F9ng c\u00E1c ph\u00F4ng ch\u1EEF STIX tr\u00EAn m\u00E1y",
webSVGfonts: "d\u00F9ng c\u00E1c ph\u00F4ng ch\u1EEF SVG tr\u00EAn Web",
genericfonts: "d\u00F9ng c\u00E1c ph\u00F4ng ch\u1EEF Unicode chung",
wofforotffonts: "Ph\u00F4ng ch\u1EEF WOFF ho\u1EB7c OTF",
eotffonts: "Ph\u00F4ng ch\u1EEF EOT",
svgfonts: "Ph\u00F4ng ch\u1EEF SVG",
WebkitNativeMMLWarning: "Tr\u00ECnh duy\u1EC7t c\u1EE7a b\u1EA1n h\u00ECnh nh\u01B0 kh\u00F4ng h\u1ED7 tr\u1EE3 MathML l\u00E0 m\u1ED9t ng\u00F4n ng\u1EEF g\u1ED1c, n\u00EAn k\u00EDch ho\u1EA1t ch\u1EBF \u0111\u1ED9 k\u1EBFt xu\u1EA5t MathML c\u00F3 th\u1EC3 l\u00E0m cho kh\u00F4ng \u0111\u1ECDc \u0111\u01B0\u1EE3c c\u00E1c to\u00E1n tr\u00EAn trang.",
MSIENativeMMLWarning: "Internet Explorer c\u1EA7n ph\u1EA7n b\u1ED5 sung MathPlayer \u0111\u1EC3 x\u1EED l\u00FD \u0111\u1EA7u ra MathML.",
OperaNativeMMLWarning: "Opera kh\u00F4ng h\u1ED7 tr\u1EE3 MathML \u0111\u1EA7y \u0111\u1EE7, n\u00EAn k\u00EDch ho\u1EA1t ch\u1EBF \u0111\u1ED9 k\u1EBFt xu\u1EA5t MathML c\u00F3 th\u1EC3 l\u00E0m cho m\u1ED9t s\u1ED1 bi\u1EC3u th\u1EE9c hi\u1EC3n th\u1ECB m\u1ED9t c\u00E1ch kh\u00F4ng ch\u00EDnh x\u00E1c.",
SafariNativeMMLWarning: "Tr\u00ECnh duy\u1EC7t c\u1EE7a b\u1EA1n h\u1ED7 tr\u1EE3 MathML g\u1ED1c nh\u01B0ng kh\u00F4ng h\u1ED7 tr\u1EE3 t\u1EA5t c\u1EA3 nh\u1EEFng t\u00EDnh n\u0103ng m\u00E0 MathJax s\u1EED d\u1EE5ng, n\u00EAn m\u1ED9t s\u1ED1 bi\u1EC3u th\u1EE9c c\u00F3 th\u1EC3 hi\u1EC3n th\u1ECB kh\u00F4ng ch\u00EDnh x\u00E1c.",
FirefoxNativeMMLWarning: "Tr\u00ECnh duy\u1EC7t c\u1EE7a b\u1EA1n h\u1ED7 tr\u1EE3 MathML g\u1ED1c nh\u01B0ng kh\u00F4ng h\u1ED7 tr\u1EE3 t\u1EA5t c\u1EA3 nh\u1EEFng t\u00EDnh n\u0103ng m\u00E0 MathJax s\u1EED d\u1EE5ng, n\u00EAn m\u1ED9t s\u1ED1 bi\u1EC3u th\u1EE9c c\u00F3 th\u1EC3 hi\u1EC3n th\u1ECB kh\u00F4ng ch\u00EDnh x\u00E1c.",
MSIESVGWarning: "SVG kh\u00F4ng \u0111\u01B0\u1EE3c h\u1ED7 tr\u1EE3 trong Internet Explorer tr\u01B0\u1EDBc IE9 ho\u1EB7c khi gi\u1EA3 l\u1EADp IE8 tr\u1EDF xu\u1ED1ng. Vi\u1EC7c k\u00EDch ho\u1EA1t ch\u1EBF \u0111\u1ED9 hi\u1EC3n th\u1ECB SVG s\u1EBD l\u00E0m cho c\u00E1c to\u00E1n hi\u1EC3n th\u1ECB kh\u00F4ng ch\u00EDnh x\u00E1c.",
LoadURL: "T\u1EA3i d\u1EEF li\u1EC7u bi\u00EAn d\u1ECBch t\u1EEB URL n\u00E0y:",
BadURL: "URL ph\u1EA3i d\u1EABn \u0111\u1EBFn m\u1ED9t t\u1EADp tin JavaScript \u0111\u1ECBnh r\u00F5 d\u1EEF li\u1EC7u bi\u00EAn d\u1ECBch MathJax. C\u00E1c t\u00EAn t\u1EADp tin JavaScript ph\u1EA3i c\u00F3 \u201C.js\u201D \u0111\u1EB1ng sau.",
BadData: "Th\u1EA5t b\u1EA1i khi t\u1EA3i d\u1EEF li\u1EC7u bi\u00EAn d\u1ECBch t\u1EEB %1",
SwitchAnyway: "C\u1EE9 k\u00EDch ho\u1EA1t ch\u1EBF \u0111\u1ED9 k\u1EBFt xu\u1EA5t n\u00E0y?\n\n(B\u1EA5m OK \u0111\u1EC3 k\u00EDch ho\u1EA1t, ho\u1EB7c Cancel \u0111\u1EC3 ti\u1EBFp t\u1EE5c s\u1EED d\u1EE5ng ch\u1EBF \u0111\u1ED9 k\u1EBFt xu\u1EA5t hi\u1EC7n t\u1EA1i.)",
ScaleMath: "Ph\u00F3ng to t\u1EA5t c\u1EA3 to\u00E1n (so v\u1EDBi v\u0103n b\u1EA3n n\u1EB1m chung quanh) b\u1EB1ng t\u1EF7 l\u1EC7:",
NonZeroScale: "T\u1EF7 l\u1EC7 ph\u1EA3i kh\u00F4ng 0",
PercentScale: "T\u1EF7 l\u1EC7 ph\u1EA3i l\u00E0 s\u1ED1 ph\u1EA7n tr\u0103m (th\u00ED d\u1EE5 120%%)",
IE8warning: "Tr\u00ECnh \u0111\u01A1n MathJax v\u00E0 t\u00EDnh n\u0103ng ph\u00F3ng to s\u1EBD kh\u00F4ng c\u00F2n ho\u1EA1t \u0111\u1ED9ng. B\u1EA1n v\u1EABn c\u00F3 th\u1EC3 b\u1EA5m gi\u1EEF Alt v\u00E0 nh\u1EA5n chu\u1ED9t v\u00E0o m\u1ED9t bi\u1EC3u th\u1EE9c \u0111\u1EC3 m\u1EDF tr\u00ECnh \u0111\u01A1n MathJax thay th\u1EBF.\n\nB\u1EA1n c\u00F3 ch\u1EAFc ch\u1EAFn mu\u1ED1n thay \u0111\u1ED5i t\u00F9y ch\u1ECDn MathPlayer?",
IE9warning: "Tr\u00ECnh \u0111\u01A1n ng\u1EEF c\u1EA3nh MathJax s\u1EBD b\u1ECB v\u00F4 hi\u1EC7u, nh\u01B0ng b\u1EA1n c\u00F3 th\u1EC3 b\u1EA5m gi\u1EEF Alt v\u00E0 nh\u1EA5n chu\u1ED9t v\u00E0o m\u1ED9t bi\u1EC3u th\u1EE9c \u0111\u1EC3 m\u1EDF tr\u00ECnh \u0111\u01A1n MathJax thay th\u1EBF.",
NoOriginalForm: "H\u00ECnh th\u1EE9c g\u1ED1c kh\u00F4ng c\u00F3 s\u1EB5n",
Close: "\u0110\u00F3ng",
EqSource: "M\u00E3 ngu\u1ED3n C\u00F4ng th\u1EE9c MathJax",
CloseAboutDialog: "\u0110\u00F3ng h\u1ED9p tho\u1EA1i gi\u1EDBi thi\u1EC7u v\u1EC1 MathJax",
FastPreview: "Xem tr\u01B0\u1EDBc nhanh",
AssistiveMML: "MathML tr\u1EE3 n\u0103ng",
InTabOrder: "Bao g\u1ED3m trong th\u1EE9 t\u1EF1 Tab"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/vi/MathMenu.js");
|
angular.module("umbraco").controller("UmbracoForms.RenderTypes.FileController",
function($scope){
var imageExts = ['jpg','jpeg','png','gif','bmp'];
$scope.files = $scope.field.replace('~', '').split(',');
$scope.isImage = function(filepath){
return imageExts.indexOf( $scope.getExtension(filepath) ) >= 0;
};
$scope.getExtension = function(filepath){
return filepath.substring(filepath.lastIndexOf(".")+1).toLowerCase();
};
$scope.getFileName = function(filepath){
return filepath.substring(filepath.lastIndexOf("/")+1);
};
$scope.getPreview = function(filepath){
return filepath.replace('~','') + "?width=400";
};
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.DocumentMapperController",
function ($scope, $routeParams,pickerResource) {
if (!$scope.setting.value) {
} else {
var value = JSON.parse($scope.setting.value);
$scope.doctype = value.doctype;
$scope.nameField = value.nameField;
$scope.nameStaticValue = value.nameStaticValue;
$scope.properties = value.properties;
}
pickerResource.getAllDocumentTypesWithAlias().then(function (response) {
$scope.doctypes = response.data;
});
pickerResource.getAllFields($routeParams.id).then(function (response) {
$scope.fields = response.data;
});
$scope.setDocType = function() {
pickerResource.getAllProperties($scope.doctype).then(function (response) {
$scope.properties = response.data;
});
};
$scope.setValue = function() {
var val = {};
val.doctype = $scope.doctype;
val.nameField = $scope.nameField;
val.nameStaticValue = $scope.nameStaticValue;
val.properties = $scope.properties;
$scope.setting.value = JSON.stringify(val);
};
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.FieldMapperController",
function ($scope, $routeParams, pickerResource) {
function init() {
if (!$scope.setting.value) {
$scope.mappings = [];
} else {
$scope.mappings = JSON.parse($scope.setting.value);
}
var formId = $routeParams.id;
if(formId === -1 && $scope.model && $scope.model.fields) {
} else {
pickerResource.getAllFields($routeParams.id).then(function (response) {
$scope.fields = response.data;
});
}
}
$scope.addMapping = function() {
$scope.mappings.push({
alias: "",
value: "",
staticValue: ""
});
};
$scope.deleteMapping = function(index) {
$scope.mappings.splice(index, 1);
$scope.setting.value = JSON.stringify($scope.mappings);
};
$scope.stringifyValue = function() {
$scope.setting.value = JSON.stringify($scope.mappings);
};
init();
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.File",
function ($scope, dialogService, utilityService) {
var umbracoVersion = Umbraco.Sys.ServerVariables.application.version;
$scope.openMediaPicker = function() {
var compareOptions = {
zeroExtend: true
};
var versionCompare = utilityService.compareVersions(umbracoVersion, "7.4", compareOptions);
if(versionCompare === 0 || versionCompare === 1) {
$scope.mediaPickerOverlay = {
view: "mediapicker",
show: true,
submit: function(model) {
var selectedImage = model.selectedImages[0];
populateFile(selectedImage);
$scope.mediaPickerOverlay.show = false;
$scope.mediaPickerOverlay = null;
}
};
} else {
dialogService.mediaPicker({ callback: populateFile });
}
};
function populateFile(item) {
//From the picked media item - get the 'umbracoFile' property
//Previously we was assuming the first property was umbracoFile but if user adds custom propeties then it may not be the first
//Rather than a for loop, use underscore.js
var umbracoFileProp = _.findWhere(item.properties, {alias: "umbracoFile"});
$scope.setting.value = umbracoFileProp.value;
}
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.Pickers.ConnectionStringController",
function ($scope, $routeParams, pickerResource) {
pickerResource.getAllConnectionStrings().then(function (response) {
$scope.strings = response.data;
});
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.Pickers.ContentController",
function ($scope, $routeParams, dialogService, entityResource, iconHelper) {
if (!$scope.setting) {
$scope.setting = {};
}
var val = parseInt($scope.setting.value);
if (!isNaN(val) && angular.isNumber(val)) {
//node
$scope.showQuery = false;
entityResource.getById($scope.setting.value, "Document").then(function (item) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.node = item;
});
}
$scope.openContentPicker = function () {
var d = dialogService.treePicker({
section: "content",
treeAlias: "content",
multiPicker: false,
callback: populate
});
};
$scope.clear = function () {
$scope.id = undefined;
$scope.node = undefined;
$scope.setting.value = undefined;
};
function populate(item) {
$scope.clear();
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.node = item;
$scope.id = item.id;
$scope.setting.value = item.id;
}
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.Pickers.ContentWithXpathController",
function ($scope, $routeParams, dialogService, entityResource, iconHelper, utilityService) {
var umbracoVersion = Umbraco.Sys.ServerVariables.application.version;
$scope.queryIsVisible = false;
$scope.helpIsVisible = false;
$scope.query = "";
if (!$scope.setting) {
$scope.setting = {};
}
function init() {
if(angular.isNumber($scope.setting.value)){
entityResource.getById($scope.setting.value, "Document").then(function (item) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.node = item;
});
} else if($scope.setting.value) {
$scope.queryIsVisible = true;
$scope.query = $scope.setting.value;
}
}
$scope.openContentPicker = function () {
var compareOptions = {
zeroExtend: true
};
var versionCompare = utilityService.compareVersions(umbracoVersion, "7.4", compareOptions);
if(versionCompare === 0 || versionCompare === 1) {
$scope.treePickerOverlay = {
view: "treepicker",
section: "content",
treeAlias: "content",
multiPicker: false,
title: "Where to save",
subtitle: "Choose location to save this node",
hideSubmitButton: true,
show: true,
submit: function(model) {
var selectedItem = model.selection[0];
populate(selectedItem);
$scope.treePickerOverlay.show = false;
$scope.treePickerOverlay = null;
}
};
} else {
var d = dialogService.treePicker({
section: "content",
treeAlias: "content",
multiPicker: false,
callback: populate
});
}
};
$scope.showQuery = function() {
$scope.queryIsVisible = true;
};
$scope.toggleHelp = function() {
$scope.helpIsVisible = !$scope.helpIsVisible;
};
$scope.setXpath = function() {
$scope.setting.value = $scope.query;
};
$scope.clear = function () {
$scope.id = undefined;
$scope.node = undefined;
$scope.setting.value = undefined;
$scope.query = undefined;
$scope.queryIsVisible = false;
};
function populate(item) {
$scope.clear();
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
$scope.node = item;
$scope.id = item.id;
$scope.setting.value = item.id;
}
init();
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.Pickers.DataTypeController",
function ($scope, $routeParams, pickerResource) {
pickerResource.getAllDataTypes().then(function (response) {
$scope.datatypes = response.data;
});
});
angular.module("umbraco").controller("UmbracoForms.SettingTypes.Pickers.DocumentTypeController",
function ($scope, $routeParams, pickerResource) {
pickerResource.getAllDocumentTypesWithAlias().then(function (response) {
$scope.doctypes = response.data;
});
});
angular.module("umbraco")
.controller("UmbracoForms.Dashboards.ActivityController",
function ($scope, recordResource) {
//var filter = {};
//recordResource.getRecords(filter).then(function(response){
// $scope.records = response.data;
//});
});
angular.module("umbraco")
.controller("UmbracoForms.Dashboards.LicensingController",
function ($scope, $location, $routeParams, $cookieStore, formResource, licensingResource, updatesResource, notificationsService, userService, utilityService) {
$scope.overlay = {
show: false,
title: "Congratulations",
description: "You've just installed Umbraco Forms - Let's create your first form"
};
var packageInstall = $cookieStore.get("umbPackageInstallId");
if (packageInstall) {
$scope.overlay.show = true;
$cookieStore.put("umbPackageInstallId", "");
}
//if not initial install, but still do not have forms
if (!$scope.overlay.show) {
formResource.getOverView().then(function (response) {
if (response.data.length === 0) {
$scope.overlay.show = true;
$scope.overlay.title = "Create a form";
$scope.overlay.description = "You do not have any forms setup yet, how about creating one now?";
}
});
}
$scope.getLicenses = function (config) {
$scope.loginError = false;
$scope.hasLicenses = undefined;
licensingResource.getAvailableLicenses(config).then(function (response) {
var licenses = response.data;
var currentDomain = window.location.hostname;
$scope.hasLicenses = licenses.length > 0;
_.each(licenses, function (lic) {
if (lic.bindings && lic.bindings.indexOf(currentDomain) >= 0) {
lic.currentDomainMatch = true;
}
});
$scope.configuredLicenses = _.filter(licenses, function (license) { return license.configured; });
$scope.openLicenses = _.filter(licenses, function (license) { return license.configured === false; });
}, function (err) {
$scope.loginError = true;
$scope.hasLicenses = undefined;
});
};
$scope.configure = function (config) {
licensingResource.configureLicense(config).then(function (response) {
$scope.configuredLicenses.length = 0;
$scope.openLicenses.length = 0;
$scope.loadStatus();
notificationsService.success("License configured", "Umbraco forms have been configured to be used on this website");
});
};
$scope.loadStatus = function () {
licensingResource.getLicenseStatus().then(function (response) {
$scope.status = response.data;
});
//Get Current User - To Check if the user Type is Admin
userService.getCurrentUser().then(function (response) {
$scope.currentUser = response;
$scope.isAdminUser = response.userType.toLowerCase() === "admin";
});
updatesResource.getUpdateStatus().then(function (response) {
$scope.version = response.data;
});
updatesResource.getVersion().then(function (response) {
$scope.currentVersion = response.data;
});
};
$scope.upgrade = function () {
//Let's tripple check the user is of the userType Admin
if (!$scope.isAdminUser) {
//The user is not an admin & should have not hit this method but if they hack the UI they could potnetially see the UI perhaps?
notificationsService.error("Insufficient Permissions", "Only Admin users have the ability to upgrade Umbraco Forms");
return;
}
$scope.installing = true;
updatesResource.installLatest($scope.version.remoteVersion).then(function (response) {
window.location.reload();
}, function (reason) {
//Most likely the 403 Unauthorised back from server side
//The error is caught already & shows a notification so need to do it here
//But stop the loading bar from spinnging forever
$scope.installing = false;
});
};
$scope.create = function () {
//Get the current umbraco version we are using
var umbracoVersion = Umbraco.Sys.ServerVariables.application.version;
var compareOptions = {
zeroExtend: true
};
//Check what version of Umbraco we have is greater than 7.4 or not
//So we can load old or new editor UI
var versionCompare = utilityService.compareVersions(umbracoVersion, "7.4", compareOptions);
//If value is 0 then versions are an exact match
//If 1 then we are greater than 7.4.x
//If it's -1 then we are less than 7.4.x
if(versionCompare < 0) {
//I am less than 7.4 - load the legacy editor
$location.url("forms/form/edit-legacy/-1?template=&create=true");
}
else {
//I am 7.4 or newer - load in shiny new UI
$location.url("forms/form/edit/-1?template=&create=true");
}
};
$scope.configuration = { domain: window.location.hostname };
$scope.loadStatus();
});
angular.module("umbraco").controller("UmbracoForms.Dashboards.YourFormsController", function ($scope,$location, formResource, recordResource, userService, securityResource, utilityService) {
var vm = this;
vm.entriesUrl = 'entries';
//Get the current umbraco version we are using
var umbracoVersion = Umbraco.Sys.ServerVariables.application.version;
var compareOptions = {
zeroExtend: true
};
//Check what version of Umbraco we have is greater than 7.4 or not
//So we can load old or new editor UI
var versionCompare = utilityService.compareVersions(umbracoVersion, "7.4", compareOptions);
//If value is 0 then versions are an exact match
//If 1 then we are greater than 7.4.x
//If it's -1 then we are less than 7.4.x
if(versionCompare < 0) {
//I am less than 7.4 - load the legacy editor
vm.entriesUrl = 'entries-legacy';
}
vm.formsLimit = 4;
vm.showAll = function(){
vm.formsLimit = 50;
};
formResource.getOverView().then(function(response){
vm.forms = response.data;
_.each(vm.forms, function(form){
var filter = { form: form.id };
recordResource.getRecordsCount(filter).then(function(response){
form.entries = response.data.count;
});
});
});
});
angular.module("umbraco")
.controller("UmbracoForms.Editors.DataSource.DeleteController",
function ($scope, dataSourceResource, navigationService, treeService) {
$scope.delete = function (id) {
dataSourceResource.deleteByGuid(id).then(function () {
treeService.removeNode($scope.currentNode);
navigationService.hideNavigation();
});
};
$scope.cancelDelete = function () {
navigationService.hideNavigation();
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.DataSource.EditController", function ($scope, $routeParams, dataSourceResource, editorState, notificationsService, dialogService, navigationService, userService, securityResource) {
//On load/init of 'editing' a prevalue source then
//Let's check & get the current user's form security
var currentUserId = null;
userService.getCurrentUser().then(function (response) {
currentUserId = response.id;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUserId).then(function (response) {
$scope.security = response.data;
//Check if we have access to current form OR manage forms has been disabled
if (!$scope.security.userSecurity.manageDataSources) {
//Show error notification
notificationsService.error("Access Denied", "You do not have access to edit Datasources");
//Resync tree so that it's removed & hides
navigationService.syncTree({ tree: "datasource", path: ['-1'], forceReload: true, activate: false }).then(function (response) {
//Response object contains node object & activate bool
//Can then reload the root node -1 for this tree 'Forms Folder'
navigationService.reloadNode(response.node);
});
//Don't need to wire anything else up
return;
}
});
});
if ($routeParams.create) {
//we are creating so get an empty data type item
dataSourceResource.getScaffold().then(function (response) {
$scope.loaded = true;
$scope.dataSource = response.data;
dataSourceResource.getAllDataSourceTypesWithSettings()
.then(function (resp) {
$scope.types = resp.data;
});
//set a shared state
editorState.set($scope.form);
});
}
else {
//we are editing so get the content item from the server
dataSourceResource.getByGuid($routeParams.id)
.then(function (response) {
$scope.dataSource = response.data;
dataSourceResource.getAllDataSourceTypesWithSettings()
.then(function (resp) {
$scope.types = resp.data;
setTypeAndSettings();
$scope.loaded = true;
});
//set a shared state
editorState.set($scope.dataSource);
});
}
$scope.setType = function () {
setTypeAndSettings();
};
$scope.save = function () {
//set settings
$scope.dataSource.settings = {};
angular.forEach($scope.dataSource.$type.settings, function (setting) {
var key = setting.alias;
var value = setting.value;
$scope.dataSource.settings[key] = value;
});
//validate settings
dataSourceResource.validateSettings($scope.dataSource)
.then(function (response) {
$scope.errors = response.data;
if ($scope.errors.length > 0) {
$scope.dataSource.valid = false;
angular.forEach($scope.errors, function (error) {
notificationsService.error("Datasource failed to save", error.Message);
});
} else {
//save
dataSourceResource.save($scope.dataSource)
.then(function (response) {
$scope.dataSource = response.data;
//set a shared state
editorState.set($scope.dataSource);
setTypeAndSettings();
navigationService.syncTree({ tree: "datasource", path: [String($scope.dataSource.id)], forceReload: true });
notificationsService.success("Datasource saved", "");
$scope.dataSource.valid = true;
$scope.dataSourceForm.$dirty = false;
}, function (err) {
notificationsService.error("Datasource failed to save", "");
});
}
}, function (err) {
notificationsService.error("Datasource failed to save", "Please check if your settings are valid");
});
};
$scope.showWizard = function() {
dialogService.open({
template: "/app_plugins/UmbracoForms/Backoffice/Datasource/dialogs/wizard.html",
dataSourceId: $scope.dataSource.id
});
};
var setTypeAndSettings = function () {
$scope.dataSource.$type = _.where($scope.types, { id: $scope.dataSource.formDataSourceTypeId })[0];
//set settings
angular.forEach($scope.dataSource.settings, function (setting) {
for (var key in $scope.dataSource.settings) {
if ($scope.dataSource.settings.hasOwnProperty(key)) {
if (_.where($scope.dataSource.$type.settings, { alias: key }).length > 0) {
_.where($scope.dataSource.$type.settings, { alias: key })[0].value = $scope.dataSource.settings[key];
}
}
}
});
};
});
angular.module("umbraco")
.controller("UmbracoForms.Editors.DataSource.WizardController",
function ($scope, $routeParams, dataSourceWizardResource, navigationService, notificationsService, dialogService) {
$scope.currentStep = 1;
dataSourceWizardResource.getScaffold($scope.dialogOptions.dataSourceId).then(function (response) {
$scope.wizard = response.data;
$scope.hasPrimaryKeys = $scope.wizard.mappings.length != _.where($scope.wizard.mappings, { prevalueKeyField: null }).length;
dataSourceWizardResource.getAllFieldTypes()
.then(function (resp) {
$scope.fieldtypes = resp.data;
$scope.ready = true;
});
});
$scope.createForm = function() {
dataSourceWizardResource.createForm($scope.wizard)
.then(function (resp) {
dialogService.closeAll();
notificationsService.success("Form created", "");
});
};
$scope.gotoStep = function (step) {
$scope.currentStep = step;
}
$scope.gotoThirdStep = function() {
if ($scope.hasPrimaryKeys) {
$scope.currentStep = 3;
} else {
$scope.currentStep = 4;
}
}
$scope.goBackToThirdStep = function() {
if ($scope.hasPrimaryKeys) {
$scope.currentStep = 3;
} else {
$scope.currentStep = 2;
}
}
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.CopyController",function ($scope, formResource, navigationService) {
//Copy Function run from button on click
$scope.copyForm = function (formId) {
//Perform copy in formResource
formResource.copy(formId, $scope.newFormName).then(function (response) {
var newFormId = response.data.id;
//Reload the tree (but do NOT mark the new item in the tree as selected/active)
navigationService.syncTree({ tree: "form", path: ["-1", String(newFormId)], forceReload: true, activate: false });
//Once 200 OK then reload tree & hide copy dialog navigation
navigationService.hideNavigation();
});
};
//Cancel button - closes dialog
$scope.cancelCopy = function() {
navigationService.hideNavigation();
}
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.CreateController", function ($scope, $routeParams, formResource, editorState, notificationsService, utilityService) {
//Use the vm approach as opposed to $scope
var vm = this;
vm.editUrl = 'edit';
//Get the current umbraco version we are using
var umbracoVersion = Umbraco.Sys.ServerVariables.application.version;
var compareOptions = {
zeroExtend: true
};
//Check what version of Umbraco we have is greater than 7.4 or not
//So we can load old or new editor UI
var versionCompare = utilityService.compareVersions(umbracoVersion, "7.4", compareOptions);
//If value is 0 then versions are an exact match
//If 1 then we are greater than 7.4.x
//If it's -1 then we are less than 7.4.x
if(versionCompare < 0) {
//I am less than 7.4 - load the legacy editor
vm.editUrl = 'edit-legacy';
}
formResource.getAllTemplates().then(function(response) {
vm.formTemplates = response.data;
});
});
angular.module("umbraco")
.controller("UmbracoForms.Editors.Form.DeleteController",
function ($scope, formResource, navigationService, treeService) {
$scope.delete = function (id) {
formResource.deleteByGuid(id).then(function () {
treeService.removeNode($scope.currentNode);
navigationService.hideNavigation();
});
};
$scope.cancelDelete = function () {
navigationService.hideNavigation();
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.EditController",
function ($scope, $routeParams, formResource, editorState, dialogService, formService, notificationsService, contentEditingHelper, formHelper, navigationService, userService, securityResource, localizationService, workflowResource) {
//On load/init of 'editing' a form then
//Let's check & get the current user's form security
var currentUserId = null;
var currentFormSecurity = null;
//By default set to have access (in case we do not find the current user's per indivudal form security item)
$scope.hasAccessToCurrentForm = true;
$scope.displayEditor = true;
$scope.page = {};
$scope.page.navigation = [
{
"name": localizationService.localize("general_design"),
"icon": "icon-document-dashed-line",
"view": "/App_Plugins/UmbracoForms/Backoffice/Form/views/design/design.html",
"active": true
},
{
"name": "Settings",
"icon": "icon-settings",
"view": "/App_Plugins/UmbracoForms/Backoffice/Form/views/settings/settings.html"
}];
userService.getCurrentUser().then(function (response) {
currentUserId = response.id;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUserId).then(function (response) {
$scope.security = response.data;
//Use _underscore.js to find a single item in the JSON array formsSecurity
//where the FORM guid matches the one we are currently editing (if underscore does not find an item it returns an empty array)
//As _.findWhere not in Umb .1.6 using _.where() that lists multiple matches - checking that we have only item in the array (ie one match)
currentFormSecurity = _.where(response.data.formsSecurity, { Form: $routeParams.id });
if (currentFormSecurity.length === 1) {
//Check & set if we have access to the form
//if we have no entry in the JSON array by default its set to true (so won't prevent)
$scope.hasAccessToCurrentForm = currentFormSecurity[0].HasAccess;
}
//Check if we have access to current form OR manage forms has been disabled
if (!$scope.hasAccessToCurrentForm || !$scope.security.userSecurity.manageForms) {
//Show error notification
notificationsService.error("Access Denied", "You do not have access to edit this form");
//Resync tree so that it's removed & hides
navigationService.syncTree({ tree: "form", path: ['-1'], forceReload: true, activate: false }).then(function(response) {
//Response object contains node object & activate bool
//Can then reload the root node -1 for this tree 'Forms Folder'
navigationService.reloadNode(response.node);
});
//Don't need to wire anything else up
return;
}
});
});
if ($routeParams.create) {
//we are creating so get an empty data type item
//formResource.getScaffold($routeParams.template)
formResource.getScaffoldWithWorkflows($routeParams.template)
.then(function(response) {
$scope.form = response.data;
//set a shared state
editorState.set($scope.form);
});
} else {
$scope.workflowsUrl = "#/forms/form/workflows/" +$routeParams.id;
$scope.entriesUrl = "#/forms/form/entries/" +$routeParams.id;
//we are editing so get the content item from the server
formResource.getWithWorkflowsByGuid($routeParams.id)
.then(function (response) {
//As we are editing an item we can highlight it in the tree
navigationService.syncTree({ tree: "form", path: [String($routeParams.id)], forceReload: false });
$scope.form = response.data;
$scope.saved = true;
// this should be removed in next major version
angular.forEach($scope.form.pages, function(page){
angular.forEach(page.fieldSets, function(fieldSet){
angular.forEach(fieldSet.containers, function(container){
angular.forEach(container.fields, function(field){
field.removePrevalueEditor = true;
});
});
});
});
//set a shared state
editorState.set($scope.form);
}, function(reason) {
//Includes ExceptionMessage, StackTrace etc from the WebAPI
var jsonErrorResponse = reason.data;
//Show notification message, a sticky Error message
notificationsService.add({ headline: "Unable to load form", message: jsonErrorResponse.ExceptionMessage, type: 'error', sticky: true });
//Hide the entire form UI
$scope.displayEditor = false;
});
}
$scope.editForm = function(form, section){
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/formsettings.html",
form: form,
section: section,
page: $scope.currentPage
});
};
$scope.save = function(){
if (formHelper.submitForm({ scope: $scope })) {
$scope.page.saveButtonState = "busy";
//make sure we set correct widths on all containers
formService.syncContainerWidths($scope.form);
formResource.saveWithWorkflows($scope.form).then(function (response) {
formHelper.resetForm({ scope: $scope });
contentEditingHelper.handleSuccessfulSave({
scope: $scope,
savedContent: response.data
});
$scope.ready = true;
//set a shared state
editorState.set($scope.form);
$scope.page.saveButtonState = "success";
navigationService.syncTree({ tree: "form", path: [String($scope.form.id)], forceReload: true });
notificationsService.success("Form saved", "");
}, function (err) {
contentEditingHelper.handleSaveError({
redirectOnFailure: false,
err: err
});
$scope.page.saveButtonState = "error";
});
}
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.EditLegacyController",
function ($scope, $routeParams, formResource, editorState, dialogService, formService, notificationsService, contentEditingHelper, formHelper, navigationService, userService, securityResource) {
//On load/init of 'editing' a form then
//Let's check & get the current user's form security
var currentUserId = null;
var currentFormSecurity = null;
//By default set to have access (in case we do not find the current user's per indivudal form security item)
$scope.hasAccessToCurrentForm = true;
userService.getCurrentUser().then(function (response) {
currentUserId = response.id;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUserId).then(function (response) {
$scope.security = response.data;
//Use _underscore.js to find a single item in the JSON array formsSecurity
//where the FORM guid matches the one we are currently editing (if underscore does not find an item it returns an empty array)
//As _.findWhere not in Umb .1.6 using _.where() that lists multiple matches - checking that we have only item in the array (ie one match)
currentFormSecurity = _.where(response.data.formsSecurity, { Form: $routeParams.id });
if (currentFormSecurity.length === 1) {
//Check & set if we have access to the form
//if we have no entry in the JSON array by default its set to true (so won't prevent)
$scope.hasAccessToCurrentForm = currentFormSecurity[0].HasAccess;
}
//Check if we have access to current form OR manage forms has been disabled
if (!$scope.hasAccessToCurrentForm || !$scope.security.userSecurity.manageForms) {
//Show error notification
notificationsService.error("Access Denied", "You do not have access to edit this form");
//Resync tree so that it's removed & hides
navigationService.syncTree({ tree: "form", path: ['-1'], forceReload: true, activate: false }).then(function(response) {
//Response object contains node object & activate bool
//Can then reload the root node -1 for this tree 'Forms Folder'
navigationService.reloadNode(response.node);
});
//Don't need to wire anything else up
return;
}
});
});
if ($routeParams.create) {
//we are creating so get an empty data type item
formResource.getScaffold($routeParams.template)
.then(function(response) {
$scope.form = response.data;
$scope.currentPage = {};
formResource.getPrevalueSources()
.then(function(resp){
$scope.prevaluesources = resp.data;
});
formResource.getAllFieldTypesWithSettings()
.then(function (resp) {
$scope.fieldtypes = resp.data;
$scope.ready = true;
});
//set a shared state
editorState.set($scope.form);
});
} else {
$scope.workflowsUrl = "#/forms/form/workflows/" +$routeParams.id;
$scope.entriesUrl = "#/forms/form/entries/" +$routeParams.id;
//we are editing so get the content item from the server
formResource.getByGuid($routeParams.id)
.then(function (response) {
//As we are editing an item we can highlight it in the tree
navigationService.syncTree({ tree: "form", path: [String($routeParams.id)], forceReload: false });
$scope.form = response.data;
$scope.saved = true;
formResource.getPrevalueSources()
.then(function (resp) {
$scope.prevaluesources = resp.data;
});
formResource.getAllFieldTypesWithSettings()
.then(function (resp) {
$scope.fieldtypes = resp.data;
$scope.ready = true;
});
//set a shared state
editorState.set($scope.form);
});
}
$scope.editForm = function(form, section){
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/formsettings.html",
form: form,
section: section,
page: $scope.currentPage
});
};
$scope.save = function(){
if (formHelper.submitForm({ scope: $scope })) {
//make sure we set correct widths on all containers
formService.syncContainerWidths($scope.form);
formResource.save($scope.form).then(function (response) {
formHelper.resetForm({ scope: $scope });
contentEditingHelper.handleSuccessfulSave({
scope: $scope,
savedContent: response.data
});
$scope.ready = true;
//$scope.form = response.data;
//set a shared state
editorState.set($scope.form);
navigationService.syncTree({ tree: "form", path: [String($scope.form.id)], forceReload: true });
notificationsService.success("Form saved", "");
}, function (err) {
notificationsService.error("Form Failed to save", err.data.Message);
});
}
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.EntriesController", function ($scope, $routeParams, recordResource, formResource, dialogService, editorState, userService, securityResource, notificationsService, navigationService) {
//On load/init of 'editing' a form then
//Let's check & get the current user's form security
var currentUserId = null;
var currentFormSecurity = null;
var vm = this;
vm.pagination = {
pageNumber: 1,
totalPages:1
};
vm.allIsChecked = false;
vm.selectedEntry = {};
vm.showEntryDetails = false;
vm.userLocale = "";
vm.nextPage = nextPage;
vm.prevPage = prevPage;
vm.goToPageNumber = goToPageNumber;
vm.viewEntryDetails = viewEntryDetails;
vm.closeEntryDetails = closeEntryDetails;
vm.nextEntryDetails = nextEntryDetails;
vm.prevEntryDetails = prevEntryDetails;
vm.datePickerChange = datePickerChange;
vm.toggleRecordState = toggleRecordState;
vm.keyboardShortcutsOverview = [
{
"name": "Entry details",
"shortcuts": [
{
"description": "Next entry",
"keys": [
{
"key": "→"
}
]
},
{
"description": "Previous entry",
"keys": [
{
"key": "←"
}
]
},
{
"description": "Close details",
"keys": [
{
"key": "esc"
}
]
}
]
}
];
//By default set to have access (in case we do not find the current user's per indivudal form security item)
$scope.hasAccessToCurrentForm = true;
userService.getCurrentUser().then(function (response) {
currentUserId = response.id;
vm.userLocale = response.locale;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUserId).then(function (response) {
$scope.security = response.data;
//Use _underscore.js to find a single item in the JSON array formsSecurity
//where the FORM guid matches the one we are currently editing (if underscore does not find an item it returns undefinied)
currentFormSecurity = _.where(response.data.formsSecurity, { Form: $routeParams.id });
if (currentFormSecurity.length === 1) {
//Check & set if we have access to the form
//if we have no entry in the JSON array by default its set to true (so won't prevent)
$scope.hasAccessToCurrentForm = currentFormSecurity[0].HasAccess;
}
//Check if we have access to current form OR manage forms has been disabled
if (!$scope.hasAccessToCurrentForm || !$scope.security.userSecurity.manageForms) {
//Show error notification
notificationsService.error("Access Denied", "You do not have access to view this form's entries");
//Resync tree so that it's removed & hides
navigationService.syncTree({ tree: "form", path: ['-1'], forceReload: true, activate: false }).then(function (response) {
//Response object contains node object & activate bool
//Can then reload the root node -1 for this tree 'Forms Folder'
navigationService.reloadNode(response.node);
});
//Don't need to wire anything else up
return;
}
});
});
formResource.getByGuid($routeParams.id)
.then(function(response){
$scope.form = response.data;
$scope.loaded = true;
//As we are editing an item we can highlight it in the tree
navigationService.syncTree({ tree: "form", path: [String($routeParams.id), String($routeParams.id) + "_entries"], forceReload: false });
});
$scope.states = [
{
"name": "Approved",
"isChecked": true
},
{
"name": "Submitted",
"isChecked": true
}
];
$scope.filter = {
startIndex: 1, //Page Number
length: 20, //No per page
form: $routeParams.id,
sortBy: "created",
sortOrder: "descending",
states: ["Approved","Submitted"]
};
$scope.records = [];
//Default value
$scope.loading = false;
recordResource.getRecordSetActions().then(function(response){
$scope.recordSetActions = response.data;
$scope.recordActions = response.data;
});
$scope.toggleRecordStateSelection = function(recordState) {
var idx = $scope.filter.states.indexOf(recordState);
// is currently selected
if (idx > -1) {
$scope.filter.states.splice(idx, 1);
}
// is newly selected
else {
$scope.filter.states.push(recordState);
}
};
$scope.hiddenFields = [2];
$scope.toggleSelection = function toggleSelection(field) {
var idx = $scope.hiddenFields.indexOf(field);
// is currently selected
if (idx > -1) {
$scope.hiddenFields.splice(idx, 1);
}else {
$scope.hiddenFields.push(field);
}
};
$scope.edit = function(schema){
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/entriessettings.html",
schema: schema,
toggle: $scope.toggleSelection,
hiddenFields: $scope.hiddenFields,
filter: $scope.filter
});
};
$scope.viewdetail = function(schema, row, event){
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/entriesdetail.html",
schema: schema,
row: row,
hiddenFields: $scope.hiddenFields
});
if(event) {
event.stopPropagation();
}
};
//$scope.pagination = [];
function nextPage(pageNumber) {
$scope.filter.startIndex++;
$scope.loadRecords($scope.filter);
}
function prevPage(pageNumber) {
$scope.filter.startIndex--;
$scope.loadRecords($scope.filter);
}
function goToPageNumber(pageNumber) {
// do magic here
$scope.filter.startIndex = pageNumber;
$scope.loadRecords($scope.filter);
}
function viewEntryDetails(schema, entry, event) {
vm.selectedEntry = {};
var entryIndex = $scope.records.results.indexOf(entry);
// get the count of the entry across the pagination: entries pr page * page index + entry index
var entryCount = $scope.filter.length * ($scope.filter.startIndex - 1) + (entryIndex + 1);
vm.selectedEntry = entry;
vm.selectedEntry.index = entryIndex;
vm.selectedEntry.entryCount = entryCount;
vm.selectedEntry.details = [];
if(schema && entry){
for (var index = 0; index < schema.length; index++) {
var schemaItem = schema[index];
//Select the value from the entry.fields array
var valueItem = entry.fields[index];
//Create new object to push into details above (so our angular view is much neater)
var itemToPush = {
name: schemaItem.name,
value: valueItem,
viewName: schemaItem.view,
view: '/app_plugins/umbracoforms/Backoffice/common/rendertypes/' + schemaItem.view + '.html'
};
var excludeItems = ["member", "state", "created", "updated"];
var found = excludeItems.indexOf(schemaItem.id);
if(excludeItems.indexOf(schemaItem.id) === -1) {
vm.selectedEntry.details.push(itemToPush);
}
}
}
vm.showEntryDetails = true;
if(event) {
event.stopPropagation();
}
}
function closeEntryDetails() {
vm.selectedEntry = {};
vm.showEntryDetails = false;
}
function nextEntryDetails() {
// get the current index and plus 1 to get the next item in the array
var nextEntryIndex = vm.selectedEntry.index + 1;
var entriesCount = $scope.records.results.length;
var currentPage = $scope.filter.startIndex;
var totalNumberOfPages = $scope.records.totalNumberOfPages;
if(nextEntryIndex < entriesCount) {
var entry = $scope.records.results[nextEntryIndex];
viewEntryDetails($scope.records.schema, entry);
} else if( totalNumberOfPages > 1 && currentPage < totalNumberOfPages) {
$scope.filter.startIndex++;
vm.pagination.pageNumber++;
recordResource.getRecords($scope.filter).then(function(response){
$scope.records = response.data;
$scope.allIsChecked = ($scope.selectedRows.length >= $scope.records.results.length);
vm.pagination.totalPages = response.data.totalNumberOfPages;
limitRecordFields($scope.records);
// get the first item from the new collection
var entry = $scope.records.results[0];
viewEntryDetails($scope.records.schema, entry);
});
}
}
function prevEntryDetails() {
var prevEntryIndex = vm.selectedEntry.index - 1;
var totalNumberOfPages = $scope.records.totalNumberOfPages;
var currentPage = $scope.filter.startIndex;
if(vm.selectedEntry.index > 0) {
var entry = $scope.records.results[prevEntryIndex];
viewEntryDetails($scope.records.schema, entry);
} else if(totalNumberOfPages > 1 && currentPage !== 1) {
$scope.filter.startIndex--;
vm.pagination.pageNumber--;
recordResource.getRecords($scope.filter).then(function(response){
$scope.records = response.data;
$scope.allIsChecked = ($scope.selectedRows.length >= $scope.records.results.length);
vm.pagination.totalPages = response.data.totalNumberOfPages;
limitRecordFields($scope.records);
// get the last item from the new collection
var lastEntryIndex = $scope.records.results.length - 1;
var entry = $scope.records.results[lastEntryIndex];
viewEntryDetails($scope.records.schema, entry);
});
}
}
function datePickerChange(dateRange) {
$scope.filter.startDate = dateRange.startDate;
$scope.filter.endDate = dateRange.endDate;
$scope.filterChanged();
}
function toggleRecordState(recordState) {
if(recordState.isChecked) {
$scope.filter.states.push(recordState.name);
} else {
var index = $scope.filter.states.indexOf(recordState.name);
if(index !== -1) {
$scope.filter.states.splice(index, 1);
}
}
$scope.filterChanged();
}
$scope.next = function(){
$scope.filter.startIndex++;
};
$scope.prev = function(){
$scope.filter.startIndex--;
};
$scope.goToPage = function(index){
$scope.filter.startIndex = index;
};
$scope.search = _.debounce(function(resetIndex){
//Set loading to true
$scope.loading = true;
$scope.reset(resetIndex);
$scope.$apply(function(){
recordResource.getRecords($scope.filter).then(function(response){
//Got results back - set loading to false]
$scope.loading = false;
$scope.records = response.data;
vm.pagination.totalPages = response.data.totalNumberOfPages;
limitRecordFields($scope.records);
});
});
}, 300);
$scope.filterChanged = function() {
var resetIndex = true;
$scope.search(resetIndex);
};
$scope.loadRecords = function(filter, append){
//Set loading to true
$scope.loading = true;
recordResource.getRecords(filter).then(function(response){
//Got response from server
$scope.loading = false;
if(append){
$scope.records = $scope.records.results.concat(response.data.results);
}else{
$scope.records = response.data;
}
$scope.allIsChecked = ($scope.selectedRows.length >= $scope.records.results.length);
limitRecordFields($scope.records);
vm.pagination.totalPages = response.data.totalNumberOfPages;
});
};
$scope.loadRecords($scope.filter);
function limitRecordFields(records) {
// function to limit how many fields are
// shown in the entries table
var falseFromIndex = 2;
var falseToIndex = records.schema.length - 4;
var trueFalseArray = [];
// make array of true/false
angular.forEach(records.schema, function(schema, index){
if(index <= falseFromIndex || index >= falseToIndex) {
trueFalseArray.push(true);
} else {
trueFalseArray.push(false);
}
});
// set array for schema
records.showSchemaArray = trueFalseArray;
// set array for row fields
angular.forEach(records.results, function(result){
result.showRecordsArray = trueFalseArray;
});
}
$scope.reset = function(resetIndex){
$scope.selectedRows.length = 0;
$scope.allIsChecked = false;
if(resetIndex){
$scope.filter.startIndex = 1;
}
};
$scope.clearSelection = function() {
$scope.selectedRows.length = 0;
vm.allIsChecked = false;
for(var i = 0; i < $scope.records.results.length; i++) {
var row = $scope.records.results[i];
row.selected = false;
}
};
$scope.more = function(){
$scope.filter.startIndex++;
$scope.loadRecords($scope.filter, true);
};
$scope.selectedRows = [];
$scope.toggleRow = function(row) {
row.selected = !row.selected;
if(row.selected){
$scope.selectedRows.push(row.id);
$scope.allIsChecked = ($scope.selectedRows.length >= $scope.records.results.length);
}else{
var i = $scope.selectedRows.indexOf(row.id);
$scope.selectedRows.splice(i,1);
$scope.allIsChecked = false;
}
};
$scope.toggleRowLegacy = function(row){
if(row.selected){
$scope.selectedRows.push(row.id);
$scope.allIsChecked = ($scope.selectedRows.length >= $scope.records.results.length);
}else{
var i = $scope.selectedRows.indexOf(row.id);
$scope.selectedRows.splice(i,1);
$scope.allIsChecked = false;
}
};
$scope.allIsChecked = false;
$scope.toggleAllLegacy = function($event){
var checkbox = $event.target;
$scope.selectedRows.length = 0;
for (var i = 0; i < $scope.records.results.length; i++) {
var entity = $scope.records.results[i];
entity.selected = checkbox.checked;
if(checkbox.checked){
$scope.selectedRows.push(entity.id);
}
}
};
$scope.toggleAll = function(allIsChecked){
$scope.selectedRows.length = 0;
for (var i = 0; i < $scope.records.results.length; i++) {
var entity = $scope.records.results[i];
entity.selected = allIsChecked;
if(allIsChecked){
$scope.selectedRows.push(entity.id);
}
}
};
$scope.executeRecordSetAction = function (action) {
//Get the data we need in order to send to the API Endpoint
var model = {
formId: $scope.form.id,
recordKeys: $scope.selectedRows,
actionId: action.id
};
//Check if the action we are running requires a JS Confirm Box along with a message to be displayed
if (action.needsConfirm && action.confirmMessage.length > 0) {
//Display the confirm box with the confirmMessage
var result = confirm(action.confirmMessage);
if (!result) {
//The user clicked cancel
//Stop the rest of the function running
return;
}
}
//We do not need to show a confirm message so excute the action immediately
recordResource.executeRecordSetAction(model).then(function (response) {
$scope.reset(true);
$scope.loadRecords($scope.filter, false);
//Show success notification that action excuted
notificationsService.success("Excuted Action", "Successfully excuted action " + action.name);
}, function (err) {
//Error Function - so get an error response from API
notificationsService.error("Excuted Action", "Failed to excute action " + action.name + " due to error: " + err);
});
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.EntriesSettingsController",
function($scope, $log, $timeout, exportResource){
//The Form ID is found in the filter object we pass into the dialog
var formId = $scope.dialogOptions.filter.form;
exportResource.getExportTypes(formId).then(function(response){
$scope.exportTypes = response.data;
});
$scope.export = function(type, filter){
filter.exportType = type.id;
exportResource.generateExport(filter).then(function(response){
var url = exportResource.getExportUrl(response.data.formId, response.data.fileName);
var iframe = document.createElement('iframe');
iframe.id = "hiddenDownloadframe";
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.src= url;
//remove all traces
$timeout(function(){
document.body.removeChild(iframe);
}, 1000);
});
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.Dialogs.FieldsetSettingController",
function ($scope, formService, dialogService) {
$scope.deleteConditionRule = function(rules, rule) {
formService.deleteConditionRule(rules, rule);
};
$scope.addConditionRule = function (condition) {
formService.addConditionRule(condition);
};
$scope.close = function() {
dialogService.closeAll();
}
}
);
angular.module("umbraco").controller("UmbracoForms.Editors.Form.Dialogs.FieldSettingController",
function ($scope, formService, dialogService) {
$scope.deleteConditionRule = function(rules, rule) {
formService.deleteConditionRule(rules, rule);
};
$scope.addConditionRule = function (condition) {
formService.addConditionRule(condition);
};
$scope.getPrevalues = function (field) {
formService.loadFieldTypePrevalues(field);
};
$scope.close = function() {
$scope.dialogOptions.field.settings = {};
angular.forEach($scope.dialogOptions.field.$fieldType.settings, function (setting) {
var key = setting.alias;
var value = setting.value;
$scope.dialogOptions.field.settings[key] = value;
dialogService.closeAll();
});
}
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.WorkflowsController", function ($scope, $routeParams, workflowResource, editorState, dialogService, $window, userService, securityResource, notificationsService, navigationService) {
//On load/init of 'editing' a form then
//Let's check & get the current user's form security
var currentUserId = null;
var currentFormSecurity = null;
//By default set to have access (in case we do not find the current user's per indivudal form security item)
$scope.hasAccessToCurrentForm = true;
userService.getCurrentUser().then(function (response) {
currentUserId = response.id;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUserId).then(function (response) {
$scope.security = response.data;
//Use _underscore.js to find a single item in the JSON array formsSecurity
//where the FORM guid matches the one we are currently editing (if underscore does not find an item it returns undefinied)
currentFormSecurity = _.where(response.data.formsSecurity, { Form: $routeParams.id });
if (currentFormSecurity.length === 1) {
//Check & set if we have access to the form
//if we have no entry in the JSON array by default its set to true (so won't prevent)
$scope.hasAccessToCurrentForm = currentFormSecurity[0].HasAccess;
}
//Check if we have access to current form OR manage forms has been disabled
if (!$scope.hasAccessToCurrentForm || !$scope.security.userSecurity.manageWorkflows || !$scope.security.userSecurity.manageForms) {
//Show error notification
notificationsService.error("Access Denied", "You do not have access to edit this form's workflow");
//Resync tree so that it's removed & hides
navigationService.syncTree({ tree: "form", path: ['-1'], forceReload: true, activate: false }).then(function (response) {
//Response object contains node object & activate bool
//Can then reload the root node -1 for this tree 'Forms Folder'
navigationService.reloadNode(response.node);
});
//Don't need to wire anything else up
return;
}
});
});
workflowResource.getAllWorkflows($routeParams.id)
.then(function(resp) {
$scope.workflows = resp.data;
$scope.loaded = true;
//As we are editing an item we can highlight it in the tree
navigationService.syncTree({ tree: "form", path: [String($routeParams.id), String($routeParams.id) + "_workflows"], forceReload: true });
}, function(reason) {
//Includes ExceptionMessage, StackTrace etc from the WebAPI
var jsonErrorResponse = reason.data;
//Show notification message, a sticky Error message
notificationsService.add({ headline: "Unable to load form", message: jsonErrorResponse.ExceptionMessage, type: 'error', sticky: true });
//Hide the entire workflows UI
$scope.loaded = false;
});
$scope.sortableOptions = {
handle: '.handle',
cursor: "move",
connectWith: '.workflows',
update: function (e, ui) {
var wfGuids = [];
var wfcount = 0;
var state = ui.item.parent().attr("rel");
ui.item.parent().children().each(function () {
if ($(this).attr("rel") != null) {
wfGuids[wfcount] = $(this).attr("rel");
wfcount++;
}
});
workflowResource.updateSortOrder(state,wfGuids).then(function () {
});
},
};
$scope.deleteWorkflow = function (workflow) {
var deleteWorkflow = $window.confirm('Are you sure you want to delete the workflow?');
if (deleteWorkflow) {
workflowResource.deleteByGuid(workflow.id).then(function() {
$scope.workflows.splice($scope.workflows.indexOf(workflow), 1);
});
}
};
$scope.updateWorkflow = function(state, workflow) {
data = {};
data.workflow = workflow;
data.state = state;
data.form = $routeParams.id;
data.add = false;
dialogService.open({
template: '/app_plugins/UmbracoForms/Backoffice/Form/dialogs/workflow.html',
show: true,
callback: update,
dialogData: data,
workflows: $scope.workflows
});
};
$scope.addWorkflow = function(state) {
data = {};
data.state = state;
data.form = $routeParams.id;
data.add = true;
dialogService.open({
template: '/app_plugins/UmbracoForms/Backoffice/Form/dialogs/workflow.html',
show: true,
callback: add,
dialogData: data
});
};
function add(data) {
$scope.workflows.push(data);
}
function update(data) {
}
});
angular.module("umbraco").controller("UmbracoForms.Editors.Form.Dialogs.WorkflowsController",
function ($scope, $routeParams, workflowResource, dialogService, notificationsService, $window) {
if ($scope.dialogData.workflow) {
//edit
$scope.workflow = $scope.dialogData.workflow;
workflowResource.getAllWorkflowTypesWithSettings()
.then(function (resp) {
$scope.types = resp.data;
setTypeAndSettings();
});
//workflowResource.getByGuid($scope.dialogData.workflow)
//.then(function (response) {
// $scope.workflow = response.data;
// workflowResource.getAllWorkflowTypesWithSettings()
// .then(function (resp) {
// $scope.types = resp.data;
// setTypeAndSettings();
// });
//});
} else {
//create
workflowResource.getScaffold()
.then(function(response) {
$scope.loaded = true;
$scope.workflow = response.data;
$scope.workflow.executesOn = $scope.dialogData.state;
$scope.workflow.form = $scope.dialogData.form;
$scope.workflow.active = true;
workflowResource.getAllWorkflowTypesWithSettings()
.then(function(resp) {
$scope.types = resp.data;
});
});
}
$scope.setType = function () {
setTypeAndSettings();
};
$scope.close = function () {
dialogService.closeAll();
};
$scope.add = function () {
save();
};
$scope.update = function () {
save();
};
$scope.delete = function() {
var deleteWorkflow = $window.confirm('Are you sure you want to delete the workflow?');
if (deleteWorkflow) {
workflowResource.deleteByGuid($scope.workflow.id).then(function () {
$scope.dialogOptions.workflows.splice($scope.dialogOptions.workflows.indexOf($scope.workflow), 1);
notificationsService.success("Workflow deleted", "");
//$scope.submit($scope.workflow);
dialogService.closeAll();
});
}
}
var save = function() {
//set settings
$scope.workflow.settings = {};
angular.forEach($scope.workflow.$type.settings, function (setting) {
var key = setting.alias;
var value = setting.value;
$scope.workflow.settings[key] = value;
});
//validate settings
workflowResource.validateSettings($scope.workflow)
.then(function (response) {
$scope.errors = response.data;
if ($scope.errors.length > 0) {
angular.forEach($scope.errors, function (error) {
notificationsService.error("Workflow failed to save", error.Message);
});
} else {
//save
workflowResource.save($scope.workflow)
.then(function (response) {
$scope.workflow = response.data;
setTypeAndSettings();
notificationsService.success("Workflow saved", "");
$scope.submit($scope.workflow);
dialogService.closeAll();
}, function (err) {
notificationsService.error("Workflow failed to save", "");
});
}
}, function (err) {
notificationsService.error("Workflow failed to save", "Please check if your settings are valid");
});
};
var setTypeAndSettings = function () {
$scope.workflow.$type = _.where($scope.types, { id: $scope.workflow.workflowTypeId })[0];
if (!$scope.workflow.name) {
$scope.workflow.name = $scope.workflow.$type.name;
}
//set settings
angular.forEach($scope.workflow.settings, function (setting) {
for (var key in $scope.workflow.settings) {
if ($scope.workflow.settings.hasOwnProperty(key)) {
if (_.where($scope.workflow.$type.settings, { alias: key }).length > 0) {
_.where($scope.workflow.$type.settings, { alias: key })[0].value = $scope.workflow.settings[key];
}
}
}
});
};
});
/**
* @ngdoc controller
* @name UmbracoForms.Overlays.FieldsetSettingsOverlay
* @function
*
* @description
* The controller for the Fieldset Settings dialog
*/
(function() {
"use strict";
function FieldsetSettingsOverlay($scope, formService) {
var vm = this;
vm.actionTypes = [];
vm.logicTypes = [];
vm.operators = [];
vm.deleteConditionRule = deleteConditionRule;
vm.addConditionRule = addConditionRule;
vm.conditionFieldSelected = conditionFieldSelected;
vm.addColumn = addColumn;
vm.removeColumn = removeColumn;
function init() {
vm.actionTypes = formService.getActionTypes();
vm.logicTypes = formService.getLogicTypes();
vm.operators = formService.getOperators();
if(!$scope.model.fieldset.condition) {
$scope.model.fieldset.condition = {};
$scope.model.fieldset.condition.actionType = vm.actionTypes[0].value;
$scope.model.fieldset.condition.logicType = vm.logicTypes[0].value;
}
}
function deleteConditionRule (rules, rule) {
formService.deleteConditionRule(rules, rule);
}
function addConditionRule(condition) {
formService.addEmptyConditionRule(condition);
// set default operator
var lastIndex = condition.rules.length - 1;
condition.rules[lastIndex].operator = vm.operators[0].value;
}
function conditionFieldSelected(selectedField, rule) {
formService.populateConditionRulePrevalues(selectedField, rule, $scope.model.fields);
}
function addColumn() {
var index = $scope.model.fieldset.containers.length;
formService.addContainer($scope.model.fieldset, index);
}
function removeColumn(container) {
formService.deleteContainer($scope.model.fieldset, container);
}
init();
}
angular.module("umbraco").controller("UmbracoForms.Overlays.FieldsetSettingsOverlay", FieldsetSettingsOverlay);
})();
/**
* @ngdoc controller
* @name UmbracoForms.Overlays.FieldSettingsOverlay
* @function
*
* @description
* The controller for the Field Settings dialog
*/
(function() {
"use strict";
function FieldSettingsOverlay($scope, localizationService, formService) {
var vm = this;
vm.showValidationPattern = false;
vm.focusOnPatternField = false;
vm.focusOnMandatoryField = false;
vm.selectedValidationType = {};
vm.actionTypes = [];
vm.logicTypes = [];
vm.operators = [];
vm.validationTypes = [{
"name": localizationService.localize("validation_validateAsEmail"),
"key": "email",
"pattern": "[a-zA-Z0-9_\.\+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-\.]+",
"enableEditing": true
}, {
"name": localizationService.localize("validation_validateAsNumber"),
"key": "number",
"pattern": "^[0-9]*$",
"enableEditing": true
}, {
"name": localizationService.localize("validation_validateAsUrl"),
"key": "url",
"pattern": "https?\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}",
"enableEditing": true
}, {
"name": localizationService.localize("validation_enterCustomValidation"),
"key": "custom",
"pattern": "",
"enableEditing": true
}];
vm.changeValidationType = changeValidationType;
vm.changeValidationPattern = changeValidationPattern;
vm.openFieldTypePickerOverlay = openFieldTypePickerOverlay;
vm.deleteConditionRule = deleteConditionRule;
vm.addConditionRule = addConditionRule;
vm.getPrevalues = getPrevalues;
vm.conditionFieldSelected = conditionFieldSelected;
function activate() {
vm.actionTypes = formService.getActionTypes();
vm.logicTypes = formService.getLogicTypes();
vm.operators = formService.getOperators();
if(!$scope.model.field.condition) {
$scope.model.field.condition = {};
$scope.model.field.condition.actionType = vm.actionTypes[0].value;
$scope.model.field.condition.logicType = vm.logicTypes[0].value;
}
matchValidationType();
}
function changeValidationPattern() {
matchValidationType();
}
function openFieldTypePickerOverlay(field) {
vm.focusOnMandatoryField = false;
vm.fieldTypePickerOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/fieldtypepicker/field-type-picker.html",
title: "Choose answer type",
hideSubmitButton: true,
show: true,
submit: function(model) {
formService.loadFieldTypeSettings(field, model.fieldType);
// this should be removed in next major version
field.removePrevalueEditor = true;
vm.fieldTypePickerOverlay.show = false;
vm.fieldTypePickerOverlay = null;
}
};
}
function matchValidationType() {
if ($scope.model.field.regex !== null && $scope.model.field.regex !== "" && $scope.model.field.regex !== undefined) {
var match = false;
// find and show if a match from the list has been chosen
angular.forEach(vm.validationTypes, function(validationType, index) {
if ($scope.model.field.regex === validationType.pattern) {
vm.selectedValidationType = validationType;
vm.showValidationPattern = true;
match = true;
}
});
// if there is no match - choose the custom validation option.
if (!match) {
angular.forEach(vm.validationTypes, function(validationType) {
if (validationType.key === "custom") {
vm.selectedValidationType = validationType;
vm.showValidationPattern = true;
}
});
}
}
}
function changeValidationType(selectedValidationType) {
if (selectedValidationType) {
$scope.model.field.regex = selectedValidationType.pattern;
vm.showValidationPattern = true;
// set focus on textarea
if (selectedValidationType.key === "custom") {
vm.focusOnPatternField = true;
}
} else {
$scope.model.field.regex = "";
vm.showValidationPattern = false;
}
}
function conditionFieldSelected(selectedField, rule) {
formService.populateConditionRulePrevalues(selectedField, rule, $scope.model.fields);
}
function deleteConditionRule (rules, rule) {
formService.deleteConditionRule(rules, rule);
}
function addConditionRule(condition) {
formService.addEmptyConditionRule(condition);
// set default operator
var lastIndex = condition.rules.length - 1;
condition.rules[lastIndex].operator = vm.operators[0].value;
}
function getPrevalues(field) {
formService.loadFieldTypePrevalues(field);
}
activate();
}
angular.module("umbraco").controller("UmbracoForms.Overlays.FieldSettingsOverlay", FieldSettingsOverlay);
})();
(function() {
"use strict";
function FieldTypePickerOverlayController($scope, formResource, formService) {
var vm = this;
vm.fieldTypes = [];
vm.searchTerm = "";
vm.pickFieldType = pickFieldType;
vm.filterItems = filterItems;
vm.showDetailsOverlay = showDetailsOverlay;
vm.hideDetailsOverlay = hideDetailsOverlay;
function init() {
// get workflows with settings
formResource.getAllFieldTypesWithSettings()
.then(function (response) {
vm.fieldTypes = response.data;
});
}
function pickFieldType(selectedFieldType) {
$scope.model.fieldType = selectedFieldType;
$scope.model.submit($scope.model);
}
function filterItems() {
// clear item details
$scope.model.itemDetails = null;
}
function showDetailsOverlay(workflowType) {
var workflowDetails = {};
workflowDetails.icon = workflowType.icon;
workflowDetails.title = workflowType.name;
workflowDetails.description = workflowType.description;
$scope.model.itemDetails = workflowDetails;
}
function hideDetailsOverlay() {
$scope.model.itemDetails = null;
}
init();
}
angular.module("umbraco").controller("UmbracoForms.Overlays.FieldTypePickerOverlayController", FieldTypePickerOverlayController);
})();
(function () {
"use strict";
function WorkflowSettingsOverlayController($scope, workflowResource) {
var vm = this;
vm.workflowTypes = [];
vm.focusWorkflowName = true;
if($scope.model.workflowType && $scope.model.workflowType.id) {
workflowResource.getScaffoldWorkflowType($scope.model.workflowType.id).then(function(response){
$scope.model.workflow = response.data;
});
}
}
angular.module("umbraco").controller("UmbracoForms.Overlays.WorkflowSettingsOverlayController", WorkflowSettingsOverlayController);
})();
(function () {
"use strict";
function WorkflowsOverviewOverlayController($scope, workflowResource, notificationsService) {
var vm = this;
// massive hack to fix submit when pressing enter
vm.focusOverlay = true;
vm.openWorkflowsTypesOverlay = openWorkflowsTypesOverlay;
vm.editWorkflow = editWorkflow;
vm.removeWorkflow = removeWorkflow;
vm.editSubmitMessageWorkflow = editSubmitMessageWorkflow;
vm.workflowsSortableOptions = {
distance: 10,
tolerance: "pointer",
connectWith: ".umb-forms-workflows__sortable-wrapper",
opacity: 0.7,
scroll: true,
cursor: "move",
zIndex: 6000,
handle: ".sortable-handle",
items: ".sortable",
placeholder: "umb-forms-workflow__workflow-placeholder",
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
},
stop: function(event, ui) {
updateSortOrder($scope.model.formWorkflows.onSubmit);
updateSortOrder($scope.model.formWorkflows.onApprove);
}
};
function updateSortOrder(array) {
var sortOrder = 0;
for(var i = 0; i < array.length; i++) {
var arrayItem = array[i];
if(arrayItem.isDeleted === false) {
arrayItem.sortOrder = sortOrder;
sortOrder++;
}
}
}
function openWorkflowsTypesOverlay(workflowArray) {
// set overlay settings and open overlay
vm.workflowsTypesOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/workflow-types.html",
title: "Choose workflow",
fields: $scope.model.fields,
hideSubmitButton: true,
show: true,
submit: function(model) {
// set sortOrder
workflowArray.push(model.workflow);
updateSortOrder(workflowArray);
vm.workflowsTypesOverlay.show = false;
vm.workflowsTypesOverlay = null;
}
};
}
function editWorkflow(workflow) {
vm.workflowSettingsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/workflow-settings.html",
title: workflow.name,
workflow: workflow,
fields: $scope.model.fields,
show: true,
submit: function(model) {
//Validate settings
workflowResource.validateWorkflowSettings(model.workflow).then(function(response){
if (response.data.length > 0) {
angular.forEach(response.data, function (error) {
notificationsService.error("Workflow failed to save", error.Message);
});
} else {
vm.workflowSettingsOverlay.show = false;
vm.workflowSettingsOverlay = null;
}
});
}
};
}
function editSubmitMessageWorkflow() {
vm.submitMessageWorkflowOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/submit-message-workflow-settings.html",
title: "Message on submit",
messageOnSubmit: $scope.model.messageOnSubmit,
goToPageOnSubmit: $scope.model.goToPageOnSubmit,
show: true,
submit: function(model) {
$scope.model.messageOnSubmit = model.messageOnSubmit;
$scope.model.goToPageOnSubmit = model.goToPageOnSubmit;
vm.submitMessageWorkflowOverlay.show = false;
vm.submitMessageWorkflowOverlay = null;
}
};
}
function removeWorkflow(workflow, event, workflowTypeArray) {
workflow.isDeleted = true;
updateSortOrder(workflowTypeArray);
event.stopPropagation();
}
}
angular.module("umbraco").controller("UmbracoForms.Overlays.WorkflowsOverviewOverlayController", WorkflowsOverviewOverlayController);
})();
(function() {
"use strict";
function WorkflowTypesOverlayController($scope, workflowResource, notificationsService) {
var vm = this;
vm.workflowTypes = [];
vm.searchTerm = "";
vm.pickWorkflowType = pickWorkflowType;
vm.filterItems = filterItems;
vm.showDetailsOverlay = showDetailsOverlay;
vm.hideDetailsOverlay = hideDetailsOverlay;
function init() {
// get workflows with settings
workflowResource.getAllWorkflowTypesWithSettings()
.then(function(response) {
vm.workflowTypes = response.data;
setDefaultWorkflowIcon(vm.workflowTypes);
});
}
function setDefaultWorkflowIcon(workflowTypes) {
for(var i = 0; i < workflowTypes.length; i++) {
var workflowType = workflowTypes[i];
if(!workflowType.icon) {
workflowType.icon = "icon-mindmap";
}
}
}
function pickWorkflowType(selectedWorkflowType) {
// set overlay settings + open overlay
vm.workflowSettingsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/workflow-settings.html",
title: selectedWorkflowType.name,
workflow: $scope.model.workflow,
workflowType: selectedWorkflowType,
fields: $scope.model.fields,
show: true,
submit: function(model) {
workflowResource.validateWorkflowSettings(model.workflow).then(function(response){
if (response.data.length > 0) {
angular.forEach(response.data, function (error) {
notificationsService.error("Workflow failed to save", error.Message);
});
} else {
//Need to add the properties to the $scope from this submitted model
$scope.model.workflow = model.workflow;
// submit overlay and return the model
$scope.model.submit($scope.model);
// close the overlay
vm.workflowSettingsOverlay.show = false;
vm.workflowSettingsOverlay = null;
}
});
}
};
}
function filterItems() {
// clear item details
$scope.model.itemDetails = null;
}
function showDetailsOverlay(workflowType) {
var workflowDetails = {};
workflowDetails.icon = workflowType.icon;
workflowDetails.title = workflowType.name;
workflowDetails.description = workflowType.description;
$scope.model.itemDetails = workflowDetails;
}
function hideDetailsOverlay() {
$scope.model.itemDetails = null;
}
init();
}
angular.module("umbraco").controller("UmbracoForms.Overlays.WorkflowTypesOverlayController", WorkflowTypesOverlayController);
})();
/**
* @ngdoc controller
* @name UmbracoForms.Editors.Form.FormDesignController
* @function
*
* @description
* The controller for the Umbraco Forns type editor
*/
(function () {
"use strict";
function formDesignController($scope, formResource, userService, securityResource) {
var vm = this;
var currentUser = {};
vm.currentPage = {};
vm.security = {};
//Get PreValues for the current form we are editing/designing
formResource.getPrevalueSources().then(function (resp) {
vm.prevaluesources = resp.data;
formResource.getAllFieldTypesWithSettings().then(function (resp) {
vm.fieldtypes = resp.data;
vm.ready = true;
});
});
userService.getCurrentUser().then(function (response) {
currentUser = response;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUser.id).then(function (response) {
vm.security = response.data;
});
});
}
angular.module("umbraco").controller("UmbracoForms.Editors.Form.FormDesignController", formDesignController);
})();
angular.module("umbraco").controller("UmbracoForms.Editors.Security.EditController", function ($scope, $routeParams, securityResource, notificationsService, navigationService) {
//Ensure the current item we are editing is highlighted in the tree
navigationService.syncTree({ tree: "formsecurity", path: [String($routeParams.id)], forceReload: true });
securityResource.getByUserId($routeParams.id).then(function (resp) {
$scope.security = resp.data;
$scope.loaded = true;
});
$scope.save = function () {
//Add a property to the object to save the Umbraco User ID taken from the routeParam
$scope.security.userSecurity.user = $routeParams.id;
securityResource.save($scope.security).then(function (response) {
$scope.userSecurity = response.data;
notificationsService.success("User's Form Security saved", "");
//SecurityForm is the name of the <form name='securitForm'>
//Set it back to Pristine after we save, so when we browse away we don't get the 'discard changes' notification
$scope.securityForm.$setPristine();
}, function (err) {
notificationsService.error("User's Form Security failed to save", "");
});
};
});
angular.module("umbraco")
.controller("UmbracoForms.Editors.PreValueSource.DeleteController",
function ($scope, preValueSourceResource, navigationService, treeService) {
$scope.delete = function (id) {
preValueSourceResource.deleteByGuid(id).then(function () {
treeService.removeNode($scope.currentNode);
navigationService.hideNavigation();
});
};
$scope.cancelDelete = function () {
navigationService.hideNavigation();
};
});
angular.module("umbraco").controller("UmbracoForms.Editors.PreValueSource.EditController", function ($scope, $routeParams, preValueSourceResource, editorState, notificationsService, navigationService, userService, securityResource) {
//On load/init of 'editing' a prevalue source then
//Let's check & get the current user's form security
var currentUserId = null;
userService.getCurrentUser().then(function (response) {
currentUserId = response.id;
//Now we can make a call to form securityResource
securityResource.getByUserId(currentUserId).then(function (response) {
$scope.security = response.data;
//Check if we have access to current form OR manage forms has been disabled
if (!$scope.security.userSecurity.managePreValueSources) {
//Show error notification
notificationsService.error("Access Denied", "You do not have access to edit Prevalue sources");
//Resync tree so that it's removed & hides
navigationService.syncTree({ tree: "prevaluesource", path: ['-1'], forceReload: true, activate: false }).then(function (response) {
//Response object contains node object & activate bool
//Can then reload the root node -1 for this tree 'Forms Folder'
navigationService.reloadNode(response.node);
});
//Don't need to wire anything else up
return;
}
});
});
if ($routeParams.create) {
//we are creating so get an empty data type item
preValueSourceResource.getScaffold()
.then(function (response) {
$scope.loaded = true;
$scope.preValueSource = response.data;
preValueSourceResource.getAllPreValueSourceTypesWithSettings()
.then(function (resp) {
$scope.types = resp.data;
});
//set a shared state
editorState.set($scope.form);
});
} else {
//we are editing so get the content item from the server
preValueSourceResource.getByGuid($routeParams.id)
.then(function (response) {
$scope.preValueSource = response.data;
preValueSourceResource.getAllPreValueSourceTypesWithSettings()
.then(function (resp) {
$scope.types = resp.data;
setTypeAndSettings();
getPrevalues();
$scope.loaded = true;
});
//As we are editing an item we can highlight it in the tree
navigationService.syncTree({ tree: "prevaluesource", path: [String($routeParams.id)], forceReload: false });
//set a shared state
editorState.set($scope.preValueSource);
});
}
$scope.setType = function () {
$scope.prevalues = null;
setTypeAndSettings();
};
$scope.save = function () {
//set settings
$scope.preValueSource.settings = {};
angular.forEach($scope.preValueSource.$type.settings, function (setting) {
var key = setting.alias;
var value = setting.value;
$scope.preValueSource.settings[key] = value;
});
//validate settings
preValueSourceResource.validateSettings($scope.preValueSource)
.then(function (response) {
$scope.errors = response.data;
if ($scope.errors.length > 0) {
angular.forEach($scope.errors, function(error) {
notificationsService.error("Prevaluesource failed to save", error.Message);
});
} else {
//save
preValueSourceResource.save($scope.preValueSource)
.then(function (response) {
$scope.preValueSource = response.data;
//set a shared state
editorState.set($scope.preValueSource);
setTypeAndSettings();
getPrevalues();
$scope.preValueSourceForm.$dirty = false;
navigationService.syncTree({ tree: "prevaluesource", path: [String($scope.preValueSource.id)], forceReload: true });
notificationsService.success("Prevaluesource saved", "");
}, function (err) {
notificationsService.error("Prevaluesource failed to save", "");
});
}
}, function (err) {
notificationsService.error("Prevaluesource failed to save", "Please check if your settings are valid");
});
};
var setTypeAndSettings = function() {
$scope.preValueSource.$type = _.where($scope.types, { id: $scope.preValueSource.fieldPreValueSourceTypeId })[0];
//set settings
angular.forEach($scope.preValueSource.settings, function (setting) {
for (var key in $scope.preValueSource.settings) {
if ($scope.preValueSource.settings.hasOwnProperty(key)) {
if (_.where($scope.preValueSource.$type.settings, { alias: key }).length > 0) {
_.where($scope.preValueSource.$type.settings, { alias: key })[0].value = $scope.preValueSource.settings[key];
}
}
}
});
};
var getPrevalues = function() {
preValueSourceResource.getPreValues($scope.preValueSource)
.then(function (response) {
$scope.prevalues = response.data;
});
};
});
angular.module("umbraco").controller("UmbracoForms.FormPickerController", function ($scope, $http, formResource) {
//Used to minipulate the Form Object we get back into the simpler form object needed here
function massageFormDataObject(form) {
var fields = [];
var fieldSummary = '';
//Not sure how to get these fields without this ugly nested loop?
//For each page in the object
for (var pageIndex = 0; pageIndex < form.pages.length; pageIndex++) {
//For each page it will have one or more fieldsets nested
for (var fieldsetIndex = 0; fieldsetIndex < form.pages[pageIndex].fieldSets.length; fieldsetIndex++)
{
//for each fieldset it will have a container
for (var containerIndex = 0; containerIndex < form.pages[pageIndex].fieldSets[fieldsetIndex].containers.length; containerIndex++)
{
//For each container will have one or more fields
for (var fieldIndex = 0; fieldIndex < form.pages[pageIndex].fieldSets[fieldsetIndex].containers[containerIndex].fields.length; fieldIndex++)
{
var field = form.pages[pageIndex].fieldSets[fieldsetIndex].containers[containerIndex].fields[fieldIndex];
//Push the field we find into our new array of just fields only
fields.push(field);
}
}
}
}
//Build up field summary
//Example: Name, Age, Location, Left column and one additional fields
//Example: Name, Age Location and Left column
var currentFieldItem = null;
//Check that we have 4 fields or less
if (fields.length <= 4) {
//Loop over first 4 items in fields array
for (var i = 0; i < fields.length; i++) {
//Get the current field object in the loop out of array
currentFieldItem = fields[i];
//Set the string fieldSummary with the name of the field aka caption
//If we are not the last item in the array prefix with a comma
//Otherwise it's an 'and
if (i !== fields.length - 1) {
fieldSummary += currentFieldItem.caption;
if (i !== fields.length - 2) {
fieldSummary += ', ';
}
}
else {
fieldSummary += ' and ' + currentFieldItem.caption;
}
}
}
else {
//Loop over first four items & then append a count of the remaining fields we have
for (var x = 0; x < 4; x++) {
//Get the current field object in the loop out of array
currentFieldItem = fields[x];
//Set the string fieldSummary with the name of the field aka caption
fieldSummary += currentFieldItem.caption;
//If we are NOT the last item use a comma
//Otherwise it's a comma
if (x !== fields.length - 1) {
fieldSummary += ', ';
}
}
//
//More than 4 records use - Name, Age, Location, Left column and one additional fiels
//TODO: Need to use word numbers :'(
var countExtraFields = fields.length - 4;
fieldSummary += 'and ' + countExtraFields + ' additional fields';
}
var pages = form.pages.length;
var summary = pages + ' page form with ' + fields.length + ' fields';
return {
id: form.id,
name: form.name,
fields: fieldSummary,
summary: summary,
workflows: form.workflows.length
};
};
$scope.loading = true;
var selectedForm = null;
formResource.getOverView().then(function (response) {
$scope.forms = response.data;
$scope.loading = false;
//Only do this is we have a value saved
if ($scope.model.value) {
//Try & find picked form from 'model.value' that we save as a
//simple GUID out of the collection in forms with _underscore
selectedForm = _.where(response.data, { id: $scope.model.value });
if (selectedForm.length === 1) {
//Found the form from the API (means we currently have access to it)
$scope.pickedFormName = selectedForm[0].name;
} else {
//We have a GUID in model.value saved but it did not come back from the overview API response
//So this means we do not have access to it, but need to show the form name in the UI
//Go fetch that specific form by the GUID we have saved
formResource.getByGuid($scope.model.value).then(function (response) {
var form = response.data;
//Add the form to the collection of forms - change to same format as API response
//Push the item into the array/collection of forms so it can still be selected as a radio button option
var formToPush = massageFormDataObject(form);
$scope.forms.push(formToPush);
});
}
}
},
function (err) {
$scope.error = "An Error has occured while loading!";
$scope.loading = false;
});
$scope.clear = function () {
$scope.model.value = null;
}
});
function dataSourceResource($http) {
var apiRoot = "backoffice/UmbracoForms/DataSource/";
return {
getScaffold: function (template) {
return $http.get(apiRoot + "GetScaffold");
},
getByGuid: function (id) {
return $http.get(apiRoot + "GetByGuid?guid=" + id);
},
deleteByGuid: function (id) {
return $http.delete(apiRoot + "DeleteByGuid?guid=" + id);
},
save: function (preValueSource) {
return $http.post(apiRoot + "PostSave", preValueSource);
},
validateSettings: function (preValueSource) {
return $http.post(apiRoot + "ValidateSettings", preValueSource);
},
getAllDataSourceTypesWithSettings: function () {
return $http.get(apiRoot + "GetAllDataSourceTypesWithSettings");
}
};
}
angular.module('umbraco.resources').factory('dataSourceResource', dataSourceResource);
function dataSourceWizardResource($http) {
var apiRoot = "backoffice/UmbracoForms/DataSourceWizard/";
return {
getScaffold: function (id) {
return $http.get(apiRoot + "GetScaffold?guid=" + id);
},
getAllFieldTypes: function () {
return $http.get(apiRoot + "GetAllFieldTypes");
},
createForm: function (wizard) {
return $http.post(apiRoot + "CreateForm", wizard);
}
};
}
angular.module('umbraco.resources').factory('dataSourceWizardResource', dataSourceWizardResource);
/**
* @ngdoc service
* @name umbraco.resources.dashboardResource
* @description Handles loading the dashboard manifest
**/
function exportResource($http) {
//the factory object returned
var apiRoot = "backoffice/UmbracoForms/Export/";
return {
getExportTypes: function (formId) {
return $http.get(apiRoot + "GetExportTypes?formId=" + formId);
},
generateExport: function (config) {
return $http.post(apiRoot + "PostGenerateExport", config);
},
getExportUrl: function (formId, fileName) {
return apiRoot + "GetExport?formId=" + formId + "&fileName=" + fileName;
},
getExport: function (token) {
return $http.get(apiRoot + "GetExport?token=" + token);
}
};
}
angular.module('umbraco.resources').factory('exportResource', exportResource);
/**
* @ngdoc service
* @name umbraco.resources.dashboardResource
* @description Handles loading the dashboard manifest
**/
function formResource($http) {
//the factory object returned
var apiRoot = "backoffice/UmbracoForms/Form/";
return {
getScaffold: function (template) {
return $http.get(apiRoot + "GetScaffold?template=" + template);
},
getScaffoldWithWorkflows: function (template) {
return $http.get(apiRoot + "GetScaffoldWithWorkflows?template=" + template);
},
getAllTemplates: function () {
return $http.get(apiRoot + "GetFormTemplates");
},
getOverView : function(){
return $http.get(apiRoot + 'GetOverView');
},
getByGuid: function (id) {
return $http.get(apiRoot + "GetByGuid?guid=" + id);
},
getWithWorkflowsByGuid: function (id) {
return $http.get(apiRoot + "GetWithWorkflowsByGuid?guid=" + id);
},
deleteByGuid: function (id) {
return $http.delete(apiRoot + "DeleteByGuid?guid=" + id);
},
save: function (form) {
return $http.post(apiRoot + "PostSave", form);
},
saveWithWorkflows: function (formWithWorkflows) {
return $http.post(apiRoot + "SaveForm", formWithWorkflows);
},
getAllFieldTypes: function() {
return $http.get(apiRoot + "GetAllFieldTypes");
},
getAllFieldTypesWithSettings: function () {
return $http.get(apiRoot + "GetAllFieldTypesWithSettings");
},
getPrevalueSources: function() {
return $http.get(apiRoot + "GetPrevalueSources");
},
copy: function(id, newFormName) {
return $http.post(apiRoot + "CopyForm", { guid: id, newName: newFormName });
}
};
}
angular.module('umbraco.resources').factory('formResource', formResource);
/**
* @ngdoc service
* @name umbraco.resources.dashboardResource
* @description Handles loading the dashboard manifest
**/
function licensingResource($http) {
//the factory object returned
var apiRoot = "backoffice/UmbracoForms/Licensing/";
return {
getLicenseStatus: function () {
return $http.get(apiRoot + "GetLicenseStatus");
},
getAvailableLicenses: function (config) {
return $http.post(apiRoot + "PostRetriveAvailableLicenses", config);
},
configureLicense: function (config) {
return $http.post(apiRoot + "PostConfigureLicense", config);
}
};
}
angular.module('umbraco.resources').factory('licensingResource', licensingResource);
function pickerResource($http) {
var apiRoot = "backoffice/UmbracoForms/Picker/";
return {
getAllConnectionStrings: function () {
return $http.get(apiRoot + "GetAllConnectionStrings");
},
getAllDataTypes: function () {
return $http.get(apiRoot + "GetAllDataTypes");
},
getAllDocumentTypes: function () {
return $http.get(apiRoot + "GetAllDocumentTypes");
},
getAllDocumentTypesWithAlias: function () {
return $http.get(apiRoot + "GetAllDocumentTypesWithAlias");
},
getAllMediaTypes: function () {
return $http.get(apiRoot + "GetAllMediaTypes");
},
getAllFields: function (formGuid) {
return $http.get(apiRoot + "GetAllFields?formGuid="+formGuid);
},
getAllProperties: function (doctypeAlias) {
return $http.get(apiRoot + "GetAllProperties?doctypeAlias=" + doctypeAlias);
}
};
}
angular.module('umbraco.resources').factory('pickerResource', pickerResource);
function preValueSourceResource($http) {
var apiRoot = "backoffice/UmbracoForms/PreValueSource/";
return {
getScaffold: function (template) {
return $http.get(apiRoot + "GetScaffold");
},
getByGuid: function (id) {
return $http.get(apiRoot + "GetByGuid?guid=" + id);
},
deleteByGuid: function (id) {
return $http.delete(apiRoot + "DeleteByGuid?guid=" + id);
},
save: function (preValueSource) {
return $http.post(apiRoot + "PostSave", preValueSource);
},
validateSettings: function (preValueSource) {
return $http.post(apiRoot + "ValidateSettings", preValueSource);
},
getPreValues: function (preValueSource) {
return $http.post(apiRoot + "GetPreValues", preValueSource);
},
getPreValuesByGuid: function (preValueSourceId) {
return $http.get(apiRoot + "GetPreValuesByGuid?preValueSourceId=" + preValueSourceId);
},
getAllPreValueSourceTypesWithSettings: function () {
return $http.get(apiRoot + "GetAllPreValueSourceTypesWithSettings");
}
};
}
angular.module('umbraco.resources').factory('preValueSourceResource', preValueSourceResource);
/**
* @ngdoc service
* @name umbraco.resources.dashboardResource
* @description Handles loading the dashboard manifest
**/
function recordResource($http) {
//the factory object returned
var apiRoot = "backoffice/UmbracoForms/Record/";
return {
getRecords: function (filter) {
return $http.post(apiRoot + "PostRetriveRecords", filter);
},
getRecordsCount: function (filter) {
return $http.post(apiRoot + "PostRetriveRecordsCount", filter);
},
getRecordActions: function () {
return $http.get(apiRoot + "GetRecordActions");
},
getRecordSetActions: function () {
return $http.get(apiRoot + "GetRecordSetActions");
},
executeRecordSetAction : function(model){
return $http.post(apiRoot + "PostExecuteRecordSetAction", model);
}
};
}
angular.module('umbraco.resources').factory('recordResource', recordResource);
function securityResource($http) {
var apiRoot = "backoffice/UmbracoForms/FormSecurity/";
return {
getByUserId: function (userId) {
return $http.get(apiRoot + "GetByUserId?userId=" + userId);
},
save: function (userSecurity) {
return $http.post(apiRoot + "PostSave", userSecurity);
}
};
}
angular.module('umbraco.resources').factory('securityResource', securityResource);
/**
* @ngdoc service
* @name umbraco.resources.dashboardResource
* @description Handles loading the dashboard manifest
**/
function updatesResource($http) {
//the factory object returned
var apiRoot = "backoffice/UmbracoForms/Updates/";
return {
getUpdateStatus: function () {
return $http.get(apiRoot + "GetUpdateStatus");
},
installLatest: function (version) {
return $http.get(apiRoot + "InstallLatest?version=" + version);
},
getVersion: function() {
return $http.get(apiRoot + "GetVersion");
}
};
}
angular.module('umbraco.resources').factory('updatesResource', updatesResource);
function workflowResource($http) {
var apiRoot = "backoffice/UmbracoForms/Workflow/";
return {
getScaffold: function (template) {
return $http.get(apiRoot + "GetScaffold");
},
getByGuid: function (id) {
return $http.get(apiRoot + "GetByGuid?guid=" + id);
},
deleteByGuid: function (id) {
return $http.delete(apiRoot + "DeleteByGuid?guid=" + id);
},
save: function (preValueSource) {
return $http.post(apiRoot + "PostSave", preValueSource);
},
validateSettings: function (preValueSource) {
return $http.post(apiRoot + "ValidateSettings", preValueSource);
},
getAllWorkflowTypesWithSettings: function () {
return $http.get(apiRoot + "GetAllWorkflowTypesWithSettings");
},
getAllWorkflows: function (formGuid) {
return $http.get(apiRoot + "GetAllWorkflows?formGuid=" + formGuid);
},
updateSortOrder: function (state, workflowIds) {
var data = {};
data.state = state;
data.guids = workflowIds;
return $http.post(apiRoot + "UpdateSortOrder", data);
},
getScaffoldWorkflowType: function(workflowTypeId){
return $http.get(apiRoot + "GetScaffoldWorkflowType?workflowTypeId="+ workflowTypeId);
},
validateWorkflowSettings: function(workflowViewModel){
return $http.post(apiRoot + "ValidateWorkflowSettings", workflowViewModel);
}
};
}
angular.module('umbraco.resources').factory('workflowResource', workflowResource);
angular.module("umbraco.directives")
.directive('umbFormsAutoFocus', function($timeout) {
return function(scope, element, attr){
var update = function() {
//if it uses its default naming
if(element.val().indexOf(" field") >= 0){
element.focus();
}
};
$timeout(function() {
update();
});
scope.$watch(attr.umbFormsFocusOn, function (_focusVal) {
$timeout(function () {
if (_focusVal) {
element.focus();
element.select();
update();
}
});
});
};
});
angular.module("umbraco.directives")
.directive('umbFormsAutoSize', function($timeout) {
return function(scope, element, attr){
var domEl = element[0];
var update = function(force) {
if(force === true){
element.height(0);
}
if(domEl.scrollHeight !== domEl.clientHeight){
element.height(domEl.scrollHeight);
}
};
element.bind('keyup keydown keypress change', update);
element.bind('blur', function(){ update(true); });
$timeout(function() {
update();
});
};
});
angular.module("umbraco.directives")
.directive('umbFormsContentPicker', function (dialogService, entityResource, iconHelper) {
return {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-content-picker.html',
require: "ngModel",
link: function (scope, element, attr, ctrl) {
ctrl.$render = function() {
var val = parseInt(ctrl.$viewValue);
if (!isNaN(val) && angular.isNumber(val) && val > 0) {
entityResource.getById(val, "Document").then(function(item) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
scope.node = item;
});
}
};
scope.openContentPicker = function () {
scope.contentPickerOverlay = {
view: "contentpicker",
show: true,
submit: function(model) {
populate(model.selection[0]);
scope.contentPickerOverlay.show = false;
scope.contentPickerOverlay = null;
}
};
};
scope.clear = function () {
scope.id = undefined;
scope.node = undefined;
updateModel(0);
};
function populate(item) {
scope.clear();
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
scope.node = item;
scope.id = item.id;
updateModel(item.id);
}
function updateModel(id) {
ctrl.$setViewValue(id);
}
}
};
});
angular.module("umbraco.directives").directive('umbFormsDateRangePicker', function (assetsService, userService) {
return {
restrict: 'A',
scope: {
userLocale: "@",
onChange: "="
},
template: '<div class="daterange daterange--double"></div>',
link: function (scope, element) {
assetsService.load([
"/App_Plugins/UmbracoForms/Assets/moment/min/moment-with-locales.min.js",
"/App_Plugins/UmbracoForms/Assets/BaremetricsCalendar/public/js/calendar.js"
])
.then(function () {
//Set the moment locale to the current user's locale
//Used for display, we still grab the date as YYYY-MM-DD to send to API endpoint
moment.locale(scope.userLocale);
var dd = new Calendar({
element: $(".daterange--double"),
earliest_date: 'January 1, 2000',
latest_date: moment(),
start_date: moment().subtract(29, 'days'),
end_date: moment(),
same_day_range: true,
callback: function () {
//Date update/changed
//Parse the dates from this component to Moment dates
var start = moment(this.start_date);
var end = moment(this.end_date);
var dateFilter = {};
dateFilter.startDate = start.format('YYYY-MM-DD');
dateFilter.endDate = end.format('YYYY-MM-DD');
if(scope.onChange) {
scope.onChange(dateFilter);
}
}
});
});
//Load CSS as dependancy
//load the seperate css for the editor to avoid it blocking our js loading
assetsService.loadCss("/App_Plugins/UmbracoForms/Assets/BaremetricsCalendar/public/css/application.css");
}
};
});
angular.module("umbraco.directives")
.directive('ufDelayedMouseleave', function ($timeout, $parse) {
return {
restrict: 'A',
link: function (scope, element, attrs, ctrl) {
var active = false;
var fn = $parse(attrs.ufDelayedMouseleave);
element.on("mouseleave", function(event) {
var callback = function() {
fn(scope, {$event:event});
};
active = false;
$timeout(function(){
if(active === false){
scope.$apply(callback);
}
}, 650);
});
element.on("mouseenter", function(event, args){
active = true;
});
}
};
});
angular.module("umbraco.directives")
.directive('umbFormsDesigner', function (dialogService, formService) {
return {
scope: {
form: "=",
fieldtypes: "=",
prevaluesources: "="
},
transclude: true,
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-designer.html',
link: function (scope, element, attrs, ctrl) {
// *********************************************
// Form management functions
// *********************************************
scope.initForm = function(form, fieldtypes){
formService.initForm(form, fieldtypes);
scope.gotoPageIndex(0);
};
// *********************************************
// Page management functions
// *********************************************
scope.gotoPageIndex = function(index){
scope.form.$currentPage = scope.form.pages[index];
scope.currentPageIndex = index;
scope.onFirstPage = scope.currentPageIndex === 0;
scope.onLastPage = scope.currentPageIndex === scope.form.pages.length-1;
};
scope.addPage = function (form) {
scope.closeItemOverlay();
formService.addPage(form);
scope.gotoPageIndex(form.pages.length -1);
};
scope.deletePage = function (page) {
var index = scope.form.pages.indexOf(page);
scope.form.pages.splice(index, 1);
if (index > 0) {
scope.currentPageIndex = index - 1;
scope.form.$currentPage = scope.form.pages[index - 1];
} else {
scope.currentPageIndex = 0;
scope.form.$currentPage = scope.form.pages[0];
}
scope.onFirstPage = scope.currentPageIndex === 0;
scope.onLastPage = scope.currentPageIndex === scope.form.pages.length - 1;
populateFields();
};
// *********************************************
// Fieldset management functions
// *********************************************
scope.setCurrentFieldset = function (fieldset) {
scope.currentFieldset = fieldset;
};
scope.addFieldset = function(page, fieldset, container, index){
scope.closeItemOverlay();
var _index = page.fieldSets.indexOf(fieldset);
formService.addFieldset(page, _index+1);
};
scope.deleteFieldset = function(page,fieldset) {
formService.deleteFieldset(page, fieldset);
};
scope.editFieldset = function (fieldset) {
populateFields();
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/fieldsetsettings.html",
fieldset: fieldset,
fields: scope.fields
});
};
// *********************************************
// Container management functions
// *********************************************
scope.addContainer = function (fieldset, container, index) {
scope.closeItemOverlay();
var _index = fieldset.containers.indexOf(container);
formService.splitContainer(fieldset, container, _index+1);
};
// *********************************************
// Field management functions
// *********************************************
scope.initField = function(field){
if(field && !field.$fieldType){
formService.setFieldType(field,field.fieldTypeId);
}
};
scope.addField = function (container, fieldtype, index) {
scope.closeItemOverlay();
formService.addField(container, fieldtype, index+1);
};
scope.editField = function(field){
populateFields();
scope.setFieldType(field);
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/fieldsettings.html",
field: field,
fields: scope.fields,
setFieldType: formService.setFieldType,
fieldtypes: scope.fieldtypes,
prevaluesources: scope.prevaluesources
});
};
scope.deleteField = function(fieldset,container,field) {
formService.deleteField(fieldset,container,field);
};
scope.copyField = function (container, field) {
var copy ={};
angular.copy(field, copy);
copy.id = generateGUID();
copy.caption = "copy of " + copy.caption;
container.fields.splice(container.fields.indexOf(field) + 1, 0, copy);
populateFields();
};
scope.setFieldType = function (field) {
//set settings
angular.forEach(field.settings, function (setting) {
for (var key in field.settings) {
if (field.settings.hasOwnProperty(key)) {
if (_.where(field.$fieldType.settings, { alias: key }).length > 0) {
_.where(field.$fieldType.settings, { alias: key })[0].value = field.settings[key];
}
}
}
});
};
// *********************************************
// Button/hover state handlers
// *********************************************
scope.setCurrentControl = function (field) {
scope.currentControl = field;
};
scope.setCurrentToolsControl = function (field) {
scope.currentToolsControl = field;
};
scope.setCurrentRemoveControl = function (Control) {
scope.currentRemoveControl = Control;
};
scope.setCurrentMoveControl = function (Control) {
scope.currentMoveControl = Control;
};
scope.setCurrentContainer = function (container) {
scope.currentContainer = container;
};
// *********************************************
// Field conditions
// *********************************************
scope.addConditionRule = function (condition) {
if (!condition.rules){
condition.rules = [];
}
condition.rules.push({
field: condition.$newrule.field,
operator: condition.$newrule.operator,
value: condition.$newrule.value
});
condition.$newrule.field = null;
condition.$newrule.operator = null;
condition.$newrule.value = null;
};
scope.deleteFieldConditionRule = function (rules, rule) {
var index = rules.indexOf(rule);
rules.splice(index, 1);
};
// *********************************************
// Sorting configurations
// *********************************************
scope.fieldSetSortableOptions = {
distance: 10,
cursor: "move",
placeholder: 'ui-sortable-placeholder',
handle: '.cell-tools-move',
connectWith: ".umb-forms-fieldsets"
};
scope.fieldSortableOptions = {
distance: 10,
cursor: "move",
placeholder: 'ui-sortable-placeholder',
handle: '.cell-tools-move',
connectWith: ".umb-forms-fields-container"
};
// *********************************************
// Add items overlay menu
// *********************************************
scope.overlayMenu = {
show: false,
style: {},
container: undefined,
fieldset: undefined
};
scope.addItemOverlay = function(sender, field, fieldset, container, index){
scope.overlayMenu.container = container;
scope.overlayMenu.fieldset = fieldset;
scope.overlayMenu.index = index;
scope.overlayMenu.style = {};
scope.overlayMenu.field = field;
//todo calculate position...
var offset = $(sender.target).offset();
var height = $(window).height();
var width = $(window).width();
if((height-offset.top) < 250){
scope.overlayMenu.style.bottom = 0;
scope.overlayMenu.style.top = "initial";
}else if(offset.top < 300){
scope.overlayMenu.style.top = 190;
}
scope.overlayMenu.show = true;
};
scope.closeItemOverlay = function(){
scope.overlayMenu.show = false;
scope.overlayMenu.field = undefined;
};
scope.adjustSize = function(ev){
if(ev.target.scrollHeight > ev.target.clientHeight){
$(ev.target).height(ev.target.scrollHeight);
}
};
// *********************************************
// Button functons
// *********************************************
scope.editForm = function (form, section) {
dialogService.closeAll();
dialogService.open(
{
template: "/app_plugins/UmbracoForms/Backoffice/Form/dialogs/formsettings.html",
form: form,
section: section,
page: scope.currentPage
});
};
// *********************************************
// Internal functons
// *********************************************
var populateFields = function() {
scope.fields = [];
angular.forEach(scope.form.pages, function(page) {
angular.forEach(page.fieldSets, function(fieldset) {
angular.forEach(fieldset.containers, function(container) {
angular.forEach(container.fields, function (field) {
scope.fields.push(field);
});
});
});
});
};
scope.initForm(scope.form, scope.fieldtypes);
}
};
});
angular.module("umbraco.directives")
.directive('umbFormsDesignerNew', function (dialogService, formService, workflowResource, notificationsService) {
return {
scope: {
form: "=",
fieldtypes: "=",
prevaluesources: "=",
security: "="
},
transclude: true,
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-designer-new.html',
link: function (scope, element, attrs, ctrl) {
scope.sortingMode = false;
scope.sortingButtonKey = "general_reorder";
// *********************************************
// Sorting management functions
// *********************************************
scope.sortablePages = {
distance: 10,
tolerance: "pointer",
opacity: 0.7,
scroll: true,
cursor: "move",
placeholder: "umb-forms__page-placeholder",
zIndex: 6000,
handle: ".sortable-handle",
items: ".sortable",
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
}
};
scope.sortableFieldsets = {
distance: 10,
tolerance: "pointer",
connectWith: ".umb-forms__fieldsets",
opacity: 0.7,
scroll: true,
cursor: "move",
placeholder: "umb-forms__fieldset-placeholder",
zIndex: 6000,
handle: ".sortable-handle",
items: ".sortable",
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
},
over: function(e, ui) {
scope.$apply(function () {
$(e.target).scope().page.dropOnEmpty = true;
});
},
out: function(e, ui) {
scope.$apply(function () {
$(e.target).scope().page.dropOnEmpty = false;
});
}
};
scope.sortableFields = {
distance: 10,
tolerance: "pointer",
connectWith: ".umb-forms__fields",
opacity: 0.7,
scroll: true,
cursor: "move",
placeholder: "umb-forms__field-placeholder",
zIndex: 6000,
handle: ".sortable-handle",
items: ".sortable",
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
},
over: function(e, ui) {
scope.$apply(function () {
$(e.target).scope().container.dropOnEmpty = true;
});
},
out: function(e, ui) {
scope.$apply(function () {
$(e.target).scope().container.dropOnEmpty = false;
});
}
};
scope.toggleSortingMode = function() {
scope.sortingMode = !scope.sortingMode;
if(scope.sortingMode) {
scope.sortingButtonKey = "general_reorderDone";
} else {
scope.sortingButtonKey = "general_reorder";
}
};
// *********************************************
// Form management functions
// *********************************************
scope.initForm = function(form, fieldtypes){
formService.initForm(form, fieldtypes);
};
// *********************************************
// Delete promt
// *********************************************
scope.togglePrompt = function(object) {
object.deletePrompt = !object.deletePrompt;
};
scope.hidePrompt = function(object) {
object.deletePrompt = false;
};
// *********************************************
// Page management functions
// *********************************************
scope.addPage = function (form) {
formService.addPage(form);
};
scope.removePage = function(pages, index) {
pages.splice(index, 1);
};
scope.formHasFields = function(form) {
var hasFields = false;
angular.forEach(scope.form.pages, function(page) {
angular.forEach(page.fieldSets, function(fieldset) {
angular.forEach(fieldset.containers, function(container) {
if(container.fields.length > 0) {
hasFields = true;
}
});
});
});
return hasFields;
};
scope.pageHasFields = function(page) {
var hasFields = false;
angular.forEach(page.fieldSets, function(fieldset) {
angular.forEach(fieldset.containers, function(container) {
if(container.fields.length > 0) {
hasFields = true;
}
});
});
return hasFields;
};
// *********************************************
// Fieldset management functions
// *********************************************
scope.addFieldset = function(page){
// always add it last
var _index = page.fieldSets.length;
formService.addFieldset(page, _index);
};
scope.removeFieldset = function(page, fieldset) {
formService.deleteFieldset(page, fieldset);
};
scope.editFieldset = function (fieldset) {
populateFields();
scope.fieldsetSettingsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/fieldsetsettings/fieldset-settings.html",
title: "Edit group",
fieldset: fieldset,
fields: scope.fields,
closeButtonLabel: "Cancel",
show: true,
submit: function(model) {
scope.fieldsetSettingsOverlay.show = false;
scope.fieldsetSettingsOverlay = null;
},
close: function(oldModel) {
fieldset.containers = oldModel.fieldset.containers;
fieldset.condition = oldModel.fieldset.condition;
scope.fieldsetSettingsOverlay.show = false;
scope.fieldsetSettingsOverlay = null;
}
};
};
// *********************************************
// Field management functions
// *********************************************
scope.addField = function(fieldset, container) {
populateFields();
var emptyField = formService.addEmptyField(container);
scope.fieldSettingsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/fieldsettings/field-settings.html",
title: "Add question",
field: emptyField,
fields: scope.fields,
prevalueSources: scope.prevaluesources,
show: true,
submit: function(model) {
emptyField.settings = {};
for (var i = 0; i < model.field.$fieldType.settings.length; i++) {
var setting = model.field.$fieldType.settings[i];
var key = setting.alias;
var value = setting.value;
emptyField.settings[key] = value;
}
scope.fieldSettingsOverlay.show = false;
scope.fieldSettingsOverlay = null;
},
close: function(oldModel) {
formService.deleteField(fieldset, container, emptyField);
scope.fieldSettingsOverlay.show = false;
scope.fieldSettingsOverlay = null;
}
};
};
scope.openFieldSettings = function(field){
populateFields();
scope.setFieldType(field);
scope.fieldSettingsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/fieldsettings/field-settings.html",
title: "Edit question",
field: field,
fields: scope.fields,
prevalueSources: scope.prevaluesources,
show: true,
submit: function(model) {
field.settings = {};
for (var i = 0; i < model.field.$fieldType.settings.length; i++) {
var setting = model.field.$fieldType.settings[i];
var key = setting.alias;
var value = setting.value;
field.settings[key] = value;
}
scope.fieldSettingsOverlay.show = false;
scope.fieldSettingsOverlay = null;
}
};
};
scope.removeField = function(fieldset,container,field) {
formService.deleteField(fieldset,container,field);
};
scope.setFieldType = function (field) {
//set settings
angular.forEach(field.settings, function (setting) {
for (var key in field.settings) {
if (field.settings.hasOwnProperty(key)) {
if (_.where(field.$fieldType.settings, { alias: key }).length > 0) {
_.where(field.$fieldType.settings, { alias: key })[0].value = field.settings[key];
}
}
}
});
};
// *********************************************
// Field conditions
// *********************************************
scope.getFieldNameFromGuid = function(selectedFieldId) {
populateFields();
for(var i = 0; i < scope.fields.length; i++) {
var field = scope.fields[i];
if(field.id === selectedFieldId) {
return field.caption;
}
}
};
// *********************************************
// Button functons
// *********************************************
scope.editWorkflows = function() {
if(scope.security && scope.security.userSecurity.manageWorkflows) {
populateFields();
scope.workflowsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/workflows-overview.html",
title: "Workflows",
formWorkflows: scope.form.formWorkflows,
messageOnSubmit: scope.form.messageOnSubmit,
goToPageOnSubmit: scope.form.goToPageOnSubmit,
submitLabel: scope.form.submitLabel,
manualApproval: scope.form.manualApproval,
fields: scope.fields,
closeButtonLabel: "Cancel",
show: true,
submit: function(model) {
scope.form.formWorkflows = model.formWorkflows;
scope.form.messageOnSubmit = model.messageOnSubmit;
scope.form.goToPageOnSubmit = model.goToPageOnSubmit;
scope.workflowsOverlay.show = false;
scope.workflowsOverlay = null;
},
close: function(oldModel) {
// reset the model
scope.form.formWorkflows = oldModel.formWorkflows;
scope.form.messageOnSubmit = oldModel.messageOnSubmit;
scope.form.goToPageOnSubmit = oldModel.goToPageOnSubmit;
scope.workflowsOverlay.show = false;
scope.workflowsOverlay = null;
}
};
}
};
scope.editWorkflowSettings = function(workflow) {
if(scope.security && scope.security.userSecurity.manageWorkflows) {
populateFields();
scope.workflowSettingsOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/workflow-settings.html",
workflow: workflow,
fields: scope.fields,
title: workflow.name,
show: true,
submit: function(model) {
//Validate settings
workflowResource.validateWorkflowSettings(model.workflow).then(function(response){
if (response.data.length > 0) {
angular.forEach(response.data, function (error) {
notificationsService.error("Workflow failed to save", error.Message);
});
} else {
scope.workflowSettingsOverlay.show = false;
scope.workflowSettingsOverlay = null;
}
});
}
};
}
};
scope.editSubmitMessageWorkflow = function() {
scope.submitMessageWorkflowOverlay = {
view: "/app_plugins/UmbracoForms/Backoffice/Form/overlays/workflows/submit-message-workflow-settings.html",
title: "Message on submit",
messageOnSubmit: scope.form.messageOnSubmit,
goToPageOnSubmit: scope.form.goToPageOnSubmit,
show: true,
submit: function(model) {
scope.form.messageOnSubmit = model.messageOnSubmit;
scope.form.goToPageOnSubmit = model.goToPageOnSubmit;
scope.submitMessageWorkflowOverlay.show = false;
scope.submitMessageWorkflowOverlay = null;
}
};
};
// *********************************************
// Internal functons
// *********************************************
var populateFields = function() {
scope.fields = [];
angular.forEach(scope.form.pages, function(page) {
angular.forEach(page.fieldSets, function(fieldset) {
angular.forEach(fieldset.containers, function(container) {
angular.forEach(container.fields, function (field) {
scope.fields.push(field);
});
});
});
});
};
scope.initForm(scope.form, scope.fieldtypes);
}
};
});
(function () {
'use strict';
function FormsEntryDetail() {
function link(scope, el, attr, ctrl) {
//console.log("from directive", scope.entry);
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-entry-detail.html',
scope: {
entry: '='
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbFormsEntryDetail', FormsEntryDetail);
})();
angular.module("umbraco.directives")
.directive('umbFormsInlinePrevalueEditor', function (notificationsService) {
return {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-inline-prevalue-editor.html',
require: "ngModel",
link: function (scope, element, attr, ctrl) {
scope.prevalues = [];
ctrl.$render = function () {
if (Object.prototype.toString.call(ctrl.$viewValue) === '[object Array]') {
scope.prevalues = ctrl.$viewValue;
}
};
function updateModel() {
ctrl.$setViewValue(scope.prevalues);
}
function addPrevalue() {
//Check that our array does not already contain the same item
if (scope.prevalues.indexOf(scope.newPrevalue) < 0) {
scope.prevalues.push(scope.newPrevalue);
scope.newPrevalue = '';
updateModel();
} else {
//Notify user they are trying to add a prevalue that already exists
notificationsService.error("PreValue Error", "Unable to add PreValue as this is a duplicate");
}
}
scope.addPrevalue = function () {
addPrevalue();
};
}
};
});
angular.module("umbraco.directives")
.directive('umbFormsLegacyContentPicker', function (dialogService, entityResource, iconHelper) {
return {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-legacy-content-picker.html',
require: "ngModel",
link: function (scope, element, attr, ctrl) {
ctrl.$render = function() {
var val = parseInt(ctrl.$viewValue);
if (!isNaN(val) && angular.isNumber(val) && val > 0) {
entityResource.getById(val, "Document").then(function(item) {
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
scope.node = item;
});
}
};
scope.openContentPicker = function () {
var d = dialogService.treePicker({
section: "content",
treeAlias: "content",
multiPicker: false,
callback: populate
});
};
scope.clear = function () {
scope.id = undefined;
scope.node = undefined;
updateModel(0);
};
function populate(item) {
scope.clear();
item.icon = iconHelper.convertFromLegacyIcon(item.icon);
scope.node = item;
scope.id = item.id;
updateModel(item.id);
}
function updateModel(id) {
ctrl.$setViewValue(id);
}
}
};
});
angular.module("umbraco.directives")
.directive('umbFormsOverlay', function () {
return {
restrict: 'A',
link: function (scope, el, attrs, ctrl) {
var margin = 50,
winHeight = $(window).height(),
calculate = _.throttle(function(){
if(el){
//detect bottom fold
var bottom_dif = (el.offset().top + el.height() + margin) - winHeight;
if(bottom_dif > 0){
$(el).css('margin-top', function (index, curValue) {
return parseInt(curValue, 10) - bottom_dif + 'px';
});
}else{
//else detect top fold
}
}
}, 1000);
//On resize, make sure to check the overlay
$(window).bind("resize", function () {
winHeight = $(window).height();
calculate();
});
}
};
});
angular.module("umbraco.directives")
.directive('umbFormsPrevalueEditor', function (notificationsService) {
return {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-prevalue-editor.html',
require: "ngModel",
link: function (scope, element, attr, ctrl) {
scope.prevalues = [];
ctrl.$render = function () {
if (Object.prototype.toString.call(ctrl.$viewValue) === '[object Array]') {
scope.prevalues = ctrl.$viewValue;
}
};
function updateModel() {
ctrl.$setViewValue(scope.prevalues);
}
scope.deletePrevalue = function (idx) {
scope.prevalues.splice(idx, 1);
updateModel();
};
scope.addPrevalue = function () {
//Check that our array does not already contain the same item
if (scope.prevalues.indexOf(scope.newPrevalue) < 0) {
scope.prevalues.push(scope.newPrevalue);
scope.newPrevalue = '';
updateModel();
} else {
//Notify user they are trying to add a prevalue that already exists
notificationsService.error("PreValue Error", "Unable to add PreValue as this is a duplicate");
}
};
}
};
});
(function () {
'use strict';
function FormsRenderType() {
var directive = {
restrict: 'E',
replace: true,
templateUrl: '/App_Plugins/UmbracoForms/directives/umb-forms-render-type.html',
scope: {
view: "=",
field: '='
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbFormsRenderType', FormsRenderType);
})();
function formService(preValueSourceResource) {
var generateGUID = function() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x7 | 0x8)).toString(16);
});
return uuid;
};
var service = {
fieldTypes: [],
actionTypes: [
{
name: "show",
value: "Show"
},
{
name: "hide",
value: "Hide"
}
],
logicTypes: [
{
name: "all",
value: "All"
},
{
name: "any",
value: "Any"
}
],
operators: [
{
name: "is",
value: "Is"
},
{
name: "is not",
value: "IsNot"
},
{
name: "is greater than",
value: "GreaterThen"
},
{
name: "is less than",
value: "LessThen"
},
{
name: "contains",
value: "Contains"
},
{
name: "starts with",
value: "StartsWith"
},
{
name: "ends with",
value: "EndsWith"
}
],
getActionTypes: function() {
return service.actionTypes;
},
getLogicTypes: function() {
return service.logicTypes;
},
getOperators: function() {
return service.operators;
},
initForm: function(form, fieldtypes){
service.fieldTypes = fieldtypes;
if(!form.pages || form.pages.length === 0){
service.addPage(form);
}else{
_.each(service.getAllFields(form), function(field){
if(!field.$fieldType){
service.setFieldType(field,field.fieldTypeId);
}
});
}
},
addPage: function(form, index){
var p = {caption: "", fieldSets: []};
service.addFieldset(p);
if(form.pages.length > index){
form.pages.splice(index, 0, p);
}else{
form.pages.push(p);
}
},
addFieldset: function(page, index){
var fs = {caption: "", containers: [], id:generateGUID()};
service.addContainer(fs);
if(page.fieldSets.length > index){
page.fieldSets.splice(index, 0, fs);
}else{
page.fieldSets.push(fs);
}
},
deleteFieldset : function(page, fieldset){
if(page.fieldSets.length > 1){
var index = page.fieldSets.indexOf(fieldset);
page.fieldSets.splice(index, 1);
}else{
fieldset.containers.length = 0;
service.addContainer(fieldset);
}
},
deleteFieldsetAtIndex : function(page, index){
if(page.fieldSets.length > 1){
page.fieldSets.splice(index, 1);
}else{
fieldset.containers.length = 0;
service.addContainer(fieldset);
}
},
splitFieldset: function(page, fieldset, container, splitAtIndex){
var newfieldset = {caption: "", containers: [{ caption: "", fields: [] }] };
var insertAt = page.fieldSets.indexOf(fieldset);
page.fieldSets.splice(insertAt+1, 0, newfieldset);
var oldFields = container.fields.slice(0,splitAtIndex+1);
var newFields = container.fields.slice(splitAtIndex+1);
newfieldset.containers[0].fields = newFields;
container.fields = oldFields;
},
addContainer: function(fieldset, index){
var c = { caption: "", fields: [] };
if(fieldset.containers.length > index){
fieldset.containers.splice(index, 0, c);
}else{
fieldset.containers.push(c);
}
},
splitContainer: function(fieldset, container, splitAtIndex){
var newContainer = { caption: "", fields: [] };
var insertAt = fieldset.containers.indexOf(container);
fieldset.containers.splice(insertAt-1, 0, newContainer);
var newFields = container.fields.slice(0,splitAtIndex+1);
var oldFields = container.fields.slice(splitAtIndex+1);
newContainer.fields = newFields;
container.fields = oldFields;
},
deleteContainer: function(fieldset, container){
//only delete the container if there are multiple ones on this fieldseet
//otherwise keep it and just clear its contents
if(fieldset.containers.length > 1){
var index = fieldset.containers.indexOf(container);
if(index >= 0){
service.deleteContainerAtIndex(fieldset, index);
}
}else{
container.fields.length = 0;
}
},
deleteContainerAtIndex: function(fieldset, index){
if(fieldset.containers.length > 1){
fieldset.containers.splice(index, 1);
}else{
fieldset.containers.length = 0;
}
},
syncContainerWidths : function(form){
_.each(form.pages, function(page){
_.each(page.fieldSets, function(fieldset){
var containers = fieldset.containers.length;
var avrg = Math.floor(12 / containers);
_.each(fieldset.containers, function(container){
container.width = avrg;
});
});
});
},
addField : function(container, fieldtype, index) {
var newField = {
caption: "",
id: generateGUID(),
settings: {},
preValues: [],
$focus: true
};
service.loadFieldTypeSettings(newField, fieldtype);
if(container.fields.length > index){
container.fields.splice(index, 0, newField);
}else{
container.fields.push(newField);
}
},
addEmptyField : function(container) {
var newField = {
caption: "",
id: generateGUID(),
settings: {},
preValues: [],
$focus: true
};
container.fields.push(newField);
return newField;
},
getAllFields : function(form){
var fields = [];
if(form.pages){
_.each(form.pages, function(page){
if(page.fieldSets){
_.each(page.fieldSets, function(fieldset){
if(fieldset.containers){
_.each(fieldset.containers, function(container){
if(container.fields){
_.each(container.fields, function(field){
fields.push(field);
});
}
});
}
});
}
});
}
return fields;
},
deleteField: function(fieldset,container,field){
var index = container.fields.indexOf(field);
if(index >= 0){
service.deleteFieldAtIndex(fieldset, container, index);
}
},
deleteFieldAtIndex: function(fieldset,container,index){
container.fields.splice(index, 1);
if(container.fields.length === 0){
service.deleteContainer(fieldset,container);
}
},
setFieldType: function(field, fieldTypeId){
//get field type
field.fieldTypeId = fieldTypeId;
var fldt = _.find(service.fieldTypes, function(ft){return ft.id === field.fieldTypeId; });
field.$fieldType = fldt;
service.loadFieldTypeSettings(field, field.$fieldType);
service.loadFieldTypePrevalues(field);
},
loadFieldTypePrevalues : function(field) {
if (field.prevalueSourceId !== null && field.prevalueSourceId !== "00000000-0000-0000-0000-000000000000") {
preValueSourceResource.getPreValuesByGuid(field.prevalueSourceId)
.then(function(response) {
field.$preValues = response.data;
});
} else {
field.$preValues = null;
}
},
loadFieldTypeSettings : function(field, fieldtype){
var stng = angular.copy(fieldtype.settings);
if(field.fieldTypeId !== fieldtype.id){
field.settings = {};
}
field.fieldTypeId = fieldtype.id;
field.$fieldType = fieldtype;
if(fieldtype.settings){
_.each(fieldtype.settings, function(setting){
if(!field.settings[setting.alias]){
field.settings[setting.alias] = "";
}
});
}
},
deleteConditionRule : function(rules, rule) {
var index = rules.indexOf(rule);
rules.splice(index, 1);
},
addConditionRule : function(condition) {
if (!condition.rules) {
condition.rules = [];
}
condition.rules.push({
field: condition.$newrule.field,
operator: condition.$newrule.operator,
value: condition.$newrule.value
});
},
addEmptyConditionRule : function(condition) {
if (!condition.rules) {
condition.rules = [];
}
condition.rules.push({
field: "",
operator: "",
value: ""
});
},
populateConditionRulePrevalues: function(selectedField, rule, fields) {
for(var i = 0; i < fields.length; i++) {
var field = fields[i];
if(field.id === selectedField) {
// prevalues and be stored in both $preValues and preValues
if(field.$preValues && field.$preValues.length > 0) {
rule.$preValues = field.$preValues;
} else if(field.preValues && field.preValues.length > 0) {
var rulePreValuesObjectArray = [];
// make prevalues to object array
for(var preValueIndex = 0; preValueIndex < field.preValues.length; preValueIndex++) {
var preValue = field.preValues[preValueIndex];
var preValueObject = {
value: preValue
};
rulePreValuesObjectArray.push(preValueObject);
}
rule.$preValues = rulePreValuesObjectArray;
} else {
rule.$preValues = null;
}
}
}
}
};
return service;
}
angular.module('umbraco.services').factory('formService', formService);
/**
* Compares two software version numbers (e.g. "1.7.1" or "1.2b").
*
*
* @param {string} v1 The first version to be compared.
* @param {string} v2 The second version to be compared.
* @param {object} [options] Optional flags that affect comparison behavior:
* <ul>
* <li>
* <tt>lexicographical: true</tt> compares each part of the version strings lexicographically instead of
* naturally; this allows suffixes such as "b" or "dev" but will cause "1.10" to be considered smaller than
* "1.2".
* </li>
* <li>
* <tt>zeroExtend: true</tt> changes the result if one version string has less parts than the other. In
* this case the shorter string will be padded with "zero" parts instead of being considered smaller.
* </li>
* </ul>
* @returns {number|NaN}
* <ul>
* <li>0 if the versions are equal</li>
* <li>a negative integer iff v1 < v2</li>
* <li>a positive integer iff v1 > v2</li>
* <li>NaN if either version string is in the wrong format</li>
* </ul>
*/
(function() {
'use strict';
function utilityService() {
function compareVersions(v1, v2, options) {
var lexicographical = options && options.lexicographical,
zeroExtend = options && options.zeroExtend,
v1parts = v1.split('.'),
v2parts = v2.split('.');
function isValidPart(x) {
return (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/).test(x);
}
if (!v1parts.every(isValidPart) || !v2parts.every(isValidPart)) {
return NaN;
}
if (zeroExtend) {
while (v1parts.length < v2parts.length) {
v1parts.push("0");
}
while (v2parts.length < v1parts.length) {
v2parts.push("0");
}
}
if (!lexicographical) {
v1parts = v1parts.map(Number);
v2parts = v2parts.map(Number);
}
for (var i = 0; i < v1parts.length; ++i) {
if (v2parts.length === i) {
return 1;
}
if (v1parts[i] === v2parts[i]) {
continue;
} else if (v1parts[i] > v2parts[i]) {
return 1;
} else {
return -1;
}
}
if (v1parts.length !== v2parts.length) {
return -1;
}
return 0;
}
var service = {
compareVersions: compareVersions
};
return service;
}
angular.module('umbraco.services').factory('utilityService', utilityService);
})();
angular.module('umbraco.filters').filter('truncate', function() {
return function(input, noOfChars, appendDots) {
//Check the length of the text we are filtering
//If its greater than noOfChars param
if(input.length > noOfChars){
//Trim the text to the length of the param
input = input.substr(0, noOfChars);
//Only append the dots if we truncated
//Append Dots is a bool
if(appendDots){
input = input + "...";
}
}
return input;
};
})
.filter('fileName', function() {
return function(input) {
// The input will be a path like so, we just want my-panda-photo.jpg
// /media/forms/upload/f2ab8761-6a75-4c9d-a281-92e5e508856a/my-panda-photo.jpg
input = input.split('\\').pop().split('/').pop();
return input;
};
});
|
import React, {Component} from 'react';
import {StyleSheet, View} from 'react-native';
import {TabView, Tab, Icon} from '@ui-kitten/components';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';
import LoginForm from '../../components/LoginForm';
import SignupForm from '../../components/SignupForm';
import Color from '../../constants/Color';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
class Login extends Component {
static navigationOptions = ({navigation}) => {
return {
title: 'Login',
header: null,
tabBarVisible: false,
};
};
state = {
selectedIndex: 0,
};
onSelect = (selectedIndex) => {
this.setState({selectedIndex});
};
renderLoginIcon = (style) => <Icon {...style} name="person-outline" />;
renderSignupIcon = (style) => <Icon {...style} name="person-add-outline" />;
render() {
return (
<KeyboardAwareScrollView
style={styles.mainContainer}
contentContainerStyle={styles.contentContainer}
enableOnAndroid>
<TabView
selectedIndex={this.state.selectedIndex}
onSelect={this.onSelect}
indicatorStyle={styles.indicatorStyle}
tabBarStyle={styles.tabBarStyle}>
<Tab title="Login" icon={this.renderLoginIcon}>
<View style={styles.container}>
<View style={styles.body}>
<View style={styles.form}>
<LoginForm navigation={this.props.navigation} />
</View>
</View>
</View>
</Tab>
<Tab title="Sign Up" icon={this.renderSignupIcon}>
<View style={styles.container}>
<View style={styles.body}>
<View style={styles.form}>
<SignupForm navigation={this.props.navigation} />
</View>
</View>
</View>
</Tab>
</TabView>
</KeyboardAwareScrollView>
);
}
}
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: Color.primary,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
contentContainer: {
flexGrow: 1,
},
body: {
paddingVertical: wp(5),
},
form: {
marginTop: 10,
width: wp(80),
},
indicatorStyle: {
backgroundColor: '#40AAB9',
},
tabBarStyle: {
backgroundColor: 'white',
},
});
export default Login;
|
import api from '../middleware/api'
import appLoading from './app-loading'
import appDoneLoading from './app-done-loading'
export const GAMES_UPDATED = 'GAMES_UPDATED'
export default function fetchGames() {
return dispatch => {
// We're loading (communicating with the API asynchronously)
dispatch(appLoading())
// Here's the new user data, create a User with it
api.authThenFind('games', (resources) => {
dispatch(appDoneLoading())
dispatch(gamesUpdated(resources))
})
}
}
function gamesUpdated(games) {
return {
type: GAMES_UPDATED,
payload: games.data,
}
}
|
'use strict';
// YOU KNOW WHAT TO DO //
/**
* each: Designed to loop over a collection, Array or Object, and applies the
* action Function to each value in the collection.
*
* @param {Array or Object} collection: The collection over which to iterate.
* @param {Function} action: The Function to be applied to each value in the
* collection
*/
function each(collection, action) {
if(Array.isArray(collection)) {
for(var i = 0; i < collection.length; i++) {
action(collection[i], i, collection);
}
} else {
for (var key in collection) {
action(collection[key], key, collection);
}
}
}
module.exports.each = each;
/**
* identity: takes an input value and returns a that value, unchanged
*
* @param {*} value: single value of any type
*
* @return {*} : the input value that is unchanged
*
*
*/
function identity (value) {
return value;
}
module.exports.identity = identity;
/**
* typeOF: takes a value and return the type of value it is
*
* @param {*} : value: a single value of any dataType
*
* @return {string} : a string of the dataType
*
*/
function typeOf(value) {
if (value === null) {
return 'null';
} else if (value instanceof Date === true) {
return 'date';
} else if (Array.isArray(value)) {
return 'array';
} else {
return typeof value;
}
}
module.exports.typeOf = typeOf;
/**
* first: takes an array and a number, returns all the indexes up to the number, returns empty array if not an array, or negative number, return first index
*
* @param {array} : an array
*
* @param {number} : a number
*
* @return {array} : return empty array if number is nagative, or parameter not an array, return first index if number is undefined or NaN,
* return array of elements up to the number parameter
*
*/
function first (array, number) {
if (!Array.isArray(array) || number < 0) {
return [];
}
if (isNaN(number) === true || number === undefined) {
return array[0];
} else {
return array.slice(0, number);
}
}
module.exports.first = first;
/**
* last: takes an array and a number, returns all the indexes down to the number, returns empty array if not an array, or negative number, return first index
*
* @param {array} array : an array
*
* @param {number} number : a number
*
* @return {array} : return empty array if number is nagative, or parameter not an array, return first index if number is undefined or NaN,
* return array of elements down to the number parameter
*
*/
function last (array, number) {
if (!Array.isArray(array) || number < 0) {
return [];
}
if (isNaN(number) === true || number === undefined) {
return array[array.length - 1];
} else {
return array.slice(-number);
}
}
module.exports.last = last;
/**
* indexOF: takes an array an a value, returns the index of the value, or -1 if value is not found
*
* @param {array} array : and array of values
*
* @param {*} value : any type of value
*
* @return {number} : return the index at whcih the value was found, or -1 if no value is found
*
*/
function indexOf(array, value) {
for (let i = 0; i < array.length; i++) {
if (value === array[i]) {
return i;
}
}
return -1;
}
module.exports.indexOf = indexOf;
/**
* contains: searches through the array to find a value
*
* @param {array} array : an Array
*
* @param {*} value : a value
*
* @return {boolean} : true if value is found, false if value is not found
*
*
*/
function contains(array, value) {
for (let i = 0; i < array.length; i++) {
if (array[i] === value) {
return true;
}
}
return false;
}
module.exports.contains = contains;
/**
* unique: takes an array, and returns an aray with all duplicates removed
*
* @param: {array} array : an array
*
* @return {array} : an array with all duplicates removed
*
*/
function unique (array) {
var myArr = [];
for (let i = 0; i < array.length; i ++) {
if(indexOf(array, array[i]) === i) {
myArr.push(array[i]);
}
}
return myArr;
};
module.exports.unique = unique;
/**
* filter: takes an array and a function, then filters the array into a new array
*
* @param {array} array : an array of values
*
* @param {function} func : a function that acts on elements, index, array
*
* @return {array} : a filtered array
*/
function filter (array, func) {
var myArr = [];
for (let i = 0; i < array.length; i++) {
if (func(array[i], i, array) === true) {
myArr.push(array[i]);
}
}
return myArr;
};
module.exports.filter = filter;
/**
* reject: takes an array and a function, returns boolean of false if any values evaluate to false
*
* @param: {array} array : an array of values
*
* @pamam: {function} func : a function to act on element, index, array on array
*
* @return {boolean} : if any values evaluate to false return false
*/
function reject (array, func) {
return filter(array, (e, i, a) => func(e, i, a) === false);
};
module.exports.reject = reject;
/**
* partition: returns 2 arrays, one of truthy values and the other of falsy values
*
* @param: {array} array : an array of values
*
* @param: {function} func : a function to act on element, index, array of array
*
* @return: {array} : return array of 2 arrays, one of truthy values, the other falsy values
*/
function partition (array, func) {
var trueArr = [];
var falseArr = [];
for (let i = 0; i < array.length; i++) {
if (func(array[i], i, array) === true) {
trueArr.push(array[i]);
}
}
for (let i = 0; i < array.length; i++) {
if (func(array[i], i, array) === false) {
falseArr.push(array[i]);
}
}
return [trueArr].concat([falseArr]);
};
module.exports.partition = partition;
/**
* map: iterates through a collection and return an new array of updated values, after being passed through the function
*
* @param: {array/object} collection : can be an array or an object
*
* @param: {function} func: a function that acts on element, index, array
*
* @return: {array} : return an updated array
*
*/
function map (collection, func) {
var myArr = [];
if (Array.isArray(collection)) {
for (let i = 0; i < collection.length; i++) {
var x = func(collection[i], i, collection);
myArr.push(x);
}
} else if (typeof collection === 'object' && collection !== null && collection instanceof Date === false) {
for (var key in collection) {
var y = func(collection[key], key, collection);
myArr.push(y);
}
}
return myArr;
}
module.exports.map = map;
/**
* pluck: takes an array of objects and a property and returns all the values assoiciated with the property into a new array
*
* @param: {array} array: an array of objects
*
* @param: {string} prop: a property or key value in an object
*
* @return: {array} : an array of values with key names that match the prop parameter
*
*/
function pluck (array, prop) {
return array.map((e, i, a) => a[i][prop]);
}
module.exports.pluck = pluck;
/**
* every: return a boolean true if every value passes to be true, false otherwise
*
* @param: {array/object} collection: an array or an object
*
* @param: {function} func : a function that acts upon element, index, array
*
* @return {boolean} : true if all elements are truthy, otherwise false, if callback not given return false.
*
*/
function every (collection, func) {
let test = true;
each(collection, function(e, i, a) {
if (typeof func === 'function' && !func(e, i, a)) {
test = false;
} else if (!e) {
test = false;
}
});
return test;
}
module.exports.every = every;
/**
* some: takes a collection, and a callback function, if the result of runing the function on ANY element results to true, return true,
* implementing the each function, iterate through the a collection of objects or arrays, accessing every element and value, for edge cases
* if a callback function is not given but an element exists, return true
*
* @param {array/object} collection: an array or an object
*
* @param {function} func : a function to act on all elements, index, array
*
* @return {boolean} : if one element is truthy, return true, otherwise return false, if no callback is given, return true if element is given, false otherwise.
*
*/
function some (collection, func) {
let test = false;
each(collection, function (e, i, c) {
if (typeof func === 'function') {
if(func(e, i, c) === true) {
test = true;
}
}
if (func === undefined) {
if(e) {
test = true;
}
}
});
return test;
}
module.exports.some = some;
/**
* reduce: takes an array, a function, and a seed, if no seed is provided, the first element in the array will become the seed,
* the callback function takes an additioanl 4 parameters including the accumulator or previous value, and the current value,
* the callback function reduces all accessed elements in the array into a single datatType.
*
* @param: {array} array : an array of values
*
* @param: {function} func : a function that acts on element, index, array of array
*
* @param: {*} seed : a value, if no value is given, value becomes the first index of the array
*
* @return: {*} : a value
*
*
*/
function reduce (arr, func, seed) {
let prevResult;
if (seed !== undefined) {
prevResult = seed;
each(arr, function(e, i, a) {
prevResult = func(prevResult, e, i, a);
});
} else {
prevResult = arr[0];
for (let i = 1; i < arr.length; i++) {
prevResult = func(prevResult, arr[i], i, arr);
}
}
return prevResult;
}
module.exports.reduce = reduce;
/**
* extend: adds objects properties to current object, takes objects as its paramaters, regardless of the number of objects, the added objects
* will be added onto the tst given object. so all passed in objects will reduce to a single object.
*
* @param {object} object : an object
*
* @return {object} : updated object
*
*
*/
function extend (object1, object2, ...object) {
return Object.assign(object1, object2, ...object);
}
module.exports.extend = extend;
|
import React from 'react';
import { Provider, useDispatch } from 'react-redux';
import Router from './routes';
// theme
import ThemeConfig from './theme';
import GlobalStyles from './theme/globalStyles';
// components
import ScrollToTop from './components/ScrollToTop';
import { BaseOptionChartStyle } from './components/charts/BaseOptionChart';
import store from './reducer';
import {request_get, onOrder} from './config'
// ----------------------------------------------------------------------
function BaseApp(){
const dispatch = useDispatch()
React.useEffect(function(){
const socket = new window.WebSocket("ws://localhost:3001");
dispatch({type: "SAVE_SOCKET", socket: socket})
socket.addEventListener("open", function() {
console.log("CONNECTED");
});
socket.addEventListener("message", function(e) {
try
{
const message = JSON.parse(e.data);
console.log('message +++', message)
//onOrder(message.random)
onOrder(message.random)
}
catch(e)
{
// Catch any errors
}
});
}, [])
return (
<ThemeConfig>
<ScrollToTop />
<GlobalStyles />
<BaseOptionChartStyle />
<Router />
</ThemeConfig>
)
}
export default function App() {
return (
<Provider store={store}>
<BaseApp/>
</Provider>
);
}
|
var utils = require('../../../util/utils');
var logger = require('pomelo-logger-ts').getLogger('forward-log', __filename);
/**
* Remote service for backend servers.
* Receive and handle request message forwarded from frontend server.
*/
module.exports = function (app) {
return new Remote(app);
};
var Remote = function (app) {
this.app = app;
};
/**
* Forward message from frontend server to other server's handlers
*
* @param msg {Object} request message
* @param session {Object} session object for current request
* @param cb {Function} callback function
*/
Remote.prototype.forwardMessage = function (msg, session, cb) {
var server = this.app.components.__server__;
var sessionService = this.app.components.__backendSession__;
if (!server) {
logger.error('server component not enable on', { serverId: this.app.serverId });
utils.invokeCallback(cb, new Error('server component not enable'));
return;
}
if (!sessionService) {
logger.error('backend session component not enable on', { serverId: this.app.serverId });
utils.invokeCallback(cb, new Error('backend sesssion component not enable'));
return;
}
// generate backend session for current request
var backendSession = sessionService.create(session);
// handle the request
logger.debug('handle message', { serverId: this.app.serverId, msg });
server.handle(msg, backendSession, function (err, resp, opts) {
// cb && cb(err, resp, opts);
utils.invokeCallback(cb, err, resp, opts);
});
};
Remote.prototype.forwardMessage2 = function (route, body, aesPassword, compressGzip, session, cb) {
var server = this.app.components.__server__;
var sessionService = this.app.components.__backendSession__;
if (!server) {
logger.error('server component not enable on', { serverId: this.app.serverId });
utils.invokeCallback(cb, new Error('server component not enable'));
return;
}
if (!sessionService) {
logger.error('backend session component not enable on %s', this.app.serverId);
utils.invokeCallback(cb, new Error('backend sesssion component not enable'));
return;
}
// generate backend session for current request
var backendSession = sessionService.create(session);
// handle the request
// logger.debug('backend server [%s] handle message: %j', this.app.serverId, msg);
var dmsg = {
route: route,
body: body,
compressGzip: compressGzip
}
var socket = {
aesPassword: aesPassword
}
var connector = this.app.components.__connector__.connector;
connector.runDecode(dmsg, socket, function (err, msg) {
if (err) {
return cb(err);
}
server.handle(msg, backendSession, function (err, resp, opts) {
utils.invokeCallback(cb, err, resp, opts);
});
});
};
|
(window["webpackJsonprenderer"] = window["webpackJsonprenderer"] || []).push([["icon.logo_google_g-js"],{
/***/ "./node_modules/@elastic/eui/es/components/icon/assets/logo_google_g.js":
/*!******************************************************************************!*\
!*** ./node_modules/@elastic/eui/es/components/icon/assets/logo_google_g.js ***!
\******************************************************************************/
/*! exports provided: icon */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"icon\", function() { return icon; });\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ \"./node_modules/react/index.js\");\n/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);\nfunction _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }\n\nfunction _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }\n\nfunction _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }\n\n\n\nvar EuiIconLogoGoogleG = function EuiIconLogoGoogleG(_ref) {\n var title = _ref.title,\n titleId = _ref.titleId,\n props = _objectWithoutProperties(_ref, [\"title\", \"titleId\"]);\n\n return react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"svg\", _extends({\n viewBox: \"0 0 32 32\",\n width: 32,\n height: 32,\n xmlns: \"http://www.w3.org/2000/svg\",\n \"aria-labelledby\": titleId\n }, props), title ? react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"title\", {\n id: titleId\n }, title) : null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"defs\", null, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n id: \"a\",\n d: \"M15.319 3.278c0-1.131-.102-2.22-.29-3.264H0v6.172h8.587c-.37 1.995-1.494 3.685-3.184 4.816v4.004h5.157c3.017-2.778 4.758-6.869 4.758-11.728z\"\n }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n id: \"c\",\n d: \"M14.343 12.956c4.308 0 7.92-1.43 10.56-3.866l-5.157-4.004c-1.429.958-3.256 1.523-5.403 1.523-4.156 0-7.674-2.806-8.928-6.578H.084v4.134c2.625 5.215 8.021 8.79 14.259 8.79z\"\n }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n id: \"e\",\n d: \"M7.028 10.25a9.59 9.59 0 01-.5-3.032 9.59 9.59 0 01.5-3.032V.052h-5.33A15.95 15.95 0 000 7.218c0 2.575.617 5.012 1.697 7.166l5.331-4.134z\"\n }), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n id: \"g\",\n d: \"M14.343 6.392c2.342 0 4.446.805 6.1 2.386l4.576-4.576C22.256 1.627 18.644.046 14.343.046 8.105.046 2.709 3.622.083 8.836l5.332 4.134c1.254-3.77 4.772-6.578 8.928-6.578z\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"g\", {\n fill: \"none\",\n fillRule: \"evenodd\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"g\", {\n transform: \"translate(15.955 13.087)\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"mask\", {\n id: \"b\",\n fill: \"#fff\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"use\", {\n xlinkHref: \"#a\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n fill: \"#4285F4\",\n fillRule: \"nonzero\",\n mask: \"url(#b)\",\n d: \"M.001 15.006h15.318V.014H.001z\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"g\", {\n transform: \"translate(1.613 19.003)\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"mask\", {\n id: \"d\",\n fill: \"#fff\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"use\", {\n xlinkHref: \"#c\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n fill: \"#34A853\",\n fillRule: \"nonzero\",\n mask: \"url(#d)\",\n d: \"M.084 12.956h24.819V.031H.084z\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"g\", {\n transform: \"translate(0 8.784)\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"mask\", {\n id: \"f\",\n fill: \"#fff\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"use\", {\n xlinkHref: \"#e\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n fill: \"#FBBC04\",\n fillRule: \"nonzero\",\n mask: \"url(#f)\",\n d: \"M0 14.384h7.028V.052H0z\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"g\", {\n transform: \"translate(1.613)\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"mask\", {\n id: \"h\",\n fill: \"#fff\"\n }, react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"use\", {\n xlinkHref: \"#g\"\n })), react__WEBPACK_IMPORTED_MODULE_0___default.a.createElement(\"path\", {\n fill: \"#EA4335\",\n fillRule: \"nonzero\",\n mask: \"url(#h)\",\n d: \"M.084 12.97h24.935V.046H.084z\"\n }))));\n};\n\nvar icon = EuiIconLogoGoogleG;\nEuiIconLogoGoogleG.__docgenInfo = {\n \"description\": \"\",\n \"methods\": [],\n \"displayName\": \"EuiIconLogoGoogleG\"\n};\n\n//# sourceURL=webpack://renderer/./node_modules/@elastic/eui/es/components/icon/assets/logo_google_g.js?");
/***/ })
}]);
|
var extend = require('util')._extend;
var ArgumentError = require('rest-facade').ArgumentError;
var RestClient = require('rest-facade').Client;
/**
* @class
* Handles authenticator with passwordless flows, e.g. SMS, Touch ID, etc.
* @constructor
* @memberOf module:auth
*
* @param {Object} options Authenticator options.
* @param {String} options.baseUrl The auth0 account URL.
* @param {String} [options.clientId] Default client ID.
* @param {String} [options.clientSecret] Default client secret.
* @param {OAuthAuthenticator} oauth OAuthAuthenticator instance.
*/
var PasswordlessAuthenticator = function(options, oauth) {
if (!options) {
throw new ArgumentError('Missing authenticator options');
}
if (typeof options !== 'object') {
throw new ArgumentError('The authenticator options must be an object');
}
/**
* Options object for the Rest Client instance.
*
* @type {Object}
*/
var clientOptions = {
errorFormatter: { message: 'message', name: 'error' },
headers: options.headers
};
this.oauth = oauth;
this.passwordless = new RestClient(options.baseUrl + '/passwordless/start', clientOptions);
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
};
/**
* Sign in with the given user credentials.
*
* @method signIn
* @memberOf module:auth.PasswordlessAuthenticator.prototype
* @example <caption>
* Given the user credentials (`phone_number` and `code`), it will do the
* authentication on the provider and return a JSON with the `access_token`
* and `id_token`.
* </caption>
*
* var data = {
* username: '{PHONE_NUMBER}',
* password: '{VERIFICATION_CODE}'
* };
*
* auth0.passwordless.signIn(data, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @example <caption>
* The user data object has the following structure.
* </caption>
*
* {
* id_token: String,
* access_token: String,
* token_type: String
* }
*
* @param {Object} userData User credentials object.
* @param {String} userData.username Username.
* @param {String} userData.password Password.
* @param {String} [userData.connection=sms] Connection string: "sms" or "email".
* @param {Function} [cb] Method callback.
*
* @return {Promise|undefined}
*/
PasswordlessAuthenticator.prototype.signIn = function(userData, cb) {
var defaultFields = {
client_id: this.clientId,
client_secret: this.clientSecret
};
var data = extend(defaultFields, userData);
// Don't let the user override the connection nor the grant type.
if (!data.connection || (data.connection !== 'email' && data.connection !== 'sms')) {
data.connection = 'sms';
}
data.grant_type = 'password';
if (!userData || typeof userData !== 'object') {
throw new ArgumentError('Missing user data object');
}
if (typeof data.username !== 'string' || data.username.trim().length === 0) {
throw new ArgumentError('username field (phone number) is required');
}
if (typeof data.password !== 'string' || data.password.trim().length === 0) {
throw new ArgumentError('password field (verification code) is required');
}
return this.oauth.signIn(data, cb);
};
/**
* Start passwordless flow sending an email.
*
* @method sendEmail
* @memberOf module:auth.PasswordlessAuthenticator.prototype
* @example <caption>
* Given the user `email` address, it will send an email with:
*
* <ul>
* <li>A link (default, `send:"link"`). You can then authenticate with this
* user opening the link and he will be automatically logged in to the
* application. Optionally, you can append/override parameters to the link
* (like `scope`, `redirect_uri`, `protocol`, `response_type`, etc.) using
* `authParams` object.
* </li>
* <li>
* A verification code (`send:"code"`). You can then authenticate with
* this user using the `/oauth/ro` endpoint specifying `email` as
* `username` and `code` as `password`.
* </li>
* </ul>
*
* Find more information in the
* <a href="https://auth0.com/docs/auth-api#!#post--with_email">API Docs</a>
* </caption>
*
* var data = {
* email: '{EMAIL}',
* send: 'link',
* authParams: {} // Optional auth params.
* };
*
* auth0.passwordless.sendEmail(data, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} userData User account data.
* @param {String} userData.email User email address.
* @param {String} userData.send The type of email to be sent.
* @param {Function} [cb] Method callback.
*
* @return {Promise|undefined}
*/
PasswordlessAuthenticator.prototype.sendEmail = function(userData, cb) {
var defaultFields = {
client_id: this.clientId,
client_secret: this.clientSecret
};
var data = extend(defaultFields, userData);
// Don't let the user override the connection nor the grant type.
data.connection = 'email';
if (!userData || typeof userData !== 'object') {
throw new ArgumentError('Missing user data object');
}
if (typeof data.email !== 'string' || data.email.trim().length === 0) {
throw new ArgumentError('email field is required');
}
if (typeof data.send !== 'string' || data.send.trim().length === 0) {
throw new ArgumentError('send field is required');
}
if (cb && cb instanceof Function) {
return this.passwordless.create(data, cb);
}
return this.passwordless.create(data);
};
/**
* Start passwordless flow sending an SMS.
*
* @method sendSMS
* @memberOf module:auth.PasswordlessAuthenticator.prototype
*
* @example <caption>
* Given the user `phone_number`, it will send a SMS message with a
* verification code. You can then authenticate with this user using the
* `/oauth/ro` endpoint specifying `phone_number` as `username` and `code` as
* `password`:
* </caption>
*
* var data = {
* phone_number: '{PHONE}'
* };
*
* auth0.passwordless.sendSMS(data, function (err) {
* if (err) {
* // Handle error.
* }
* });
*
* @param {Object} userData User account data.
* @param {String} userData.phone_number User phone number.
* @param {Function} [cb] Method callback.
*
* @return {Promise|undefined}
*/
PasswordlessAuthenticator.prototype.sendSMS = function(userData, cb) {
var defaultFields = {
client_id: this.clientId,
client_secret: this.clientSecret
};
var data = extend(defaultFields, userData);
// Don't let the user override the connection nor the grant type.
data.connection = 'sms';
if (!userData || typeof userData !== 'object') {
throw new ArgumentError('Missing user data object');
}
if (typeof data.phone_number !== 'string' || data.phone_number.trim().length === 0) {
throw new ArgumentError('phone_number field is required');
}
if (cb && cb instanceof Function) {
return this.passwordless.create(data, cb);
}
return this.passwordless.create(data);
};
module.exports = PasswordlessAuthenticator;
|
const express = require("express"),
path = require("path"),
app = express(),
port = process.env.PORT || 3000;
app.get('/', (req, res) => {
let userInfo = req.header("user-agent");
res.send(`UserInfo: ${userInfo}`);
});
app.get('/receipts', (req, res) => {
let file = path.join(__dirname, "asset/receipt.pdf");
res.sendFile();
});
app.get('/products', (req, res) => {
let storeProducts = '';
res.json(storeProducts);
});
app.listen(port, err => {
if (err) {
console.error("Error: ", err);
return;
}
console.log(`Listening http://localhost:${port}`);
});
|
const { dialog } = require('electron').remote
const { BrowserWindow } = require("electron");
const { app } = require("electron");
const { remote } = require('electron')
const { shell } = require('electron')
const { clipboard } = require('electron')
const { Menu, MenuItem } = remote
win = remote.getCurrentWindow()
const contents = win.webContents
var ipc = require('electron').ipcRenderer
fs = require('fs');
var findpage = true
var search = document.getElementById("search")
search.select()
var view = document.getElementById("webview")
var secure = document.getElementById("security")
|
export { default as FormatTime } from './format-time';
export { default as FormatDate } from './format-date';
export { default as FormatNumber } from './format-number';
export { default as FormatMessage } from './format-message';
export { default as FormatRelative } from './format-relative';
|
const path = require('path');
const webpack = require('webpack');
const md5 = require('md5');
const fs = require('fs');
const reactVersion = require('react/package.json').version;
const fileHashMemo = {};
const getFileHash = (filepath) => {
if (fileHashMemo[filepath]) {
return fileHashMemo[filepath];
}
let contentHash = md5(fs.readFileSync(filepath, 'utf8'));
fileHashMemo[filepath] = contentHash.substr(contentHash.length - 5);
return fileHashMemo[filepath];
};
const generateScopedName = (localName, resourcePath) => {
let componentName = resourcePath.split('/').slice(-2, -1);
let contentHash = getFileHash(resourcePath);
//let hash = md5(resourcePath);
return `${componentName}_${localName}_${contentHash}`;
};
module.exports = ({config}, env) => {
if (env === 'PRODUCTION') {
// see https://github.com/storybooks/storybook/issues/1570
config.plugins = config.plugins.filter(plugin => plugin.constructor.name !== 'UglifyJsPlugin')
}
config.plugins.push(new webpack.DefinePlugin({REACT_VERSION: JSON.stringify(reactVersion)}));
config.resolve.extensions.push('.ts', '.tsx');
return Object.assign(config, {
parallelism: 1,
module: {
rules: [
{
test: /\.jsx?$/,
include: [__dirname, path.resolve(__dirname + '/../src'), path.resolve(__dirname + '/../packages'), /collection-view/],
loader: require.resolve('babel-loader')
},
{
test: /\.(ts|tsx)$/,
use: [
{ loader: require.resolve('babel-loader') },
]
},
{
test: /\.styl$/,
use: [
'style-loader',
'css-loader',
{
loader: 'stylus-loader',
options: {
paths: [__dirname + '/../node_modules'],
define: {
'embedurl': require('stylus').url()
},
'resolve url': true,
set: {
'include css': true
},
use: [require('svg-stylus')()]
}
}
],
include: path.resolve(__dirname, '../')
},
{
test: /packages[\\/].*\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 1,
getLocalIdent: (context, localIdentName, localName) => {
return generateScopedName(localName, context.resourcePath);
},
}
},
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: require('../postcss.config').plugins
}
}
],
include: path.resolve(__dirname, '../')
},
{
test: /\.css$/,
loaders: ['style-loader', 'css-loader'],
include: path.resolve(__dirname, '../'),
exclude: /packages[\\/].*\.css$/
},
{
test: /\.(ttf|woff|woff2|svg|gif|cur|eot|png|jpg)(\?[a-f0-9]{32})?$/,
loader: 'url-loader?limit=8192'// limit inlining base64 URLs to <=8k images, direct URLs for the rest
}
]
}
});
};
|
const express = require("express");
const mongoose = require("mongoose");
const PORT = process.env.PORT || 8080;
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/workout", {
useNewUrlParser: true,
useFindAndModify: false
});
// routes
app.use(require("./routes/api.js"));
app.use(require("./routes/html-routes.js"));
app.listen(PORT, () => {
console.log(`App running on port ${PORT}! http://localhost:${PORT}`);
});
|
"use strict";
function contains(a, e) {
for (var i = 0; i < a.length; i++) {
if (a[i] === e) {
return true;
}
}
return false;
}
function append(a, e) {
var d = remove(a, e);
d.push(e);
return d;
}
function remove(a, e) {
var d = [];
for (var i = 0; i < a.length; i++) {
if (a[i] !== e) {
d.push(a[i]);
}
}
return d;
}
function equals(l, r) {
return (l === r) ? true : false;
}
function foreach(a, f) {
var terminator = Object();
for (var i = 0; i < a.length; i++) {
if (f(a[i]) === terminator) {
break;
}
}
}
function foreachClass(c, f) {
var n = document.getElementsByClassName(c);
foreach(n, f);
}
function foreachTag(t, f) {
var n = document.getElementsByTagName(t);
foreach(n, f);
}
function foreachTagWithClass(t, c, f) {
var n = c instanceof Array ? contains : equals;
foreachTag(t, function(e) {
if (n(c, e.className)) {
return f(e);
}
});
}
var cookie = {
get:function(n, m) { return (m = ('; ' + document.cookie + ';').match('; ' + n + '(.*?);')) ? decodeURIComponent(m[1]) : ''; },
set:function(n, v) { document.cookie = n + '=' + encodeURIComponent(v) + '; expires=Mon, 31-Dec-2029 23:59:59 GMT'; }
};
var warater = {
init:function() {
cookie.set('WARATAADD', '');
cookie.set('WARATADEL', '');
warater.initPage();
},
initPage:function() {
foreachClass('warata', function(e) {
var m = e.getElementsByClassName('waratamark');
var c = e.getElementsByClassName('waratacount');
var i = e.getElementsByClassName('identify');
var n = e.attributes.name.value;
var v = e.getElementsByClassName('waratalist');
var a = document.createElement('span');
if(m[0].childNodes.length == 0) {
m[0].appendChild(a);
a.appendChild(document.createTextNode('★'));
a.title = '押せばワラタの星光る';
a.style.marginLeft = '1em';
var s = document.createElement('span');
s.className = 'waratacount';
a.appendChild(s);
a.onclick = function() {
warater.update(m, c, i, n, v, 1);
return false;
};
warater.update(m, c, i, n, v, 0);
}
});
},
update:function(m, c, i, n, v, f) {
var wa = cookie.get('WARATAADD=');
var waa = wa.split(/,/);
if(waa.length == 1 && waa[0] === '') {
waa = [];
}
var wd = cookie.get('WARATADEL=');
var wda = wd.split(/,/);
if(wda.length == 1 && wda[0] === '') {
wda = [];
}
var va = v[0].attributes.name.value.split(/:/);
if(va.length == 1 && va[0] === '') {
va = [];
}
var t = i[0].attributes.name.value + ':' + n;
if(f !== 0) {
if(contains(va, n)) {
wda = contains(wda, t) ? remove(wda, t) : append(wda, t);
} else {
waa = contains(waa, t) ? remove(waa, t) : append(waa, t);
}
cookie.set('WARATAADD', waa.join(','));
cookie.set('WARATADEL', wda.join(','));
}
var ff = 0;
if(contains(waa, t)) {
ff++;
}
if(contains(wda, t)) {
--ff;
}
m[0].style.cursor = 'pointer';
ff += va.length;
m[0].style.color = (contains(waa, t) || (ff >= 0 && contains(va, n))) ? 'red' : 'yellow';
if(contains(wda, t)) {
m[0].style.color = 'yellow';
}
c[0].innerHTML = (ff > 0) ? ff : '';
if(c[0].innerHTML === '') {
m[0].style.color = 'white';
}
}
};
warater.init();
// vim: tabstop=8 softtabstop=4 shiftwidth=4 textwidth=78 :
|
/**
* @author Mikael Emtinger
*/
PrairieCameraFreeExplore = function( shared ) {
// setttings
var CAMERA_Y = 25;
var CAMERA_FORWARD_SPEED = 2;
var CAMERA_VERTICAL_FACTOR = 20;
var CAMERA_VERTICAL_LIMIT = 200;
var CAMERA_HORIZONTAL_FACTOR = 15;
var CAMERA_INERTIA = 0.02;
var CAMERA_ROLL_FACTOR = 0.4;
var CAMERA_RADIUS = 795;
// variables
var wantedCamera;
var wantedCameraTarget;
var wantedCameraDirection = new THREE.Vector3();
var world;
var portals;
var camera;
var center;
var portalDirectionDot = new THREE.Vector3();
// construct
world = shared.worlds.prairie;
portals = world.portals;
center = new THREE.Vector3( 350, 0, -300);
camera = new THREE.Camera( 50, shared.viewportWidth / shared.viewportHeight, 1, 100000 );
camera.target.position.set( 0, 0, -100 );
wantedCamera = new THREE.Object3D();
wantedCameraTarget = new THREE.Object3D();
wantedCameraTarget.position.set( 0, 0, -100 );
world.scene.addChild( camera );
world.scene.addChild( camera.target );
world.scene.addChild( wantedCamera );
world.scene.addChild( wantedCameraTarget );
//--- public ---
var that = {};
that.camera = camera;
//--- reset camera ---
that.resetCamera = function() {
wantedCamera.position.set( center.x - 200, CAMERA_Y, center.z );
wantedCameraTarget.position.set( center.x + 300, CAMERA_Y, center.z );
camera.position.copy( wantedCamera.position );
camera.target.position.copy( wantedCameraTarget.position );
}
//--- update camera ---
that.updateCamera = function( progress, delta, time ) {
delta = delta * ( 1000 / 30 ) / 1000;
// get mouse
var mouseX = shared.mouse.x / shared.screenWidth - 0.5;
var mouseY = shared.mouse.y / shared.screenHeight - 0.5;
// handle up/down (cap lowest, highest)
if( Math.abs( wantedCameraTarget.position.y - wantedCamera.position.y ) < CAMERA_VERTICAL_LIMIT ) {
wantedCameraTarget.position.y -= mouseY * CAMERA_VERTICAL_FACTOR * delta;
} else {
if( wantedCameraTarget.position.y > wantedCamera.position.y ) wantedCameraTarget.position.y -= CAMERA_VERTICAL_FACTOR;
if( wantedCameraTarget.position.y < wantedCamera.position.y ) wantedCameraTarget.position.y += CAMERA_VERTICAL_FACTOR;
}
// handle left/right
wantedCameraDirection.sub( wantedCameraTarget.position, wantedCamera.position ).normalize();
wantedCameraTarget.position.x = wantedCamera.position.x + wantedCameraDirection.x * 350 - wantedCameraDirection.z * CAMERA_HORIZONTAL_FACTOR * mouseX * delta;
wantedCameraTarget.position.z = wantedCamera.position.z + wantedCameraDirection.z * 350 + wantedCameraDirection.x * CAMERA_HORIZONTAL_FACTOR * mouseX * delta;
// move forward
// if moving towards portal, home in on it
var closestPortal;
var closestDistance = 9999999999;
for( var p = 0; p < portals.length; p++ ) {
var portal = portals[ p ];
var dot = portalDirectionDot.sub( portal.object.matrixWorld.getPosition(), wantedCamera.position ).normalize().dot( wantedCameraDirection );
if( dot > 0.7 && portal.currentDistance < closestDistance ) {
closestDistance = portal.currentDistance;
closestPortal = portal;
}
}
if( closestPortal && closestDistance < closestPortal.radius * 2 ) {
portalDirectionDot.sub( closestPortal.object.matrixWorld.getPosition(), wantedCamera.position );
wantedCamera.position.addSelf( portalDirectionDot.normalize().multiplyScalar( CAMERA_FORWARD_SPEED * delta ));
} else {
var movement = wantedCameraDirection.multiplyScalar( CAMERA_FORWARD_SPEED * delta );
movement.y = ( CAMERA_Y - wantedCamera.position.y ) * 0.03;
wantedCamera.position.addSelf( movement );
var x = wantedCamera.position.x - center.x;
var z = wantedCamera.position.z - center.z;
var dot = portalDirectionDot.sub( center, wantedCamera.position ).normalize().dot( wantedCameraDirection );
if( Math.sqrt( x * x + z * z ) > CAMERA_RADIUS && dot < 0 ) {
wantedCamera.position.subSelf( movement );
}
}
// position intertia
camera.position.x += ( wantedCamera.position.x - camera.position.x ) * CAMERA_INERTIA * delta;
camera.position.y += ( wantedCamera.position.y - camera.position.y ) * CAMERA_INERTIA * delta;
camera.position.z += ( wantedCamera.position.z - camera.position.z ) * CAMERA_INERTIA * delta;
camera.target.position.x += ( wantedCameraTarget.position.x - camera.target.position.x ) * CAMERA_INERTIA * delta;
camera.target.position.y += ( wantedCameraTarget.position.y - camera.target.position.y ) * CAMERA_INERTIA * delta;
camera.target.position.z += ( wantedCameraTarget.position.z - camera.target.position.z ) * CAMERA_INERTIA * delta;
// roll
var currentCameraZ = camera.matrixWorld.getColumnZ();
wantedCameraDirection.normalize();
wantedCameraDirection.y = currentCameraZ.y;
wantedCameraDirection.subSelf( currentCameraZ ).normalize();
wantedCameraDirection.multiplyScalar( CAMERA_ROLL_FACTOR * delta );
wantedCamera.up.set( 0, 1, 0 );
wantedCamera.up.subSelf( wantedCameraDirection ).normalize();
camera.up.x += ( wantedCamera.up.x - camera.up.x ) * CAMERA_INERTIA * delta;
camera.up.y += ( wantedCamera.up.y - camera.up.y ) * CAMERA_INERTIA * delta;
camera.up.z += ( wantedCamera.up.z - camera.up.z ) * CAMERA_INERTIA * delta;
}
return that;
}
|
const path = require('path');
module.exports = {
entry: {
main: './_scripts/main.js',
home: './_scripts/home.js',
post: './_scripts/post.js',
404: './_scripts/404.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'assets/js'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules)/,
loader: 'babel-loader',
},
{
test: /\.sass$/,
exclude: /(node_modules)/,
use: [
'raw-loader',
'sass-loader',
],
},
],
},
};
|
module.exports = function (color) {
let ret
if (color) {
if (Array.isArray(color)) {
ret = color.slice()
if (ret.length > 4) {
ret = ret.slice(0, 4)
} else if (ret.length !== 4) {
while (ret.length < 4) {
ret.push(1)
}
}
}
} else {
ret = [1, 1, 1, 1]
}
return ret
}
|
module.exports={A:{A:{"2":"J D E F oB","33":"A B"},B:{"33":"C K L G M N O","132":"P Q R U V W X Y","260":"Z a b c d e f S H g"},C:{"1":"6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB gB MB hB NB OB T PB QB RB SB TB UB VB WB XB YB ZB aB bB cB P Q R iB U V W X Y Z a b c d e f S H g","2":"pB fB I h qB rB","33":"0 1 2 3 4 5 J D E F A B C K L G M N O i j k l m n o p q r s t u v w x y z"},D:{"1":"Z a b c d e f S H g sB tB uB","2":"0 1 2 3 4 5 6 7 8 9 I h J D E F A B C K L G M N O i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB","132":"IB JB KB LB gB MB hB NB OB T PB QB RB SB TB UB VB WB XB YB ZB aB bB cB P Q R U V W X Y"},E:{"2":"I h vB jB","33":"J D E F A B C K L G wB xB yB zB kB dB eB 0B 1B 2B lB 3B"},F:{"2":"0 1 2 3 4 F B C G M N O i j k l m n o p q r s t u v w x y z 4B 5B 6B 7B dB mB 8B eB","132":"5 6 7 8 9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB T PB QB RB SB TB UB VB WB XB YB ZB aB bB cB P Q R iB"},G:{"2":"jB 9B","33":"E nB AC BC CC DC EC FC GC HC IC JC KC LC MC NC OC PC QC RC SC lB"},H:{"2":"TC"},I:{"1":"H","2":"fB I UC VC WC XC nB YC ZC"},J:{"2":"D A"},K:{"1":"T","2":"A B C dB mB eB"},L:{"1":"H"},M:{"1":"S"},N:{"2":"A B"},O:{"4":"aC"},P:{"1":"cC dC eC fC kB gC hC iC jC kC","2":"I","132":"bC"},Q:{"2":"lC"},R:{"132":"mC"},S:{"1":"nC"}},B:5,C:"CSS Hyphenation"};
|
import computed from "ember-addons/ember-computed-decorators";
const { isEmpty, makeArray } = Ember;
export default Ember.Component.extend({
layoutName: "select-kit/templates/components/select-kit/select-kit-header",
classNames: ["select-kit-header"],
classNameBindings: ["isFocused", "isNone"],
attributeBindings: [
"tabindex",
"ariaLabel:aria-label",
"ariaHasPopup:aria-haspopup",
"sanitizedTitle:title",
"value:data-value",
"name:data-name"
],
isNone: Ember.computed.none("computedContent.value"),
ariaHasPopup: true,
ariaLabel: Ember.computed.or("computedContent.ariaLabel", "sanitizedTitle"),
@computed("computedContent.title", "name")
title(computedContentTitle, name) {
if (computedContentTitle) return computedContentTitle;
if (name) return name;
return "";
},
// this might need a more advanced solution
// but atm it's the only case we have to handle
@computed("title")
sanitizedTitle(title) {
return String(title).replace("…", "");
},
label: Ember.computed.or("computedContent.label", "title", "name"),
name: Ember.computed.alias("computedContent.name"),
value: Ember.computed.alias("computedContent.value"),
@computed("computedContent.icon", "computedContent.icons")
icons(icon, icons) {
return makeArray(icon)
.concat(icons)
.filter(i => !isEmpty(i));
},
click() {
this.sendAction("onToggle");
}
});
|
/**
* コメント内の画像を縮小表示する処理
*/
const limitImageSize = document.getElementById('limitImageSize');
limitImageSize.addEventListener('change', function () {
const state = this.checked;
sendState(state);
chrome.storage.local.set({ limitImageSize: state }, () => { });
});
function sendState(state) {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.scripting.executeScript({
target: { tabId: tabs[0].id },
func: state => ICR.setLimitImageSize(state),
args: [state]
}, () => { });
});
}
export function initialize(initParam) {
limitImageSize.checked = initParam.limitImageSize;
}
|
chrome.runtime.sendMessage(document.URL, (response) => {
// 3. Got an asynchronous response with the data from the background
console.log('received user data', response);
if (response == 1) {
alert('It is a Legitimate Website!');
} else {
alert('Beware!!! It is a Phishing Website!');
}
//initializeUI(response);
});
|
// COPYRIGHT © 201 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/3.31/esri/copyright.txt for details.
define({inputLayerLabel:"Elegir la capa de ubicación de entidad o ráster respecto a la cual se calculará la distancia",inputRaster:"Elegir la capa de entidades o ráster para representar barreras (opcional)",maxDistanceLabel:"Distancia máxima a calcular (opcional)",outputCellSize:"Tamaño de celda de salida (opcional)",distanceMethod:"Método de distancia",resultDistLayerName:"Nombre de la capa de resultados de distancia",resultDirectionLayerName:"Nombre de la capa de resultados de dirección (opcional)",resultAllocationLayerName:"Nombre de la capa de resultados de asignación (opcional)",outputBackDirectionName:"Nombre de la capa de resultados de dirección hacia atrás (opcional)",outputLayerName:"Distancia calculada de ${layername}",allocationFieldLabel:"Elegir campo de asignación (opcional)",itemDescription:"Capa de entidades generada al ejecutar Calcular distancia en ${layerName}. ",itemTags:"Resultados del análisis, CalculateDistance, ${layername} ${fieldname}",itemSnippet:"Capa de entidades generada a partir de CalculateDistance.",planar:"Planar",geodesic:"Geodésico",selectDistance:"-- seleccionar --"});
|
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/alpinejs/dist/module.esm.js":
/*!**************************************************!*\
!*** ./node_modules/alpinejs/dist/module.esm.js ***!
\**************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ module_default)
/* harmony export */ });
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __markAsModule = (target) => __defProp(target, "__esModule", {value: true});
var __commonJS = (callback, module) => () => {
if (!module) {
module = {exports: {}};
callback(module.exports, module);
}
return module.exports;
};
var __exportStar = (target, module, desc) => {
if (module && typeof module === "object" || typeof module === "function") {
for (let key of __getOwnPropNames(module))
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable});
}
return target;
};
var __toModule = (module) => {
return __exportStar(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? {get: () => module.default, enumerable: true} : {value: module, enumerable: true})), module);
};
// node_modules/@vue/shared/dist/shared.cjs.js
var require_shared_cjs = __commonJS((exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
function makeMap(str, expectsLowerCase) {
const map = Object.create(null);
const list = str.split(",");
for (let i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val];
}
var PatchFlagNames = {
[1]: `TEXT`,
[2]: `CLASS`,
[4]: `STYLE`,
[8]: `PROPS`,
[16]: `FULL_PROPS`,
[32]: `HYDRATE_EVENTS`,
[64]: `STABLE_FRAGMENT`,
[128]: `KEYED_FRAGMENT`,
[256]: `UNKEYED_FRAGMENT`,
[512]: `NEED_PATCH`,
[1024]: `DYNAMIC_SLOTS`,
[2048]: `DEV_ROOT_FRAGMENT`,
[-1]: `HOISTED`,
[-2]: `BAIL`
};
var slotFlagsText = {
[1]: "STABLE",
[2]: "DYNAMIC",
[3]: "FORWARDED"
};
var GLOBALS_WHITE_LISTED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt";
var isGloballyWhitelisted = /* @__PURE__ */ makeMap(GLOBALS_WHITE_LISTED);
var range = 2;
function generateCodeFrame(source, start2 = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start2) {
for (let j = i - range; j <= i + range || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
const pad = start2 - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start2);
res.push(` | ` + " ".repeat(pad) + "^".repeat(length));
} else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + "^".repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join("\n");
}
var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs);
var isBooleanAttr2 = /* @__PURE__ */ makeMap(specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`);
var unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/;
var attrValidationCache = {};
function isSSRSafeAttrName(name) {
if (attrValidationCache.hasOwnProperty(name)) {
return attrValidationCache[name];
}
const isUnsafe = unsafeAttrCharRE.test(name);
if (isUnsafe) {
console.error(`unsafe attribute name: ${name}`);
}
return attrValidationCache[name] = !isUnsafe;
}
var propsToAttrMap = {
acceptCharset: "accept-charset",
className: "class",
htmlFor: "for",
httpEquiv: "http-equiv"
};
var isNoUnitNumericStyleProp = /* @__PURE__ */ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,stroke-miterlimit,stroke-opacity,stroke-width`);
var isKnownAttr = /* @__PURE__ */ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`);
function normalizeStyle(value) {
if (isArray(value)) {
const res = {};
for (let i = 0; i < value.length; i++) {
const item = value[i];
const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
if (normalized) {
for (const key in normalized) {
res[key] = normalized[key];
}
}
}
return res;
} else if (isObject(value)) {
return value;
}
}
var listDelimiterRE = /;(?![^(]*\))/g;
var propertyDelimiterRE = /:(.+)/;
function parseStringStyle(cssText) {
const ret = {};
cssText.split(listDelimiterRE).forEach((item) => {
if (item) {
const tmp = item.split(propertyDelimiterRE);
tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
}
});
return ret;
}
function stringifyStyle(styles) {
let ret = "";
if (!styles) {
return ret;
}
for (const key in styles) {
const value = styles[key];
const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key);
if (isString(value) || typeof value === "number" && isNoUnitNumericStyleProp(normalizedKey)) {
ret += `${normalizedKey}:${value};`;
}
}
return ret;
}
function normalizeClass(value) {
let res = "";
if (isString(value)) {
res = value;
} else if (isArray(value)) {
for (let i = 0; i < value.length; i++) {
const normalized = normalizeClass(value[i]);
if (normalized) {
res += normalized + " ";
}
}
} else if (isObject(value)) {
for (const name in value) {
if (value[name]) {
res += name + " ";
}
}
}
return res.trim();
}
var HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot";
var SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view";
var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
var isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS);
var isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS);
var isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);
var escapeRE = /["'&<>]/;
function escapeHtml(string) {
const str = "" + string;
const match = escapeRE.exec(str);
if (!match) {
return str;
}
let html = "";
let escaped;
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34:
escaped = """;
break;
case 38:
escaped = "&";
break;
case 39:
escaped = "'";
break;
case 60:
escaped = "<";
break;
case 62:
escaped = ">";
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escaped;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
var commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g;
function escapeHtmlComment(src) {
return src.replace(commentStripRE, "");
}
function looseCompareArrays(a, b) {
if (a.length !== b.length)
return false;
let equal = true;
for (let i = 0; equal && i < a.length; i++) {
equal = looseEqual(a[i], b[i]);
}
return equal;
}
function looseEqual(a, b) {
if (a === b)
return true;
let aValidType = isDate(a);
let bValidType = isDate(b);
if (aValidType || bValidType) {
return aValidType && bValidType ? a.getTime() === b.getTime() : false;
}
aValidType = isArray(a);
bValidType = isArray(b);
if (aValidType || bValidType) {
return aValidType && bValidType ? looseCompareArrays(a, b) : false;
}
aValidType = isObject(a);
bValidType = isObject(b);
if (aValidType || bValidType) {
if (!aValidType || !bValidType) {
return false;
}
const aKeysCount = Object.keys(a).length;
const bKeysCount = Object.keys(b).length;
if (aKeysCount !== bKeysCount) {
return false;
}
for (const key in a) {
const aHasKey = a.hasOwnProperty(key);
const bHasKey = b.hasOwnProperty(key);
if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) {
return false;
}
}
}
return String(a) === String(b);
}
function looseIndexOf(arr, val) {
return arr.findIndex((item) => looseEqual(item, val));
}
var toDisplayString = (val) => {
return val == null ? "" : isObject(val) ? JSON.stringify(val, replacer, 2) : String(val);
};
var replacer = (_key, val) => {
if (isMap(val)) {
return {
[`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => {
entries[`${key} =>`] = val2;
return entries;
}, {})
};
} else if (isSet(val)) {
return {
[`Set(${val.size})`]: [...val.values()]
};
} else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
return String(val);
}
return val;
};
var babelParserDefaultPlugins = [
"bigInt",
"optionalChaining",
"nullishCoalescingOperator"
];
var EMPTY_OBJ = Object.freeze({});
var EMPTY_ARR = Object.freeze([]);
var NOOP = () => {
};
var NO = () => false;
var onRE = /^on[^a-z]/;
var isOn = (key) => onRE.test(key);
var isModelListener = (key) => key.startsWith("onUpdate:");
var extend = Object.assign;
var remove = (arr, el) => {
const i = arr.indexOf(el);
if (i > -1) {
arr.splice(i, 1);
}
};
var hasOwnProperty = Object.prototype.hasOwnProperty;
var hasOwn = (val, key) => hasOwnProperty.call(val, key);
var isArray = Array.isArray;
var isMap = (val) => toTypeString(val) === "[object Map]";
var isSet = (val) => toTypeString(val) === "[object Set]";
var isDate = (val) => val instanceof Date;
var isFunction = (val) => typeof val === "function";
var isString = (val) => typeof val === "string";
var isSymbol = (val) => typeof val === "symbol";
var isObject = (val) => val !== null && typeof val === "object";
var isPromise = (val) => {
return isObject(val) && isFunction(val.then) && isFunction(val.catch);
};
var objectToString = Object.prototype.toString;
var toTypeString = (value) => objectToString.call(value);
var toRawType = (value) => {
return toTypeString(value).slice(8, -1);
};
var isPlainObject = (val) => toTypeString(val) === "[object Object]";
var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key;
var isReservedProp = /* @__PURE__ */ makeMap(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted");
var cacheStringFunction = (fn) => {
const cache = Object.create(null);
return (str) => {
const hit = cache[str];
return hit || (cache[str] = fn(str));
};
};
var camelizeRE = /-(\w)/g;
var camelize = cacheStringFunction((str) => {
return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
});
var hyphenateRE = /\B([A-Z])/g;
var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase());
var capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
var toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``);
var hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
var invokeArrayFns = (fns, arg) => {
for (let i = 0; i < fns.length; i++) {
fns[i](arg);
}
};
var def = (obj, key, value) => {
Object.defineProperty(obj, key, {
configurable: true,
enumerable: false,
value
});
};
var toNumber = (val) => {
const n = parseFloat(val);
return isNaN(n) ? val : n;
};
var _globalThis;
var getGlobalThis = () => {
return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : {});
};
exports.EMPTY_ARR = EMPTY_ARR;
exports.EMPTY_OBJ = EMPTY_OBJ;
exports.NO = NO;
exports.NOOP = NOOP;
exports.PatchFlagNames = PatchFlagNames;
exports.babelParserDefaultPlugins = babelParserDefaultPlugins;
exports.camelize = camelize;
exports.capitalize = capitalize;
exports.def = def;
exports.escapeHtml = escapeHtml;
exports.escapeHtmlComment = escapeHtmlComment;
exports.extend = extend;
exports.generateCodeFrame = generateCodeFrame;
exports.getGlobalThis = getGlobalThis;
exports.hasChanged = hasChanged;
exports.hasOwn = hasOwn;
exports.hyphenate = hyphenate;
exports.invokeArrayFns = invokeArrayFns;
exports.isArray = isArray;
exports.isBooleanAttr = isBooleanAttr2;
exports.isDate = isDate;
exports.isFunction = isFunction;
exports.isGloballyWhitelisted = isGloballyWhitelisted;
exports.isHTMLTag = isHTMLTag;
exports.isIntegerKey = isIntegerKey;
exports.isKnownAttr = isKnownAttr;
exports.isMap = isMap;
exports.isModelListener = isModelListener;
exports.isNoUnitNumericStyleProp = isNoUnitNumericStyleProp;
exports.isObject = isObject;
exports.isOn = isOn;
exports.isPlainObject = isPlainObject;
exports.isPromise = isPromise;
exports.isReservedProp = isReservedProp;
exports.isSSRSafeAttrName = isSSRSafeAttrName;
exports.isSVGTag = isSVGTag;
exports.isSet = isSet;
exports.isSpecialBooleanAttr = isSpecialBooleanAttr;
exports.isString = isString;
exports.isSymbol = isSymbol;
exports.isVoidTag = isVoidTag;
exports.looseEqual = looseEqual;
exports.looseIndexOf = looseIndexOf;
exports.makeMap = makeMap;
exports.normalizeClass = normalizeClass;
exports.normalizeStyle = normalizeStyle;
exports.objectToString = objectToString;
exports.parseStringStyle = parseStringStyle;
exports.propsToAttrMap = propsToAttrMap;
exports.remove = remove;
exports.slotFlagsText = slotFlagsText;
exports.stringifyStyle = stringifyStyle;
exports.toDisplayString = toDisplayString;
exports.toHandlerKey = toHandlerKey;
exports.toNumber = toNumber;
exports.toRawType = toRawType;
exports.toTypeString = toTypeString;
});
// node_modules/@vue/shared/index.js
var require_shared = __commonJS((exports, module) => {
"use strict";
if (false) {} else {
module.exports = require_shared_cjs();
}
});
// node_modules/@vue/reactivity/dist/reactivity.cjs.js
var require_reactivity_cjs = __commonJS((exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
var shared = require_shared();
var targetMap = new WeakMap();
var effectStack = [];
var activeEffect;
var ITERATE_KEY = Symbol("iterate");
var MAP_KEY_ITERATE_KEY = Symbol("Map key iterate");
function isEffect(fn) {
return fn && fn._isEffect === true;
}
function effect3(fn, options = shared.EMPTY_OBJ) {
if (isEffect(fn)) {
fn = fn.raw;
}
const effect4 = createReactiveEffect(fn, options);
if (!options.lazy) {
effect4();
}
return effect4;
}
function stop2(effect4) {
if (effect4.active) {
cleanup(effect4);
if (effect4.options.onStop) {
effect4.options.onStop();
}
effect4.active = false;
}
}
var uid = 0;
function createReactiveEffect(fn, options) {
const effect4 = function reactiveEffect() {
if (!effect4.active) {
return fn();
}
if (!effectStack.includes(effect4)) {
cleanup(effect4);
try {
enableTracking();
effectStack.push(effect4);
activeEffect = effect4;
return fn();
} finally {
effectStack.pop();
resetTracking();
activeEffect = effectStack[effectStack.length - 1];
}
}
};
effect4.id = uid++;
effect4.allowRecurse = !!options.allowRecurse;
effect4._isEffect = true;
effect4.active = true;
effect4.raw = fn;
effect4.deps = [];
effect4.options = options;
return effect4;
}
function cleanup(effect4) {
const {deps} = effect4;
if (deps.length) {
for (let i = 0; i < deps.length; i++) {
deps[i].delete(effect4);
}
deps.length = 0;
}
}
var shouldTrack = true;
var trackStack = [];
function pauseTracking() {
trackStack.push(shouldTrack);
shouldTrack = false;
}
function enableTracking() {
trackStack.push(shouldTrack);
shouldTrack = true;
}
function resetTracking() {
const last = trackStack.pop();
shouldTrack = last === void 0 ? true : last;
}
function track(target, type, key) {
if (!shouldTrack || activeEffect === void 0) {
return;
}
let depsMap = targetMap.get(target);
if (!depsMap) {
targetMap.set(target, depsMap = new Map());
}
let dep = depsMap.get(key);
if (!dep) {
depsMap.set(key, dep = new Set());
}
if (!dep.has(activeEffect)) {
dep.add(activeEffect);
activeEffect.deps.push(dep);
if (activeEffect.options.onTrack) {
activeEffect.options.onTrack({
effect: activeEffect,
target,
type,
key
});
}
}
}
function trigger(target, type, key, newValue, oldValue, oldTarget) {
const depsMap = targetMap.get(target);
if (!depsMap) {
return;
}
const effects = new Set();
const add2 = (effectsToAdd) => {
if (effectsToAdd) {
effectsToAdd.forEach((effect4) => {
if (effect4 !== activeEffect || effect4.allowRecurse) {
effects.add(effect4);
}
});
}
};
if (type === "clear") {
depsMap.forEach(add2);
} else if (key === "length" && shared.isArray(target)) {
depsMap.forEach((dep, key2) => {
if (key2 === "length" || key2 >= newValue) {
add2(dep);
}
});
} else {
if (key !== void 0) {
add2(depsMap.get(key));
}
switch (type) {
case "add":
if (!shared.isArray(target)) {
add2(depsMap.get(ITERATE_KEY));
if (shared.isMap(target)) {
add2(depsMap.get(MAP_KEY_ITERATE_KEY));
}
} else if (shared.isIntegerKey(key)) {
add2(depsMap.get("length"));
}
break;
case "delete":
if (!shared.isArray(target)) {
add2(depsMap.get(ITERATE_KEY));
if (shared.isMap(target)) {
add2(depsMap.get(MAP_KEY_ITERATE_KEY));
}
}
break;
case "set":
if (shared.isMap(target)) {
add2(depsMap.get(ITERATE_KEY));
}
break;
}
}
const run = (effect4) => {
if (effect4.options.onTrigger) {
effect4.options.onTrigger({
effect: effect4,
target,
key,
type,
newValue,
oldValue,
oldTarget
});
}
if (effect4.options.scheduler) {
effect4.options.scheduler(effect4);
} else {
effect4();
}
};
effects.forEach(run);
}
var isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`);
var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map((key) => Symbol[key]).filter(shared.isSymbol));
var get2 = /* @__PURE__ */ createGetter();
var shallowGet = /* @__PURE__ */ createGetter(false, true);
var readonlyGet = /* @__PURE__ */ createGetter(true);
var shallowReadonlyGet = /* @__PURE__ */ createGetter(true, true);
var arrayInstrumentations = {};
["includes", "indexOf", "lastIndexOf"].forEach((key) => {
const method = Array.prototype[key];
arrayInstrumentations[key] = function(...args) {
const arr = toRaw2(this);
for (let i = 0, l = this.length; i < l; i++) {
track(arr, "get", i + "");
}
const res = method.apply(arr, args);
if (res === -1 || res === false) {
return method.apply(arr, args.map(toRaw2));
} else {
return res;
}
};
});
["push", "pop", "shift", "unshift", "splice"].forEach((key) => {
const method = Array.prototype[key];
arrayInstrumentations[key] = function(...args) {
pauseTracking();
const res = method.apply(this, args);
resetTracking();
return res;
};
});
function createGetter(isReadonly2 = false, shallow = false) {
return function get3(target, key, receiver) {
if (key === "__v_isReactive") {
return !isReadonly2;
} else if (key === "__v_isReadonly") {
return isReadonly2;
} else if (key === "__v_raw" && receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) {
return target;
}
const targetIsArray = shared.isArray(target);
if (!isReadonly2 && targetIsArray && shared.hasOwn(arrayInstrumentations, key)) {
return Reflect.get(arrayInstrumentations, key, receiver);
}
const res = Reflect.get(target, key, receiver);
if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
return res;
}
if (!isReadonly2) {
track(target, "get", key);
}
if (shallow) {
return res;
}
if (isRef(res)) {
const shouldUnwrap = !targetIsArray || !shared.isIntegerKey(key);
return shouldUnwrap ? res.value : res;
}
if (shared.isObject(res)) {
return isReadonly2 ? readonly(res) : reactive3(res);
}
return res;
};
}
var set2 = /* @__PURE__ */ createSetter();
var shallowSet = /* @__PURE__ */ createSetter(true);
function createSetter(shallow = false) {
return function set3(target, key, value, receiver) {
let oldValue = target[key];
if (!shallow) {
value = toRaw2(value);
oldValue = toRaw2(oldValue);
if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) {
oldValue.value = value;
return true;
}
}
const hadKey = shared.isArray(target) && shared.isIntegerKey(key) ? Number(key) < target.length : shared.hasOwn(target, key);
const result = Reflect.set(target, key, value, receiver);
if (target === toRaw2(receiver)) {
if (!hadKey) {
trigger(target, "add", key, value);
} else if (shared.hasChanged(value, oldValue)) {
trigger(target, "set", key, value, oldValue);
}
}
return result;
};
}
function deleteProperty(target, key) {
const hadKey = shared.hasOwn(target, key);
const oldValue = target[key];
const result = Reflect.deleteProperty(target, key);
if (result && hadKey) {
trigger(target, "delete", key, void 0, oldValue);
}
return result;
}
function has(target, key) {
const result = Reflect.has(target, key);
if (!shared.isSymbol(key) || !builtInSymbols.has(key)) {
track(target, "has", key);
}
return result;
}
function ownKeys(target) {
track(target, "iterate", shared.isArray(target) ? "length" : ITERATE_KEY);
return Reflect.ownKeys(target);
}
var mutableHandlers = {
get: get2,
set: set2,
deleteProperty,
has,
ownKeys
};
var readonlyHandlers = {
get: readonlyGet,
set(target, key) {
{
console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
}
return true;
},
deleteProperty(target, key) {
{
console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
}
return true;
}
};
var shallowReactiveHandlers = shared.extend({}, mutableHandlers, {
get: shallowGet,
set: shallowSet
});
var shallowReadonlyHandlers = shared.extend({}, readonlyHandlers, {
get: shallowReadonlyGet
});
var toReactive = (value) => shared.isObject(value) ? reactive3(value) : value;
var toReadonly = (value) => shared.isObject(value) ? readonly(value) : value;
var toShallow = (value) => value;
var getProto = (v) => Reflect.getPrototypeOf(v);
function get$1(target, key, isReadonly2 = false, isShallow = false) {
target = target["__v_raw"];
const rawTarget = toRaw2(target);
const rawKey = toRaw2(key);
if (key !== rawKey) {
!isReadonly2 && track(rawTarget, "get", key);
}
!isReadonly2 && track(rawTarget, "get", rawKey);
const {has: has2} = getProto(rawTarget);
const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive;
if (has2.call(rawTarget, key)) {
return wrap(target.get(key));
} else if (has2.call(rawTarget, rawKey)) {
return wrap(target.get(rawKey));
} else if (target !== rawTarget) {
target.get(key);
}
}
function has$1(key, isReadonly2 = false) {
const target = this["__v_raw"];
const rawTarget = toRaw2(target);
const rawKey = toRaw2(key);
if (key !== rawKey) {
!isReadonly2 && track(rawTarget, "has", key);
}
!isReadonly2 && track(rawTarget, "has", rawKey);
return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey);
}
function size(target, isReadonly2 = false) {
target = target["__v_raw"];
!isReadonly2 && track(toRaw2(target), "iterate", ITERATE_KEY);
return Reflect.get(target, "size", target);
}
function add(value) {
value = toRaw2(value);
const target = toRaw2(this);
const proto = getProto(target);
const hadKey = proto.has.call(target, value);
if (!hadKey) {
target.add(value);
trigger(target, "add", value, value);
}
return this;
}
function set$1(key, value) {
value = toRaw2(value);
const target = toRaw2(this);
const {has: has2, get: get3} = getProto(target);
let hadKey = has2.call(target, key);
if (!hadKey) {
key = toRaw2(key);
hadKey = has2.call(target, key);
} else {
checkIdentityKeys(target, has2, key);
}
const oldValue = get3.call(target, key);
target.set(key, value);
if (!hadKey) {
trigger(target, "add", key, value);
} else if (shared.hasChanged(value, oldValue)) {
trigger(target, "set", key, value, oldValue);
}
return this;
}
function deleteEntry(key) {
const target = toRaw2(this);
const {has: has2, get: get3} = getProto(target);
let hadKey = has2.call(target, key);
if (!hadKey) {
key = toRaw2(key);
hadKey = has2.call(target, key);
} else {
checkIdentityKeys(target, has2, key);
}
const oldValue = get3 ? get3.call(target, key) : void 0;
const result = target.delete(key);
if (hadKey) {
trigger(target, "delete", key, void 0, oldValue);
}
return result;
}
function clear() {
const target = toRaw2(this);
const hadItems = target.size !== 0;
const oldTarget = shared.isMap(target) ? new Map(target) : new Set(target);
const result = target.clear();
if (hadItems) {
trigger(target, "clear", void 0, void 0, oldTarget);
}
return result;
}
function createForEach(isReadonly2, isShallow) {
return function forEach(callback, thisArg) {
const observed = this;
const target = observed["__v_raw"];
const rawTarget = toRaw2(target);
const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive;
!isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY);
return target.forEach((value, key) => {
return callback.call(thisArg, wrap(value), wrap(key), observed);
});
};
}
function createIterableMethod(method, isReadonly2, isShallow) {
return function(...args) {
const target = this["__v_raw"];
const rawTarget = toRaw2(target);
const targetIsMap = shared.isMap(rawTarget);
const isPair = method === "entries" || method === Symbol.iterator && targetIsMap;
const isKeyOnly = method === "keys" && targetIsMap;
const innerIterator = target[method](...args);
const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive;
!isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
return {
next() {
const {value, done} = innerIterator.next();
return done ? {value, done} : {
value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
done
};
},
[Symbol.iterator]() {
return this;
}
};
};
}
function createReadonlyMethod(type) {
return function(...args) {
{
const key = args[0] ? `on key "${args[0]}" ` : ``;
console.warn(`${shared.capitalize(type)} operation ${key}failed: target is readonly.`, toRaw2(this));
}
return type === "delete" ? false : this;
};
}
var mutableInstrumentations = {
get(key) {
return get$1(this, key);
},
get size() {
return size(this);
},
has: has$1,
add,
set: set$1,
delete: deleteEntry,
clear,
forEach: createForEach(false, false)
};
var shallowInstrumentations = {
get(key) {
return get$1(this, key, false, true);
},
get size() {
return size(this);
},
has: has$1,
add,
set: set$1,
delete: deleteEntry,
clear,
forEach: createForEach(false, true)
};
var readonlyInstrumentations = {
get(key) {
return get$1(this, key, true);
},
get size() {
return size(this, true);
},
has(key) {
return has$1.call(this, key, true);
},
add: createReadonlyMethod("add"),
set: createReadonlyMethod("set"),
delete: createReadonlyMethod("delete"),
clear: createReadonlyMethod("clear"),
forEach: createForEach(true, false)
};
var shallowReadonlyInstrumentations = {
get(key) {
return get$1(this, key, true, true);
},
get size() {
return size(this, true);
},
has(key) {
return has$1.call(this, key, true);
},
add: createReadonlyMethod("add"),
set: createReadonlyMethod("set"),
delete: createReadonlyMethod("delete"),
clear: createReadonlyMethod("clear"),
forEach: createForEach(true, true)
};
var iteratorMethods = ["keys", "values", "entries", Symbol.iterator];
iteratorMethods.forEach((method) => {
mutableInstrumentations[method] = createIterableMethod(method, false, false);
readonlyInstrumentations[method] = createIterableMethod(method, true, false);
shallowInstrumentations[method] = createIterableMethod(method, false, true);
shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
});
function createInstrumentationGetter(isReadonly2, shallow) {
const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations;
return (target, key, receiver) => {
if (key === "__v_isReactive") {
return !isReadonly2;
} else if (key === "__v_isReadonly") {
return isReadonly2;
} else if (key === "__v_raw") {
return target;
}
return Reflect.get(shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver);
};
}
var mutableCollectionHandlers = {
get: createInstrumentationGetter(false, false)
};
var shallowCollectionHandlers = {
get: createInstrumentationGetter(false, true)
};
var readonlyCollectionHandlers = {
get: createInstrumentationGetter(true, false)
};
var shallowReadonlyCollectionHandlers = {
get: createInstrumentationGetter(true, true)
};
function checkIdentityKeys(target, has2, key) {
const rawKey = toRaw2(key);
if (rawKey !== key && has2.call(target, rawKey)) {
const type = shared.toRawType(target);
console.warn(`Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`);
}
}
var reactiveMap = new WeakMap();
var shallowReactiveMap = new WeakMap();
var readonlyMap = new WeakMap();
var shallowReadonlyMap = new WeakMap();
function targetTypeMap(rawType) {
switch (rawType) {
case "Object":
case "Array":
return 1;
case "Map":
case "Set":
case "WeakMap":
case "WeakSet":
return 2;
default:
return 0;
}
}
function getTargetType(value) {
return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(shared.toRawType(value));
}
function reactive3(target) {
if (target && target["__v_isReadonly"]) {
return target;
}
return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
}
function shallowReactive(target) {
return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
}
function readonly(target) {
return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
}
function shallowReadonly(target) {
return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
}
function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) {
if (!shared.isObject(target)) {
{
console.warn(`value cannot be made reactive: ${String(target)}`);
}
return target;
}
if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) {
return target;
}
const existingProxy = proxyMap.get(target);
if (existingProxy) {
return existingProxy;
}
const targetType = getTargetType(target);
if (targetType === 0) {
return target;
}
const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers);
proxyMap.set(target, proxy);
return proxy;
}
function isReactive2(value) {
if (isReadonly(value)) {
return isReactive2(value["__v_raw"]);
}
return !!(value && value["__v_isReactive"]);
}
function isReadonly(value) {
return !!(value && value["__v_isReadonly"]);
}
function isProxy(value) {
return isReactive2(value) || isReadonly(value);
}
function toRaw2(observed) {
return observed && toRaw2(observed["__v_raw"]) || observed;
}
function markRaw(value) {
shared.def(value, "__v_skip", true);
return value;
}
var convert = (val) => shared.isObject(val) ? reactive3(val) : val;
function isRef(r) {
return Boolean(r && r.__v_isRef === true);
}
function ref(value) {
return createRef(value);
}
function shallowRef(value) {
return createRef(value, true);
}
var RefImpl = class {
constructor(_rawValue, _shallow = false) {
this._rawValue = _rawValue;
this._shallow = _shallow;
this.__v_isRef = true;
this._value = _shallow ? _rawValue : convert(_rawValue);
}
get value() {
track(toRaw2(this), "get", "value");
return this._value;
}
set value(newVal) {
if (shared.hasChanged(toRaw2(newVal), this._rawValue)) {
this._rawValue = newVal;
this._value = this._shallow ? newVal : convert(newVal);
trigger(toRaw2(this), "set", "value", newVal);
}
}
};
function createRef(rawValue, shallow = false) {
if (isRef(rawValue)) {
return rawValue;
}
return new RefImpl(rawValue, shallow);
}
function triggerRef(ref2) {
trigger(toRaw2(ref2), "set", "value", ref2.value);
}
function unref(ref2) {
return isRef(ref2) ? ref2.value : ref2;
}
var shallowUnwrapHandlers = {
get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
set: (target, key, value, receiver) => {
const oldValue = target[key];
if (isRef(oldValue) && !isRef(value)) {
oldValue.value = value;
return true;
} else {
return Reflect.set(target, key, value, receiver);
}
}
};
function proxyRefs(objectWithRefs) {
return isReactive2(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers);
}
var CustomRefImpl = class {
constructor(factory) {
this.__v_isRef = true;
const {get: get3, set: set3} = factory(() => track(this, "get", "value"), () => trigger(this, "set", "value"));
this._get = get3;
this._set = set3;
}
get value() {
return this._get();
}
set value(newVal) {
this._set(newVal);
}
};
function customRef(factory) {
return new CustomRefImpl(factory);
}
function toRefs(object) {
if (!isProxy(object)) {
console.warn(`toRefs() expects a reactive object but received a plain one.`);
}
const ret = shared.isArray(object) ? new Array(object.length) : {};
for (const key in object) {
ret[key] = toRef(object, key);
}
return ret;
}
var ObjectRefImpl = class {
constructor(_object, _key) {
this._object = _object;
this._key = _key;
this.__v_isRef = true;
}
get value() {
return this._object[this._key];
}
set value(newVal) {
this._object[this._key] = newVal;
}
};
function toRef(object, key) {
return isRef(object[key]) ? object[key] : new ObjectRefImpl(object, key);
}
var ComputedRefImpl = class {
constructor(getter, _setter, isReadonly2) {
this._setter = _setter;
this._dirty = true;
this.__v_isRef = true;
this.effect = effect3(getter, {
lazy: true,
scheduler: () => {
if (!this._dirty) {
this._dirty = true;
trigger(toRaw2(this), "set", "value");
}
}
});
this["__v_isReadonly"] = isReadonly2;
}
get value() {
const self2 = toRaw2(this);
if (self2._dirty) {
self2._value = this.effect();
self2._dirty = false;
}
track(self2, "get", "value");
return self2._value;
}
set value(newValue) {
this._setter(newValue);
}
};
function computed(getterOrOptions) {
let getter;
let setter;
if (shared.isFunction(getterOrOptions)) {
getter = getterOrOptions;
setter = () => {
console.warn("Write operation failed: computed value is readonly");
};
} else {
getter = getterOrOptions.get;
setter = getterOrOptions.set;
}
return new ComputedRefImpl(getter, setter, shared.isFunction(getterOrOptions) || !getterOrOptions.set);
}
exports.ITERATE_KEY = ITERATE_KEY;
exports.computed = computed;
exports.customRef = customRef;
exports.effect = effect3;
exports.enableTracking = enableTracking;
exports.isProxy = isProxy;
exports.isReactive = isReactive2;
exports.isReadonly = isReadonly;
exports.isRef = isRef;
exports.markRaw = markRaw;
exports.pauseTracking = pauseTracking;
exports.proxyRefs = proxyRefs;
exports.reactive = reactive3;
exports.readonly = readonly;
exports.ref = ref;
exports.resetTracking = resetTracking;
exports.shallowReactive = shallowReactive;
exports.shallowReadonly = shallowReadonly;
exports.shallowRef = shallowRef;
exports.stop = stop2;
exports.toRaw = toRaw2;
exports.toRef = toRef;
exports.toRefs = toRefs;
exports.track = track;
exports.trigger = trigger;
exports.triggerRef = triggerRef;
exports.unref = unref;
});
// node_modules/@vue/reactivity/index.js
var require_reactivity = __commonJS((exports, module) => {
"use strict";
if (false) {} else {
module.exports = require_reactivity_cjs();
}
});
// packages/alpinejs/src/scheduler.js
var flushPending = false;
var flushing = false;
var queue = [];
function scheduler(callback) {
queueJob(callback);
}
function queueJob(job) {
if (!queue.includes(job))
queue.push(job);
queueFlush();
}
function queueFlush() {
if (!flushing && !flushPending) {
flushPending = true;
queueMicrotask(flushJobs);
}
}
function flushJobs() {
flushPending = false;
flushing = true;
for (let i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
flushing = false;
}
// packages/alpinejs/src/reactivity.js
var reactive;
var effect;
var release;
var raw;
var shouldSchedule = true;
function disableEffectScheduling(callback) {
shouldSchedule = false;
callback();
shouldSchedule = true;
}
function setReactivityEngine(engine) {
reactive = engine.reactive;
release = engine.release;
effect = (callback) => engine.effect(callback, {scheduler: (task) => {
if (shouldSchedule) {
scheduler(task);
} else {
task();
}
}});
raw = engine.raw;
}
function overrideEffect(override) {
effect = override;
}
function elementBoundEffect(el) {
let cleanup = () => {
};
let wrappedEffect = (callback) => {
let effectReference = effect(callback);
if (!el._x_effects) {
el._x_effects = new Set();
el._x_runEffects = () => {
el._x_effects.forEach((i) => i());
};
}
el._x_effects.add(effectReference);
cleanup = () => {
if (effectReference === void 0)
return;
el._x_effects.delete(effectReference);
release(effectReference);
};
};
return [wrappedEffect, () => {
cleanup();
}];
}
// packages/alpinejs/src/mutation.js
var onAttributeAddeds = [];
var onElRemoveds = [];
var onElAddeds = [];
function onElAdded(callback) {
onElAddeds.push(callback);
}
function onElRemoved(callback) {
onElRemoveds.push(callback);
}
function onAttributesAdded(callback) {
onAttributeAddeds.push(callback);
}
function onAttributeRemoved(el, name, callback) {
if (!el._x_attributeCleanups)
el._x_attributeCleanups = {};
if (!el._x_attributeCleanups[name])
el._x_attributeCleanups[name] = [];
el._x_attributeCleanups[name].push(callback);
}
function cleanupAttributes(el, names) {
if (!el._x_attributeCleanups)
return;
Object.entries(el._x_attributeCleanups).forEach(([name, value]) => {
if (names === void 0 || names.includes(name)) {
value.forEach((i) => i());
delete el._x_attributeCleanups[name];
}
});
}
var observer = new MutationObserver(onMutate);
var currentlyObserving = false;
function startObservingMutations() {
observer.observe(document, {subtree: true, childList: true, attributes: true, attributeOldValue: true});
currentlyObserving = true;
}
function stopObservingMutations() {
flushObserver();
observer.disconnect();
currentlyObserving = false;
}
var recordQueue = [];
var willProcessRecordQueue = false;
function flushObserver() {
recordQueue = recordQueue.concat(observer.takeRecords());
if (recordQueue.length && !willProcessRecordQueue) {
willProcessRecordQueue = true;
queueMicrotask(() => {
processRecordQueue();
willProcessRecordQueue = false;
});
}
}
function processRecordQueue() {
onMutate(recordQueue);
recordQueue.length = 0;
}
function mutateDom(callback) {
if (!currentlyObserving)
return callback();
stopObservingMutations();
let result = callback();
startObservingMutations();
return result;
}
var isCollecting = false;
var deferredMutations = [];
function deferMutations() {
isCollecting = true;
}
function flushAndStopDeferringMutations() {
isCollecting = false;
onMutate(deferredMutations);
deferredMutations = [];
}
function onMutate(mutations) {
if (isCollecting) {
deferredMutations = deferredMutations.concat(mutations);
return;
}
let addedNodes = [];
let removedNodes = [];
let addedAttributes = new Map();
let removedAttributes = new Map();
for (let i = 0; i < mutations.length; i++) {
if (mutations[i].target._x_ignoreMutationObserver)
continue;
if (mutations[i].type === "childList") {
mutations[i].addedNodes.forEach((node) => node.nodeType === 1 && addedNodes.push(node));
mutations[i].removedNodes.forEach((node) => node.nodeType === 1 && removedNodes.push(node));
}
if (mutations[i].type === "attributes") {
let el = mutations[i].target;
let name = mutations[i].attributeName;
let oldValue = mutations[i].oldValue;
let add = () => {
if (!addedAttributes.has(el))
addedAttributes.set(el, []);
addedAttributes.get(el).push({name, value: el.getAttribute(name)});
};
let remove = () => {
if (!removedAttributes.has(el))
removedAttributes.set(el, []);
removedAttributes.get(el).push(name);
};
if (el.hasAttribute(name) && oldValue === null) {
add();
} else if (el.hasAttribute(name)) {
remove();
add();
} else {
remove();
}
}
}
removedAttributes.forEach((attrs, el) => {
cleanupAttributes(el, attrs);
});
addedAttributes.forEach((attrs, el) => {
onAttributeAddeds.forEach((i) => i(el, attrs));
});
addedNodes.forEach((node) => {
node._x_ignoreSelf = true;
node._x_ignore = true;
});
for (let node of addedNodes) {
if (removedNodes.includes(node))
continue;
delete node._x_ignoreSelf;
delete node._x_ignore;
onElAddeds.forEach((i) => i(node));
node._x_ignore = true;
node._x_ignoreSelf = true;
}
addedNodes.forEach((node) => {
delete node._x_ignoreSelf;
delete node._x_ignore;
});
for (let node of removedNodes) {
if (addedNodes.includes(node))
continue;
onElRemoveds.forEach((i) => i(node));
}
addedNodes = null;
removedNodes = null;
addedAttributes = null;
removedAttributes = null;
}
// packages/alpinejs/src/scope.js
function addScopeToNode(node, data2, referenceNode) {
node._x_dataStack = [data2, ...closestDataStack(referenceNode || node)];
return () => {
node._x_dataStack = node._x_dataStack.filter((i) => i !== data2);
};
}
function refreshScope(element, scope) {
let existingScope = element._x_dataStack[0];
Object.entries(scope).forEach(([key, value]) => {
existingScope[key] = value;
});
}
function closestDataStack(node) {
if (node._x_dataStack)
return node._x_dataStack;
if (typeof ShadowRoot === "function" && node instanceof ShadowRoot) {
return closestDataStack(node.host);
}
if (!node.parentNode) {
return [];
}
return closestDataStack(node.parentNode);
}
function mergeProxies(objects) {
let thisProxy = new Proxy({}, {
ownKeys: () => {
return Array.from(new Set(objects.flatMap((i) => Object.keys(i))));
},
has: (target, name) => {
return objects.some((obj) => obj.hasOwnProperty(name));
},
get: (target, name) => {
return (objects.find((obj) => {
if (obj.hasOwnProperty(name)) {
let descriptor = Object.getOwnPropertyDescriptor(obj, name);
if (descriptor.get && descriptor.get._x_alreadyBound || descriptor.set && descriptor.set._x_alreadyBound) {
return true;
}
if ((descriptor.get || descriptor.set) && descriptor.enumerable) {
let getter = descriptor.get;
let setter = descriptor.set;
let property = descriptor;
getter = getter && getter.bind(thisProxy);
setter = setter && setter.bind(thisProxy);
if (getter)
getter._x_alreadyBound = true;
if (setter)
setter._x_alreadyBound = true;
Object.defineProperty(obj, name, {
...property,
get: getter,
set: setter
});
}
return true;
}
return false;
}) || {})[name];
},
set: (target, name, value) => {
let closestObjectWithKey = objects.find((obj) => obj.hasOwnProperty(name));
if (closestObjectWithKey) {
closestObjectWithKey[name] = value;
} else {
objects[objects.length - 1][name] = value;
}
return true;
}
});
return thisProxy;
}
// packages/alpinejs/src/interceptor.js
function initInterceptors(data2) {
let isObject = (val) => typeof val === "object" && !Array.isArray(val) && val !== null;
let recurse = (obj, basePath = "") => {
Object.entries(Object.getOwnPropertyDescriptors(obj)).forEach(([key, {value, enumerable}]) => {
if (enumerable === false || value === void 0)
return;
let path = basePath === "" ? key : `${basePath}.${key}`;
if (typeof value === "object" && value !== null && value._x_interceptor) {
obj[key] = value.initialize(data2, path, key);
} else {
if (isObject(value) && value !== obj && !(value instanceof Element)) {
recurse(value, path);
}
}
});
};
return recurse(data2);
}
function interceptor(callback, mutateObj = () => {
}) {
let obj = {
initialValue: void 0,
_x_interceptor: true,
initialize(data2, path, key) {
return callback(this.initialValue, () => get(data2, path), (value) => set(data2, path, value), path, key);
}
};
mutateObj(obj);
return (initialValue) => {
if (typeof initialValue === "object" && initialValue !== null && initialValue._x_interceptor) {
let initialize = obj.initialize.bind(obj);
obj.initialize = (data2, path, key) => {
let innerValue = initialValue.initialize(data2, path, key);
obj.initialValue = innerValue;
return initialize(data2, path, key);
};
} else {
obj.initialValue = initialValue;
}
return obj;
};
}
function get(obj, path) {
return path.split(".").reduce((carry, segment) => carry[segment], obj);
}
function set(obj, path, value) {
if (typeof path === "string")
path = path.split(".");
if (path.length === 1)
obj[path[0]] = value;
else if (path.length === 0)
throw error;
else {
if (obj[path[0]])
return set(obj[path[0]], path.slice(1), value);
else {
obj[path[0]] = {};
return set(obj[path[0]], path.slice(1), value);
}
}
}
// packages/alpinejs/src/magics.js
var magics = {};
function magic(name, callback) {
magics[name] = callback;
}
function injectMagics(obj, el) {
Object.entries(magics).forEach(([name, callback]) => {
Object.defineProperty(obj, `$${name}`, {
get() {
return callback(el, {Alpine: alpine_default, interceptor});
},
enumerable: false
});
});
return obj;
}
// packages/alpinejs/src/utils/error.js
function tryCatch(el, expression, callback, ...args) {
try {
return callback(...args);
} catch (e) {
handleError(e, el, expression);
}
}
function handleError(error2, el, expression = void 0) {
Object.assign(error2, {el, expression});
console.warn(`Alpine Expression Error: ${error2.message}
${expression ? 'Expression: "' + expression + '"\n\n' : ""}`, el);
setTimeout(() => {
throw error2;
}, 0);
}
// packages/alpinejs/src/evaluator.js
function evaluate(el, expression, extras = {}) {
let result;
evaluateLater(el, expression)((value) => result = value, extras);
return result;
}
function evaluateLater(...args) {
return theEvaluatorFunction(...args);
}
var theEvaluatorFunction = normalEvaluator;
function setEvaluator(newEvaluator) {
theEvaluatorFunction = newEvaluator;
}
function normalEvaluator(el, expression) {
let overriddenMagics = {};
injectMagics(overriddenMagics, el);
let dataStack = [overriddenMagics, ...closestDataStack(el)];
if (typeof expression === "function") {
return generateEvaluatorFromFunction(dataStack, expression);
}
let evaluator = generateEvaluatorFromString(dataStack, expression, el);
return tryCatch.bind(null, el, expression, evaluator);
}
function generateEvaluatorFromFunction(dataStack, func) {
return (receiver = () => {
}, {scope = {}, params = []} = {}) => {
let result = func.apply(mergeProxies([scope, ...dataStack]), params);
runIfTypeOfFunction(receiver, result);
};
}
var evaluatorMemo = {};
function generateFunctionFromString(expression, el) {
if (evaluatorMemo[expression]) {
return evaluatorMemo[expression];
}
let AsyncFunction = Object.getPrototypeOf(async function() {
}).constructor;
let rightSideSafeExpression = /^[\n\s]*if.*\(.*\)/.test(expression) || /^(let|const)\s/.test(expression) ? `(() => { ${expression} })()` : expression;
const safeAsyncFunction = () => {
try {
return new AsyncFunction(["__self", "scope"], `with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`);
} catch (error2) {
handleError(error2, el, expression);
return Promise.resolve();
}
};
let func = safeAsyncFunction();
evaluatorMemo[expression] = func;
return func;
}
function generateEvaluatorFromString(dataStack, expression, el) {
let func = generateFunctionFromString(expression, el);
return (receiver = () => {
}, {scope = {}, params = []} = {}) => {
func.result = void 0;
func.finished = false;
let completeScope = mergeProxies([scope, ...dataStack]);
if (typeof func === "function") {
let promise = func(func, completeScope).catch((error2) => handleError(error2, el, expression));
if (func.finished) {
runIfTypeOfFunction(receiver, func.result, completeScope, params, el);
func.result = void 0;
} else {
promise.then((result) => {
runIfTypeOfFunction(receiver, result, completeScope, params, el);
}).catch((error2) => handleError(error2, el, expression)).finally(() => func.result = void 0);
}
}
};
}
function runIfTypeOfFunction(receiver, value, scope, params, el) {
if (typeof value === "function") {
let result = value.apply(scope, params);
if (result instanceof Promise) {
result.then((i) => runIfTypeOfFunction(receiver, i, scope, params)).catch((error2) => handleError(error2, el, value));
} else {
receiver(result);
}
} else {
receiver(value);
}
}
// packages/alpinejs/src/directives.js
var prefixAsString = "x-";
function prefix(subject = "") {
return prefixAsString + subject;
}
function setPrefix(newPrefix) {
prefixAsString = newPrefix;
}
var directiveHandlers = {};
function directive(name, callback) {
directiveHandlers[name] = callback;
}
function directives(el, attributes, originalAttributeOverride) {
let transformedAttributeMap = {};
let directives2 = Array.from(attributes).map(toTransformedAttributes((newName, oldName) => transformedAttributeMap[newName] = oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap, originalAttributeOverride)).sort(byPriority);
return directives2.map((directive2) => {
return getDirectiveHandler(el, directive2);
});
}
function attributesOnly(attributes) {
return Array.from(attributes).map(toTransformedAttributes()).filter((attr) => !outNonAlpineAttributes(attr));
}
var isDeferringHandlers = false;
var directiveHandlerStacks = new Map();
var currentHandlerStackKey = Symbol();
function deferHandlingDirectives(callback) {
isDeferringHandlers = true;
let key = Symbol();
currentHandlerStackKey = key;
directiveHandlerStacks.set(key, []);
let flushHandlers = () => {
while (directiveHandlerStacks.get(key).length)
directiveHandlerStacks.get(key).shift()();
directiveHandlerStacks.delete(key);
};
let stopDeferring = () => {
isDeferringHandlers = false;
flushHandlers();
};
callback(flushHandlers);
stopDeferring();
}
function getDirectiveHandler(el, directive2) {
let noop = () => {
};
let handler3 = directiveHandlers[directive2.type] || noop;
let cleanups = [];
let cleanup = (callback) => cleanups.push(callback);
let [effect3, cleanupEffect] = elementBoundEffect(el);
cleanups.push(cleanupEffect);
let utilities = {
Alpine: alpine_default,
effect: effect3,
cleanup,
evaluateLater: evaluateLater.bind(evaluateLater, el),
evaluate: evaluate.bind(evaluate, el)
};
let doCleanup = () => cleanups.forEach((i) => i());
onAttributeRemoved(el, directive2.original, doCleanup);
let fullHandler = () => {
if (el._x_ignore || el._x_ignoreSelf)
return;
handler3.inline && handler3.inline(el, directive2, utilities);
handler3 = handler3.bind(handler3, el, directive2, utilities);
isDeferringHandlers ? directiveHandlerStacks.get(currentHandlerStackKey).push(handler3) : handler3();
};
fullHandler.runCleanups = doCleanup;
return fullHandler;
}
var startingWith = (subject, replacement) => ({name, value}) => {
if (name.startsWith(subject))
name = name.replace(subject, replacement);
return {name, value};
};
var into = (i) => i;
function toTransformedAttributes(callback = () => {
}) {
return ({name, value}) => {
let {name: newName, value: newValue} = attributeTransformers.reduce((carry, transform) => {
return transform(carry);
}, {name, value});
if (newName !== name)
callback(newName, name);
return {name: newName, value: newValue};
};
}
var attributeTransformers = [];
function mapAttributes(callback) {
attributeTransformers.push(callback);
}
function outNonAlpineAttributes({name}) {
return alpineAttributeRegex().test(name);
}
var alpineAttributeRegex = () => new RegExp(`^${prefixAsString}([^:^.]+)\\b`);
function toParsedDirectives(transformedAttributeMap, originalAttributeOverride) {
return ({name, value}) => {
let typeMatch = name.match(alpineAttributeRegex());
let valueMatch = name.match(/:([a-zA-Z0-9\-:]+)/);
let modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || [];
let original = originalAttributeOverride || transformedAttributeMap[name] || name;
return {
type: typeMatch ? typeMatch[1] : null,
value: valueMatch ? valueMatch[1] : null,
modifiers: modifiers.map((i) => i.replace(".", "")),
expression: value,
original
};
};
}
var DEFAULT = "DEFAULT";
var directiveOrder = [
"ignore",
"ref",
"data",
"bind",
"init",
"for",
"model",
"transition",
"show",
"if",
DEFAULT,
"element"
];
function byPriority(a, b) {
let typeA = directiveOrder.indexOf(a.type) === -1 ? DEFAULT : a.type;
let typeB = directiveOrder.indexOf(b.type) === -1 ? DEFAULT : b.type;
return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB);
}
// packages/alpinejs/src/utils/dispatch.js
function dispatch(el, name, detail = {}) {
el.dispatchEvent(new CustomEvent(name, {
detail,
bubbles: true,
composed: true,
cancelable: true
}));
}
// packages/alpinejs/src/nextTick.js
var tickStack = [];
var isHolding = false;
function nextTick(callback) {
tickStack.push(callback);
queueMicrotask(() => {
isHolding || setTimeout(() => {
releaseNextTicks();
});
});
}
function releaseNextTicks() {
isHolding = false;
while (tickStack.length)
tickStack.shift()();
}
function holdNextTicks() {
isHolding = true;
}
// packages/alpinejs/src/utils/walk.js
function walk(el, callback) {
if (typeof ShadowRoot === "function" && el instanceof ShadowRoot) {
Array.from(el.children).forEach((el2) => walk(el2, callback));
return;
}
let skip = false;
callback(el, () => skip = true);
if (skip)
return;
let node = el.firstElementChild;
while (node) {
walk(node, callback, false);
node = node.nextElementSibling;
}
}
// packages/alpinejs/src/utils/warn.js
function warn(message, ...args) {
console.warn(`Alpine Warning: ${message}`, ...args);
}
// packages/alpinejs/src/lifecycle.js
function start() {
if (!document.body)
warn("Unable to initialize. Trying to load Alpine before `<body>` is available. Did you forget to add `defer` in Alpine's `<script>` tag?");
dispatch(document, "alpine:init");
dispatch(document, "alpine:initializing");
startObservingMutations();
onElAdded((el) => initTree(el, walk));
onElRemoved((el) => nextTick(() => destroyTree(el)));
onAttributesAdded((el, attrs) => {
directives(el, attrs).forEach((handle) => handle());
});
let outNestedComponents = (el) => !closestRoot(el.parentElement, true);
Array.from(document.querySelectorAll(allSelectors())).filter(outNestedComponents).forEach((el) => {
initTree(el);
});
dispatch(document, "alpine:initialized");
}
var rootSelectorCallbacks = [];
var initSelectorCallbacks = [];
function rootSelectors() {
return rootSelectorCallbacks.map((fn) => fn());
}
function allSelectors() {
return rootSelectorCallbacks.concat(initSelectorCallbacks).map((fn) => fn());
}
function addRootSelector(selectorCallback) {
rootSelectorCallbacks.push(selectorCallback);
}
function addInitSelector(selectorCallback) {
initSelectorCallbacks.push(selectorCallback);
}
function closestRoot(el, includeInitSelectors = false) {
if (!el)
return;
const selectors = includeInitSelectors ? allSelectors() : rootSelectors();
if (selectors.some((selector) => el.matches(selector)))
return el;
if (!el.parentElement)
return;
return closestRoot(el.parentElement, includeInitSelectors);
}
function isRoot(el) {
return rootSelectors().some((selector) => el.matches(selector));
}
function initTree(el, walker = walk) {
deferHandlingDirectives(() => {
walker(el, (el2, skip) => {
directives(el2, el2.attributes).forEach((handle) => handle());
el2._x_ignore && skip();
});
});
}
function destroyTree(root) {
walk(root, (el) => cleanupAttributes(el));
}
// packages/alpinejs/src/utils/classes.js
function setClasses(el, value) {
if (Array.isArray(value)) {
return setClassesFromString(el, value.join(" "));
} else if (typeof value === "object" && value !== null) {
return setClassesFromObject(el, value);
} else if (typeof value === "function") {
return setClasses(el, value());
}
return setClassesFromString(el, value);
}
function setClassesFromString(el, classString) {
let split = (classString2) => classString2.split(" ").filter(Boolean);
let missingClasses = (classString2) => classString2.split(" ").filter((i) => !el.classList.contains(i)).filter(Boolean);
let addClassesAndReturnUndo = (classes) => {
el.classList.add(...classes);
return () => {
el.classList.remove(...classes);
};
};
classString = classString === true ? classString = "" : classString || "";
return addClassesAndReturnUndo(missingClasses(classString));
}
function setClassesFromObject(el, classObject) {
let split = (classString) => classString.split(" ").filter(Boolean);
let forAdd = Object.entries(classObject).flatMap(([classString, bool]) => bool ? split(classString) : false).filter(Boolean);
let forRemove = Object.entries(classObject).flatMap(([classString, bool]) => !bool ? split(classString) : false).filter(Boolean);
let added = [];
let removed = [];
forRemove.forEach((i) => {
if (el.classList.contains(i)) {
el.classList.remove(i);
removed.push(i);
}
});
forAdd.forEach((i) => {
if (!el.classList.contains(i)) {
el.classList.add(i);
added.push(i);
}
});
return () => {
removed.forEach((i) => el.classList.add(i));
added.forEach((i) => el.classList.remove(i));
};
}
// packages/alpinejs/src/utils/styles.js
function setStyles(el, value) {
if (typeof value === "object" && value !== null) {
return setStylesFromObject(el, value);
}
return setStylesFromString(el, value);
}
function setStylesFromObject(el, value) {
let previousStyles = {};
Object.entries(value).forEach(([key, value2]) => {
previousStyles[key] = el.style[key];
el.style.setProperty(kebabCase(key), value2);
});
setTimeout(() => {
if (el.style.length === 0) {
el.removeAttribute("style");
}
});
return () => {
setStyles(el, previousStyles);
};
}
function setStylesFromString(el, value) {
let cache = el.getAttribute("style", value);
el.setAttribute("style", value);
return () => {
el.setAttribute("style", cache);
};
}
function kebabCase(subject) {
return subject.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
// packages/alpinejs/src/utils/once.js
function once(callback, fallback = () => {
}) {
let called = false;
return function() {
if (!called) {
called = true;
callback.apply(this, arguments);
} else {
fallback.apply(this, arguments);
}
};
}
// packages/alpinejs/src/directives/x-transition.js
directive("transition", (el, {value, modifiers, expression}, {evaluate: evaluate2}) => {
if (typeof expression === "function")
expression = evaluate2(expression);
if (!expression) {
registerTransitionsFromHelper(el, modifiers, value);
} else {
registerTransitionsFromClassString(el, expression, value);
}
});
function registerTransitionsFromClassString(el, classString, stage) {
registerTransitionObject(el, setClasses, "");
let directiveStorageMap = {
enter: (classes) => {
el._x_transition.enter.during = classes;
},
"enter-start": (classes) => {
el._x_transition.enter.start = classes;
},
"enter-end": (classes) => {
el._x_transition.enter.end = classes;
},
leave: (classes) => {
el._x_transition.leave.during = classes;
},
"leave-start": (classes) => {
el._x_transition.leave.start = classes;
},
"leave-end": (classes) => {
el._x_transition.leave.end = classes;
}
};
directiveStorageMap[stage](classString);
}
function registerTransitionsFromHelper(el, modifiers, stage) {
registerTransitionObject(el, setStyles);
let doesntSpecify = !modifiers.includes("in") && !modifiers.includes("out") && !stage;
let transitioningIn = doesntSpecify || modifiers.includes("in") || ["enter"].includes(stage);
let transitioningOut = doesntSpecify || modifiers.includes("out") || ["leave"].includes(stage);
if (modifiers.includes("in") && !doesntSpecify) {
modifiers = modifiers.filter((i, index) => index < modifiers.indexOf("out"));
}
if (modifiers.includes("out") && !doesntSpecify) {
modifiers = modifiers.filter((i, index) => index > modifiers.indexOf("out"));
}
let wantsAll = !modifiers.includes("opacity") && !modifiers.includes("scale");
let wantsOpacity = wantsAll || modifiers.includes("opacity");
let wantsScale = wantsAll || modifiers.includes("scale");
let opacityValue = wantsOpacity ? 0 : 1;
let scaleValue = wantsScale ? modifierValue(modifiers, "scale", 95) / 100 : 1;
let delay = modifierValue(modifiers, "delay", 0);
let origin = modifierValue(modifiers, "origin", "center");
let property = "opacity, transform";
let durationIn = modifierValue(modifiers, "duration", 150) / 1e3;
let durationOut = modifierValue(modifiers, "duration", 75) / 1e3;
let easing = `cubic-bezier(0.4, 0.0, 0.2, 1)`;
if (transitioningIn) {
el._x_transition.enter.during = {
transformOrigin: origin,
transitionDelay: delay,
transitionProperty: property,
transitionDuration: `${durationIn}s`,
transitionTimingFunction: easing
};
el._x_transition.enter.start = {
opacity: opacityValue,
transform: `scale(${scaleValue})`
};
el._x_transition.enter.end = {
opacity: 1,
transform: `scale(1)`
};
}
if (transitioningOut) {
el._x_transition.leave.during = {
transformOrigin: origin,
transitionDelay: delay,
transitionProperty: property,
transitionDuration: `${durationOut}s`,
transitionTimingFunction: easing
};
el._x_transition.leave.start = {
opacity: 1,
transform: `scale(1)`
};
el._x_transition.leave.end = {
opacity: opacityValue,
transform: `scale(${scaleValue})`
};
}
}
function registerTransitionObject(el, setFunction, defaultValue = {}) {
if (!el._x_transition)
el._x_transition = {
enter: {during: defaultValue, start: defaultValue, end: defaultValue},
leave: {during: defaultValue, start: defaultValue, end: defaultValue},
in(before = () => {
}, after = () => {
}) {
transition(el, setFunction, {
during: this.enter.during,
start: this.enter.start,
end: this.enter.end
}, before, after);
},
out(before = () => {
}, after = () => {
}) {
transition(el, setFunction, {
during: this.leave.during,
start: this.leave.start,
end: this.leave.end
}, before, after);
}
};
}
window.Element.prototype._x_toggleAndCascadeWithTransitions = function(el, value, show, hide) {
let clickAwayCompatibleShow = () => {
document.visibilityState === "visible" ? requestAnimationFrame(show) : setTimeout(show);
};
if (value) {
if (el._x_transition && (el._x_transition.enter || el._x_transition.leave)) {
el._x_transition.enter && (Object.entries(el._x_transition.enter.during).length || Object.entries(el._x_transition.enter.start).length || Object.entries(el._x_transition.enter.end).length) ? el._x_transition.in(show) : clickAwayCompatibleShow();
} else {
el._x_transition ? el._x_transition.in(show) : clickAwayCompatibleShow();
}
return;
}
el._x_hidePromise = el._x_transition ? new Promise((resolve, reject) => {
el._x_transition.out(() => {
}, () => resolve(hide));
el._x_transitioning.beforeCancel(() => reject({isFromCancelledTransition: true}));
}) : Promise.resolve(hide);
queueMicrotask(() => {
let closest = closestHide(el);
if (closest) {
if (!closest._x_hideChildren)
closest._x_hideChildren = [];
closest._x_hideChildren.push(el);
} else {
queueMicrotask(() => {
let hideAfterChildren = (el2) => {
let carry = Promise.all([
el2._x_hidePromise,
...(el2._x_hideChildren || []).map(hideAfterChildren)
]).then(([i]) => i());
delete el2._x_hidePromise;
delete el2._x_hideChildren;
return carry;
};
hideAfterChildren(el).catch((e) => {
if (!e.isFromCancelledTransition)
throw e;
});
});
}
});
};
function closestHide(el) {
let parent = el.parentNode;
if (!parent)
return;
return parent._x_hidePromise ? parent : closestHide(parent);
}
function transition(el, setFunction, {during, start: start2, end} = {}, before = () => {
}, after = () => {
}) {
if (el._x_transitioning)
el._x_transitioning.cancel();
if (Object.keys(during).length === 0 && Object.keys(start2).length === 0 && Object.keys(end).length === 0) {
before();
after();
return;
}
let undoStart, undoDuring, undoEnd;
performTransition(el, {
start() {
undoStart = setFunction(el, start2);
},
during() {
undoDuring = setFunction(el, during);
},
before,
end() {
undoStart();
undoEnd = setFunction(el, end);
},
after,
cleanup() {
undoDuring();
undoEnd();
}
});
}
function performTransition(el, stages) {
let interrupted, reachedBefore, reachedEnd;
let finish = once(() => {
mutateDom(() => {
interrupted = true;
if (!reachedBefore)
stages.before();
if (!reachedEnd) {
stages.end();
releaseNextTicks();
}
stages.after();
if (el.isConnected)
stages.cleanup();
delete el._x_transitioning;
});
});
el._x_transitioning = {
beforeCancels: [],
beforeCancel(callback) {
this.beforeCancels.push(callback);
},
cancel: once(function() {
while (this.beforeCancels.length) {
this.beforeCancels.shift()();
}
;
finish();
}),
finish
};
mutateDom(() => {
stages.start();
stages.during();
});
holdNextTicks();
requestAnimationFrame(() => {
if (interrupted)
return;
let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, "").replace("s", "")) * 1e3;
let delay = Number(getComputedStyle(el).transitionDelay.replace(/,.*/, "").replace("s", "")) * 1e3;
if (duration === 0)
duration = Number(getComputedStyle(el).animationDuration.replace("s", "")) * 1e3;
mutateDom(() => {
stages.before();
});
reachedBefore = true;
requestAnimationFrame(() => {
if (interrupted)
return;
mutateDom(() => {
stages.end();
});
releaseNextTicks();
setTimeout(el._x_transitioning.finish, duration + delay);
reachedEnd = true;
});
});
}
function modifierValue(modifiers, key, fallback) {
if (modifiers.indexOf(key) === -1)
return fallback;
const rawValue = modifiers[modifiers.indexOf(key) + 1];
if (!rawValue)
return fallback;
if (key === "scale") {
if (isNaN(rawValue))
return fallback;
}
if (key === "duration") {
let match = rawValue.match(/([0-9]+)ms/);
if (match)
return match[1];
}
if (key === "origin") {
if (["top", "right", "left", "center", "bottom"].includes(modifiers[modifiers.indexOf(key) + 2])) {
return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(" ");
}
}
return rawValue;
}
// packages/alpinejs/src/clone.js
var isCloning = false;
function skipDuringClone(callback, fallback = () => {
}) {
return (...args) => isCloning ? fallback(...args) : callback(...args);
}
function clone(oldEl, newEl) {
if (!newEl._x_dataStack)
newEl._x_dataStack = oldEl._x_dataStack;
isCloning = true;
dontRegisterReactiveSideEffects(() => {
cloneTree(newEl);
});
isCloning = false;
}
function cloneTree(el) {
let hasRunThroughFirstEl = false;
let shallowWalker = (el2, callback) => {
walk(el2, (el3, skip) => {
if (hasRunThroughFirstEl && isRoot(el3))
return skip();
hasRunThroughFirstEl = true;
callback(el3, skip);
});
};
initTree(el, shallowWalker);
}
function dontRegisterReactiveSideEffects(callback) {
let cache = effect;
overrideEffect((callback2, el) => {
let storedEffect = cache(callback2);
release(storedEffect);
return () => {
};
});
callback();
overrideEffect(cache);
}
// packages/alpinejs/src/utils/debounce.js
function debounce(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// packages/alpinejs/src/utils/throttle.js
function throttle(func, limit) {
let inThrottle;
return function() {
let context = this, args = arguments;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// packages/alpinejs/src/plugin.js
function plugin(callback) {
callback(alpine_default);
}
// packages/alpinejs/src/store.js
var stores = {};
var isReactive = false;
function store(name, value) {
if (!isReactive) {
stores = reactive(stores);
isReactive = true;
}
if (value === void 0) {
return stores[name];
}
stores[name] = value;
if (typeof value === "object" && value !== null && value.hasOwnProperty("init") && typeof value.init === "function") {
stores[name].init();
}
initInterceptors(stores[name]);
}
function getStores() {
return stores;
}
// packages/alpinejs/src/datas.js
var datas = {};
function data(name, callback) {
datas[name] = callback;
}
function injectDataProviders(obj, context) {
Object.entries(datas).forEach(([name, callback]) => {
Object.defineProperty(obj, name, {
get() {
return (...args) => {
return callback.bind(context)(...args);
};
},
enumerable: false
});
});
return obj;
}
// packages/alpinejs/src/alpine.js
var Alpine = {
get reactive() {
return reactive;
},
get release() {
return release;
},
get effect() {
return effect;
},
get raw() {
return raw;
},
version: "3.5.2",
flushAndStopDeferringMutations,
disableEffectScheduling,
setReactivityEngine,
closestDataStack,
skipDuringClone,
addRootSelector,
deferMutations,
mapAttributes,
evaluateLater,
setEvaluator,
mergeProxies,
closestRoot,
interceptor,
transition,
setStyles,
mutateDom,
directive,
throttle,
debounce,
evaluate,
initTree,
nextTick,
prefix: setPrefix,
plugin,
magic,
store,
start,
clone,
data
};
var alpine_default = Alpine;
// packages/alpinejs/src/index.js
var import_reactivity9 = __toModule(require_reactivity());
// packages/alpinejs/src/magics/$nextTick.js
magic("nextTick", () => nextTick);
// packages/alpinejs/src/magics/$dispatch.js
magic("dispatch", (el) => dispatch.bind(dispatch, el));
// packages/alpinejs/src/magics/$watch.js
magic("watch", (el) => (key, callback) => {
let evaluate2 = evaluateLater(el, key);
let firstTime = true;
let oldValue;
effect(() => evaluate2((value) => {
let div = document.createElement("div");
div.dataset.throwAway = value;
if (!firstTime) {
queueMicrotask(() => {
callback(value, oldValue);
oldValue = value;
});
} else {
oldValue = value;
}
firstTime = false;
}));
});
// packages/alpinejs/src/magics/$store.js
magic("store", getStores);
// packages/alpinejs/src/magics/$data.js
magic("data", (el) => {
return mergeProxies(closestDataStack(el));
});
// packages/alpinejs/src/magics/$root.js
magic("root", (el) => closestRoot(el));
// packages/alpinejs/src/magics/$refs.js
magic("refs", (el) => {
if (el._x_refs_proxy)
return el._x_refs_proxy;
el._x_refs_proxy = mergeProxies(getArrayOfRefObject(el));
return el._x_refs_proxy;
});
function getArrayOfRefObject(el) {
let refObjects = [];
let currentEl = el;
while (currentEl) {
if (currentEl._x_refs)
refObjects.push(currentEl._x_refs);
currentEl = currentEl.parentNode;
}
return refObjects;
}
// packages/alpinejs/src/magics/$el.js
magic("el", (el) => el);
// packages/alpinejs/src/directives/x-ignore.js
var handler = () => {
};
handler.inline = (el, {modifiers}, {cleanup}) => {
modifiers.includes("self") ? el._x_ignoreSelf = true : el._x_ignore = true;
cleanup(() => {
modifiers.includes("self") ? delete el._x_ignoreSelf : delete el._x_ignore;
});
};
directive("ignore", handler);
// packages/alpinejs/src/directives/x-effect.js
directive("effect", (el, {expression}, {effect: effect3}) => effect3(evaluateLater(el, expression)));
// packages/alpinejs/src/utils/bind.js
function bind(el, name, value, modifiers = []) {
if (!el._x_bindings)
el._x_bindings = reactive({});
el._x_bindings[name] = value;
name = modifiers.includes("camel") ? camelCase(name) : name;
switch (name) {
case "value":
bindInputValue(el, value);
break;
case "style":
bindStyles(el, value);
break;
case "class":
bindClasses(el, value);
break;
default:
bindAttribute(el, name, value);
break;
}
}
function bindInputValue(el, value) {
if (el.type === "radio") {
if (el.attributes.value === void 0) {
el.value = value;
}
if (window.fromModel) {
el.checked = checkedAttrLooseCompare(el.value, value);
}
} else if (el.type === "checkbox") {
if (Number.isInteger(value)) {
el.value = value;
} else if (!Number.isInteger(value) && !Array.isArray(value) && typeof value !== "boolean" && ![null, void 0].includes(value)) {
el.value = String(value);
} else {
if (Array.isArray(value)) {
el.checked = value.some((val) => checkedAttrLooseCompare(val, el.value));
} else {
el.checked = !!value;
}
}
} else if (el.tagName === "SELECT") {
updateSelect(el, value);
} else {
if (el.value === value)
return;
el.value = value;
}
}
function bindClasses(el, value) {
if (el._x_undoAddedClasses)
el._x_undoAddedClasses();
el._x_undoAddedClasses = setClasses(el, value);
}
function bindStyles(el, value) {
if (el._x_undoAddedStyles)
el._x_undoAddedStyles();
el._x_undoAddedStyles = setStyles(el, value);
}
function bindAttribute(el, name, value) {
if ([null, void 0, false].includes(value) && attributeShouldntBePreservedIfFalsy(name)) {
el.removeAttribute(name);
} else {
if (isBooleanAttr(name))
value = name;
setIfChanged(el, name, value);
}
}
function setIfChanged(el, attrName, value) {
if (el.getAttribute(attrName) != value) {
el.setAttribute(attrName, value);
}
}
function updateSelect(el, value) {
const arrayWrappedValue = [].concat(value).map((value2) => {
return value2 + "";
});
Array.from(el.options).forEach((option) => {
option.selected = arrayWrappedValue.includes(option.value);
});
}
function camelCase(subject) {
return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase());
}
function checkedAttrLooseCompare(valueA, valueB) {
return valueA == valueB;
}
function isBooleanAttr(attrName) {
const booleanAttributes = [
"disabled",
"checked",
"required",
"readonly",
"hidden",
"open",
"selected",
"autofocus",
"itemscope",
"multiple",
"novalidate",
"allowfullscreen",
"allowpaymentrequest",
"formnovalidate",
"autoplay",
"controls",
"loop",
"muted",
"playsinline",
"default",
"ismap",
"reversed",
"async",
"defer",
"nomodule"
];
return booleanAttributes.includes(attrName);
}
function attributeShouldntBePreservedIfFalsy(name) {
return !["aria-pressed", "aria-checked", "aria-expanded"].includes(name);
}
// packages/alpinejs/src/utils/on.js
function on(el, event, modifiers, callback) {
let listenerTarget = el;
let handler3 = (e) => callback(e);
let options = {};
let wrapHandler = (callback2, wrapper) => (e) => wrapper(callback2, e);
if (modifiers.includes("dot"))
event = dotSyntax(event);
if (modifiers.includes("camel"))
event = camelCase2(event);
if (modifiers.includes("passive"))
options.passive = true;
if (modifiers.includes("capture"))
options.capture = true;
if (modifiers.includes("window"))
listenerTarget = window;
if (modifiers.includes("document"))
listenerTarget = document;
if (modifiers.includes("prevent"))
handler3 = wrapHandler(handler3, (next, e) => {
e.preventDefault();
next(e);
});
if (modifiers.includes("stop"))
handler3 = wrapHandler(handler3, (next, e) => {
e.stopPropagation();
next(e);
});
if (modifiers.includes("self"))
handler3 = wrapHandler(handler3, (next, e) => {
e.target === el && next(e);
});
if (modifiers.includes("away") || modifiers.includes("outside")) {
listenerTarget = document;
handler3 = wrapHandler(handler3, (next, e) => {
if (el.contains(e.target))
return;
if (el.offsetWidth < 1 && el.offsetHeight < 1)
return;
if (el._x_isShown === false)
return;
next(e);
});
}
handler3 = wrapHandler(handler3, (next, e) => {
if (isKeyEvent(event)) {
if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) {
return;
}
}
next(e);
});
if (modifiers.includes("debounce")) {
let nextModifier = modifiers[modifiers.indexOf("debounce") + 1] || "invalid-wait";
let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250;
handler3 = debounce(handler3, wait);
}
if (modifiers.includes("throttle")) {
let nextModifier = modifiers[modifiers.indexOf("throttle") + 1] || "invalid-wait";
let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250;
handler3 = throttle(handler3, wait);
}
if (modifiers.includes("once")) {
handler3 = wrapHandler(handler3, (next, e) => {
next(e);
listenerTarget.removeEventListener(event, handler3, options);
});
}
listenerTarget.addEventListener(event, handler3, options);
return () => {
listenerTarget.removeEventListener(event, handler3, options);
};
}
function dotSyntax(subject) {
return subject.replace(/-/g, ".");
}
function camelCase2(subject) {
return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase());
}
function isNumeric(subject) {
return !Array.isArray(subject) && !isNaN(subject);
}
function kebabCase2(subject) {
return subject.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]/, "-").toLowerCase();
}
function isKeyEvent(event) {
return ["keydown", "keyup"].includes(event);
}
function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) {
let keyModifiers = modifiers.filter((i) => {
return !["window", "document", "prevent", "stop", "once"].includes(i);
});
if (keyModifiers.includes("debounce")) {
let debounceIndex = keyModifiers.indexOf("debounce");
keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || "invalid-wait").split("ms")[0]) ? 2 : 1);
}
if (keyModifiers.length === 0)
return false;
if (keyModifiers.length === 1 && keyToModifiers(e.key).includes(keyModifiers[0]))
return false;
const systemKeyModifiers = ["ctrl", "shift", "alt", "meta", "cmd", "super"];
const selectedSystemKeyModifiers = systemKeyModifiers.filter((modifier) => keyModifiers.includes(modifier));
keyModifiers = keyModifiers.filter((i) => !selectedSystemKeyModifiers.includes(i));
if (selectedSystemKeyModifiers.length > 0) {
const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter((modifier) => {
if (modifier === "cmd" || modifier === "super")
modifier = "meta";
return e[`${modifier}Key`];
});
if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) {
if (keyToModifiers(e.key).includes(keyModifiers[0]))
return false;
}
}
return true;
}
function keyToModifiers(key) {
if (!key)
return [];
key = kebabCase2(key);
let modifierToKeyMap = {
ctrl: "control",
slash: "/",
space: "-",
spacebar: "-",
cmd: "meta",
esc: "escape",
up: "arrow-up",
down: "arrow-down",
left: "arrow-left",
right: "arrow-right",
period: ".",
equal: "="
};
modifierToKeyMap[key] = key;
return Object.keys(modifierToKeyMap).map((modifier) => {
if (modifierToKeyMap[modifier] === key)
return modifier;
}).filter((modifier) => modifier);
}
// packages/alpinejs/src/directives/x-model.js
directive("model", (el, {modifiers, expression}, {effect: effect3, cleanup}) => {
let evaluate2 = evaluateLater(el, expression);
let assignmentExpression = `${expression} = rightSideOfExpression($event, ${expression})`;
let evaluateAssignment = evaluateLater(el, assignmentExpression);
var event = el.tagName.toLowerCase() === "select" || ["checkbox", "radio"].includes(el.type) || modifiers.includes("lazy") ? "change" : "input";
let assigmentFunction = generateAssignmentFunction(el, modifiers, expression);
let removeListener = on(el, event, modifiers, (e) => {
evaluateAssignment(() => {
}, {scope: {
$event: e,
rightSideOfExpression: assigmentFunction
}});
});
cleanup(() => removeListener());
let evaluateSetModel = evaluateLater(el, `${expression} = __placeholder`);
el._x_model = {
get() {
let result;
evaluate2((value) => result = value);
return result;
},
set(value) {
evaluateSetModel(() => {
}, {scope: {__placeholder: value}});
}
};
el._x_forceModelUpdate = () => {
evaluate2((value) => {
if (value === void 0 && expression.match(/\./))
value = "";
window.fromModel = true;
mutateDom(() => bind(el, "value", value));
delete window.fromModel;
});
};
effect3(() => {
if (modifiers.includes("unintrusive") && document.activeElement.isSameNode(el))
return;
el._x_forceModelUpdate();
});
});
function generateAssignmentFunction(el, modifiers, expression) {
if (el.type === "radio") {
mutateDom(() => {
if (!el.hasAttribute("name"))
el.setAttribute("name", expression);
});
}
return (event, currentValue) => {
return mutateDom(() => {
if (event instanceof CustomEvent && event.detail !== void 0) {
return event.detail || event.target.value;
} else if (el.type === "checkbox") {
if (Array.isArray(currentValue)) {
let newValue = modifiers.includes("number") ? safeParseNumber(event.target.value) : event.target.value;
return event.target.checked ? currentValue.concat([newValue]) : currentValue.filter((el2) => !checkedAttrLooseCompare2(el2, newValue));
} else {
return event.target.checked;
}
} else if (el.tagName.toLowerCase() === "select" && el.multiple) {
return modifiers.includes("number") ? Array.from(event.target.selectedOptions).map((option) => {
let rawValue = option.value || option.text;
return safeParseNumber(rawValue);
}) : Array.from(event.target.selectedOptions).map((option) => {
return option.value || option.text;
});
} else {
let rawValue = event.target.value;
return modifiers.includes("number") ? safeParseNumber(rawValue) : modifiers.includes("trim") ? rawValue.trim() : rawValue;
}
});
};
}
function safeParseNumber(rawValue) {
let number = rawValue ? parseFloat(rawValue) : null;
return isNumeric2(number) ? number : rawValue;
}
function checkedAttrLooseCompare2(valueA, valueB) {
return valueA == valueB;
}
function isNumeric2(subject) {
return !Array.isArray(subject) && !isNaN(subject);
}
// packages/alpinejs/src/directives/x-cloak.js
directive("cloak", (el) => queueMicrotask(() => mutateDom(() => el.removeAttribute(prefix("cloak")))));
// packages/alpinejs/src/directives/x-init.js
addInitSelector(() => `[${prefix("init")}]`);
directive("init", skipDuringClone((el, {expression}) => {
if (typeof expression === "string") {
return !!expression.trim() && evaluate(el, expression, {}, false);
}
return evaluate(el, expression, {}, false);
}));
// packages/alpinejs/src/directives/x-text.js
directive("text", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => {
let evaluate2 = evaluateLater2(expression);
effect3(() => {
evaluate2((value) => {
mutateDom(() => {
el.textContent = value;
});
});
});
});
// packages/alpinejs/src/directives/x-html.js
directive("html", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => {
let evaluate2 = evaluateLater2(expression);
effect3(() => {
evaluate2((value) => {
el.innerHTML = value;
});
});
});
// packages/alpinejs/src/directives/x-bind.js
mapAttributes(startingWith(":", into(prefix("bind:"))));
directive("bind", (el, {value, modifiers, expression, original}, {effect: effect3}) => {
if (!value)
return applyBindingsObject(el, expression, original, effect3);
if (value === "key")
return storeKeyForXFor(el, expression);
let evaluate2 = evaluateLater(el, expression);
effect3(() => evaluate2((result) => {
if (result === void 0 && expression.match(/\./))
result = "";
mutateDom(() => bind(el, value, result, modifiers));
}));
});
function applyBindingsObject(el, expression, original, effect3) {
let getBindings = evaluateLater(el, expression);
let cleanupRunners = [];
effect3(() => {
while (cleanupRunners.length)
cleanupRunners.pop()();
getBindings((bindings) => {
let attributes = Object.entries(bindings).map(([name, value]) => ({name, value}));
attributes = attributes.filter((attr) => {
return !(typeof attr.value === "object" && !Array.isArray(attr.value) && attr.value !== null);
});
let staticAttributes = attributesOnly(attributes);
attributes = attributes.map((attribute) => {
if (staticAttributes.find((attr) => attr.name === attribute.name)) {
return {
name: `x-bind:${attribute.name}`,
value: `"${attribute.value}"`
};
}
return attribute;
});
directives(el, attributes, original).map((handle) => {
cleanupRunners.push(handle.runCleanups);
handle();
});
});
});
}
function storeKeyForXFor(el, expression) {
el._x_keyExpression = expression;
}
// packages/alpinejs/src/directives/x-data.js
addRootSelector(() => `[${prefix("data")}]`);
directive("data", skipDuringClone((el, {expression}, {cleanup}) => {
expression = expression === "" ? "{}" : expression;
let magicContext = {};
injectMagics(magicContext, el);
let dataProviderContext = {};
injectDataProviders(dataProviderContext, magicContext);
let data2 = evaluate(el, expression, {scope: dataProviderContext});
if (data2 === void 0)
data2 = {};
injectMagics(data2, el);
let reactiveData = reactive(data2);
initInterceptors(reactiveData);
let undo = addScopeToNode(el, reactiveData);
reactiveData["init"] && evaluate(el, reactiveData["init"]);
cleanup(() => {
undo();
reactiveData["destroy"] && evaluate(el, reactiveData["destroy"]);
});
}));
// packages/alpinejs/src/directives/x-show.js
directive("show", (el, {modifiers, expression}, {effect: effect3}) => {
let evaluate2 = evaluateLater(el, expression);
let hide = () => mutateDom(() => {
el.style.display = "none";
el._x_isShown = false;
});
let show = () => mutateDom(() => {
if (el.style.length === 1 && el.style.display === "none") {
el.removeAttribute("style");
} else {
el.style.removeProperty("display");
}
el._x_isShown = true;
});
let clickAwayCompatibleShow = () => setTimeout(show);
let toggle = once((value) => value ? show() : hide(), (value) => {
if (typeof el._x_toggleAndCascadeWithTransitions === "function") {
el._x_toggleAndCascadeWithTransitions(el, value, show, hide);
} else {
value ? clickAwayCompatibleShow() : hide();
}
});
let oldValue;
let firstTime = true;
effect3(() => evaluate2((value) => {
if (!firstTime && value === oldValue)
return;
if (modifiers.includes("immediate"))
value ? clickAwayCompatibleShow() : hide();
toggle(value);
oldValue = value;
firstTime = false;
}));
});
// packages/alpinejs/src/directives/x-for.js
directive("for", (el, {expression}, {effect: effect3, cleanup}) => {
let iteratorNames = parseForExpression(expression);
let evaluateItems = evaluateLater(el, iteratorNames.items);
let evaluateKey = evaluateLater(el, el._x_keyExpression || "index");
el._x_prevKeys = [];
el._x_lookup = {};
effect3(() => loop(el, iteratorNames, evaluateItems, evaluateKey));
cleanup(() => {
Object.values(el._x_lookup).forEach((el2) => el2.remove());
delete el._x_prevKeys;
delete el._x_lookup;
});
});
function loop(el, iteratorNames, evaluateItems, evaluateKey) {
let isObject = (i) => typeof i === "object" && !Array.isArray(i);
let templateEl = el;
evaluateItems((items) => {
if (isNumeric3(items) && items >= 0) {
items = Array.from(Array(items).keys(), (i) => i + 1);
}
if (items === void 0)
items = [];
let lookup = el._x_lookup;
let prevKeys = el._x_prevKeys;
let scopes = [];
let keys = [];
if (isObject(items)) {
items = Object.entries(items).map(([key, value]) => {
let scope = getIterationScopeVariables(iteratorNames, value, key, items);
evaluateKey((value2) => keys.push(value2), {scope: {index: key, ...scope}});
scopes.push(scope);
});
} else {
for (let i = 0; i < items.length; i++) {
let scope = getIterationScopeVariables(iteratorNames, items[i], i, items);
evaluateKey((value) => keys.push(value), {scope: {index: i, ...scope}});
scopes.push(scope);
}
}
let adds = [];
let moves = [];
let removes = [];
let sames = [];
for (let i = 0; i < prevKeys.length; i++) {
let key = prevKeys[i];
if (keys.indexOf(key) === -1)
removes.push(key);
}
prevKeys = prevKeys.filter((key) => !removes.includes(key));
let lastKey = "template";
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
let prevIndex = prevKeys.indexOf(key);
if (prevIndex === -1) {
prevKeys.splice(i, 0, key);
adds.push([lastKey, i]);
} else if (prevIndex !== i) {
let keyInSpot = prevKeys.splice(i, 1)[0];
let keyForSpot = prevKeys.splice(prevIndex - 1, 1)[0];
prevKeys.splice(i, 0, keyForSpot);
prevKeys.splice(prevIndex, 0, keyInSpot);
moves.push([keyInSpot, keyForSpot]);
} else {
sames.push(key);
}
lastKey = key;
}
for (let i = 0; i < removes.length; i++) {
let key = removes[i];
lookup[key].remove();
lookup[key] = null;
delete lookup[key];
}
for (let i = 0; i < moves.length; i++) {
let [keyInSpot, keyForSpot] = moves[i];
let elInSpot = lookup[keyInSpot];
let elForSpot = lookup[keyForSpot];
let marker = document.createElement("div");
mutateDom(() => {
elForSpot.after(marker);
elInSpot.after(elForSpot);
marker.before(elInSpot);
marker.remove();
});
refreshScope(elForSpot, scopes[keys.indexOf(keyForSpot)]);
}
for (let i = 0; i < adds.length; i++) {
let [lastKey2, index] = adds[i];
let lastEl = lastKey2 === "template" ? templateEl : lookup[lastKey2];
let scope = scopes[index];
let key = keys[index];
let clone2 = document.importNode(templateEl.content, true).firstElementChild;
addScopeToNode(clone2, reactive(scope), templateEl);
mutateDom(() => {
lastEl.after(clone2);
initTree(clone2);
});
if (typeof key === "object") {
warn("x-for key cannot be an object, it must be a string or an integer", templateEl);
}
lookup[key] = clone2;
}
for (let i = 0; i < sames.length; i++) {
refreshScope(lookup[sames[i]], scopes[keys.indexOf(sames[i])]);
}
templateEl._x_prevKeys = keys;
});
}
function parseForExpression(expression) {
let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
let stripParensRE = /^\s*\(|\)\s*$/g;
let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
let inMatch = expression.match(forAliasRE);
if (!inMatch)
return;
let res = {};
res.items = inMatch[2].trim();
let item = inMatch[1].replace(stripParensRE, "").trim();
let iteratorMatch = item.match(forIteratorRE);
if (iteratorMatch) {
res.item = item.replace(forIteratorRE, "").trim();
res.index = iteratorMatch[1].trim();
if (iteratorMatch[2]) {
res.collection = iteratorMatch[2].trim();
}
} else {
res.item = item;
}
return res;
}
function getIterationScopeVariables(iteratorNames, item, index, items) {
let scopeVariables = {};
if (/^\[.*\]$/.test(iteratorNames.item) && Array.isArray(item)) {
let names = iteratorNames.item.replace("[", "").replace("]", "").split(",").map((i) => i.trim());
names.forEach((name, i) => {
scopeVariables[name] = item[i];
});
} else if (/^\{.*\}$/.test(iteratorNames.item) && !Array.isArray(item) && typeof item === "object") {
let names = iteratorNames.item.replace("{", "").replace("}", "").split(",").map((i) => i.trim());
names.forEach((name) => {
scopeVariables[name] = item[name];
});
} else {
scopeVariables[iteratorNames.item] = item;
}
if (iteratorNames.index)
scopeVariables[iteratorNames.index] = index;
if (iteratorNames.collection)
scopeVariables[iteratorNames.collection] = items;
return scopeVariables;
}
function isNumeric3(subject) {
return !Array.isArray(subject) && !isNaN(subject);
}
// packages/alpinejs/src/directives/x-ref.js
function handler2() {
}
handler2.inline = (el, {expression}, {cleanup}) => {
let root = closestRoot(el);
if (!root._x_refs)
root._x_refs = {};
root._x_refs[expression] = el;
cleanup(() => delete root._x_refs[expression]);
};
directive("ref", handler2);
// packages/alpinejs/src/directives/x-if.js
directive("if", (el, {expression}, {effect: effect3, cleanup}) => {
let evaluate2 = evaluateLater(el, expression);
let show = () => {
if (el._x_currentIfEl)
return el._x_currentIfEl;
let clone2 = el.content.cloneNode(true).firstElementChild;
addScopeToNode(clone2, {}, el);
mutateDom(() => {
el.after(clone2);
initTree(clone2);
});
el._x_currentIfEl = clone2;
el._x_undoIf = () => {
clone2.remove();
delete el._x_currentIfEl;
};
return clone2;
};
let hide = () => {
if (!el._x_undoIf)
return;
el._x_undoIf();
delete el._x_undoIf;
};
effect3(() => evaluate2((value) => {
value ? show() : hide();
}));
cleanup(() => el._x_undoIf && el._x_undoIf());
});
// packages/alpinejs/src/directives/x-on.js
mapAttributes(startingWith("@", into(prefix("on:"))));
directive("on", skipDuringClone((el, {value, modifiers, expression}, {cleanup}) => {
let evaluate2 = expression ? evaluateLater(el, expression) : () => {
};
let removeListener = on(el, value, modifiers, (e) => {
evaluate2(() => {
}, {scope: {$event: e}, params: [e]});
});
cleanup(() => removeListener());
}));
// packages/alpinejs/src/index.js
alpine_default.setEvaluator(normalEvaluator);
alpine_default.setReactivityEngine({reactive: import_reactivity9.reactive, effect: import_reactivity9.effect, release: import_reactivity9.stop, raw: import_reactivity9.toRaw});
var src_default = alpine_default;
// packages/alpinejs/builds/module.js
var module_default = src_default;
/***/ }),
/***/ "./node_modules/axios/index.js":
/*!*************************************!*\
!*** ./node_modules/axios/index.js ***!
\*************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js");
/***/ }),
/***/ "./node_modules/axios/lib/adapters/xhr.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/adapters/xhr.js ***!
\************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js");
var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js");
var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js");
var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js");
var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js");
var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js");
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(
timeoutErrorMessage,
config,
config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = config.responseType;
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (!requestData) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
/***/ }),
/***/ "./node_modules/axios/lib/axios.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/axios.js ***!
\*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js");
var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js");
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js");
axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js");
// Expose isAxiosError
axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./node_modules/axios/lib/helpers/isAxiosError.js");
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports["default"] = axios;
/***/ }),
/***/ "./node_modules/axios/lib/cancel/Cancel.js":
/*!*************************************************!*\
!*** ./node_modules/axios/lib/cancel/Cancel.js ***!
\*************************************************/
/***/ ((module) => {
"use strict";
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
/***/ }),
/***/ "./node_modules/axios/lib/cancel/CancelToken.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/cancel/CancelToken.js ***!
\******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js");
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/ }),
/***/ "./node_modules/axios/lib/cancel/isCancel.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/cancel/isCancel.js ***!
\***************************************************/
/***/ ((module) => {
"use strict";
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/ }),
/***/ "./node_modules/axios/lib/core/Axios.js":
/*!**********************************************!*\
!*** ./node_modules/axios/lib/core/Axios.js ***!
\**********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js");
var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js");
var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js");
var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js");
var validator = __webpack_require__(/*! ../helpers/validator */ "./node_modules/axios/lib/helpers/validator.js");
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'),
forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'),
clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0')
}, false);
}
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected(error);
break;
}
}
try {
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: (config || {}).data
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
/***/ }),
/***/ "./node_modules/axios/lib/core/InterceptorManager.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/core/InterceptorManager.js ***!
\***********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/***/ "./node_modules/axios/lib/core/buildFullPath.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/buildFullPath.js ***!
\******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js");
var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js");
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
/***/ }),
/***/ "./node_modules/axios/lib/core/createError.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/createError.js ***!
\****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js");
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/***/ }),
/***/ "./node_modules/axios/lib/core/dispatchRequest.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/core/dispatchRequest.js ***!
\********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js");
var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js");
var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js");
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/ }),
/***/ "./node_modules/axios/lib/core/enhanceError.js":
/*!*****************************************************!*\
!*** ./node_modules/axios/lib/core/enhanceError.js ***!
\*****************************************************/
/***/ ((module) => {
"use strict";
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
/***/ }),
/***/ "./node_modules/axios/lib/core/mergeConfig.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/core/mergeConfig.js ***!
\****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
var defaultToConfig2Keys = [
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
];
var directMergeKeys = ['validateStatus'];
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
}
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
}
});
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
utils.forEach(directMergeKeys, function merge(prop) {
if (prop in config2) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys)
.concat(directMergeKeys);
var otherKeys = Object
.keys(config1)
.concat(Object.keys(config2))
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, mergeDeepProperties);
return config;
};
/***/ }),
/***/ "./node_modules/axios/lib/core/settle.js":
/*!***********************************************!*\
!*** ./node_modules/axios/lib/core/settle.js ***!
\***********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js");
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
/***/ }),
/***/ "./node_modules/axios/lib/core/transformData.js":
/*!******************************************************!*\
!*** ./node_modules/axios/lib/core/transformData.js ***!
\******************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
var defaults = __webpack_require__(/*! ./../defaults */ "./node_modules/axios/lib/defaults.js");
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers);
});
return data;
};
/***/ }),
/***/ "./node_modules/axios/lib/defaults.js":
/*!********************************************!*\
!*** ./node_modules/axios/lib/defaults.js ***!
\********************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
/* provided dependency */ var process = __webpack_require__(/*! process/browser.js */ "./node_modules/process/browser.js");
var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js");
var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js");
var enhanceError = __webpack_require__(/*! ./core/enhanceError */ "./node_modules/axios/lib/core/enhanceError.js");
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js");
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js");
}
return adapter;
}
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
},
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {
setContentTypeIfUnset(headers, 'application/json');
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional;
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw enhanceError(e, this, 'E_JSON_PARSE');
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults.headers = {
common: {
'Accept': 'application/json, text/plain, */*'
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/***/ }),
/***/ "./node_modules/axios/lib/helpers/bind.js":
/*!************************************************!*\
!*** ./node_modules/axios/lib/helpers/bind.js ***!
\************************************************/
/***/ ((module) => {
"use strict";
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/buildURL.js":
/*!****************************************************!*\
!*** ./node_modules/axios/lib/helpers/buildURL.js ***!
\****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/combineURLs.js":
/*!*******************************************************!*\
!*** ./node_modules/axios/lib/helpers/combineURLs.js ***!
\*******************************************************/
/***/ ((module) => {
"use strict";
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/cookies.js":
/*!***************************************************!*\
!*** ./node_modules/axios/lib/helpers/cookies.js ***!
\***************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js":
/*!*********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***!
\*********************************************************/
/***/ ((module) => {
"use strict";
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isAxiosError.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isAxiosError.js ***!
\********************************************************/
/***/ ((module) => {
"use strict";
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return (typeof payload === 'object') && (payload.isAxiosError === true);
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js":
/*!***********************************************************!*\
!*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***!
\***********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js":
/*!***************************************************************!*\
!*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***!
\***************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js");
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/parseHeaders.js":
/*!********************************************************!*\
!*** ./node_modules/axios/lib/helpers/parseHeaders.js ***!
\********************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js");
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/spread.js":
/*!**************************************************!*\
!*** ./node_modules/axios/lib/helpers/spread.js ***!
\**************************************************/
/***/ ((module) => {
"use strict";
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ }),
/***/ "./node_modules/axios/lib/helpers/validator.js":
/*!*****************************************************!*\
!*** ./node_modules/axios/lib/helpers/validator.js ***!
\*****************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var pkg = __webpack_require__(/*! ./../../package.json */ "./node_modules/axios/package.json");
var validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
var currentVerArr = pkg.version.split('.');
/**
* Compare package versions
* @param {string} version
* @param {string?} thanVersion
* @returns {boolean}
*/
function isOlderVersion(version, thanVersion) {
var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr;
var destVer = version.split('.');
for (var i = 0; i < 3; i++) {
if (pkgVersionArr[i] > destVer[i]) {
return true;
} else if (pkgVersionArr[i] < destVer[i]) {
return false;
}
}
return false;
}
/**
* Transitional option validator
* @param {function|boolean?} validator
* @param {string?} version
* @param {string} message
* @returns {function}
*/
validators.transitional = function transitional(validator, version, message) {
var isDeprecated = version && isOlderVersion(version);
function formatMessage(opt, desc) {
return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return function(value, opt, opts) {
if (validator === false) {
throw new Error(formatMessage(opt, ' has been removed in ' + version));
}
if (isDeprecated && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
/**
* Assert object's properties type
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new TypeError('options must be an object');
}
var keys = Object.keys(options);
var i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new TypeError('option ' + opt + ' must be ' + result);
}
continue;
}
if (allowUnknown !== true) {
throw Error('Unknown option ' + opt);
}
}
}
module.exports = {
isOlderVersion: isOlderVersion,
assertOptions: assertOptions,
validators: validators
};
/***/ }),
/***/ "./node_modules/axios/lib/utils.js":
/*!*****************************************!*\
!*** ./node_modules/axios/lib/utils.js ***!
\*****************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js");
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM
};
/***/ }),
/***/ "./resources/js/app.js":
/*!*****************************!*\
!*** ./resources/js/app.js ***!
\*****************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var alpinejs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! alpinejs */ "./node_modules/alpinejs/dist/module.esm.js");
__webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js");
window.Alpine = alpinejs__WEBPACK_IMPORTED_MODULE_0__["default"];
alpinejs__WEBPACK_IMPORTED_MODULE_0__["default"].start();
/***/ }),
/***/ "./resources/js/bootstrap.js":
/*!***********************************!*\
!*** ./resources/js/bootstrap.js ***!
\***********************************/
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js");
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = __webpack_require__(/*! axios */ "./node_modules/axios/index.js");
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
/***/ }),
/***/ "./node_modules/lodash/lodash.js":
/*!***************************************!*\
!*** ./node_modules/lodash/lodash.js ***!
\***************************************/
/***/ (function(module, exports, __webpack_require__) {
/* module decorator */ module = __webpack_require__.nmd(module);
var __WEBPACK_AMD_DEFINE_RESULT__;/**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
;(function() {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used as the semantic version number. */
var VERSION = '4.17.21';
/** Used as the size to enable large array optimizations. */
var LARGE_ARRAY_SIZE = 200;
/** Error message constants. */
var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
FUNC_ERROR_TEXT = 'Expected a function',
INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';
/** Used to stand-in for `undefined` hash values. */
var HASH_UNDEFINED = '__lodash_hash_undefined__';
/** Used as the maximum memoize cache size. */
var MAX_MEMOIZE_SIZE = 500;
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1,
CLONE_FLAT_FLAG = 2,
CLONE_SYMBOLS_FLAG = 4;
/** Used to compose bitmasks for value comparisons. */
var COMPARE_PARTIAL_FLAG = 1,
COMPARE_UNORDERED_FLAG = 2;
/** Used to compose bitmasks for function metadata. */
var WRAP_BIND_FLAG = 1,
WRAP_BIND_KEY_FLAG = 2,
WRAP_CURRY_BOUND_FLAG = 4,
WRAP_CURRY_FLAG = 8,
WRAP_CURRY_RIGHT_FLAG = 16,
WRAP_PARTIAL_FLAG = 32,
WRAP_PARTIAL_RIGHT_FLAG = 64,
WRAP_ARY_FLAG = 128,
WRAP_REARG_FLAG = 256,
WRAP_FLIP_FLAG = 512;
/** Used as default options for `_.truncate`. */
var DEFAULT_TRUNC_LENGTH = 30,
DEFAULT_TRUNC_OMISSION = '...';
/** Used to detect hot functions by number of calls within a span of milliseconds. */
var HOT_COUNT = 800,
HOT_SPAN = 16;
/** Used to indicate the type of lazy iteratees. */
var LAZY_FILTER_FLAG = 1,
LAZY_MAP_FLAG = 2,
LAZY_WHILE_FLAG = 3;
/** Used as references for various `Number` constants. */
var INFINITY = 1 / 0,
MAX_SAFE_INTEGER = 9007199254740991,
MAX_INTEGER = 1.7976931348623157e+308,
NAN = 0 / 0;
/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
/** Used to associate wrap methods with their bit flags. */
var wrapFlags = [
['ary', WRAP_ARY_FLAG],
['bind', WRAP_BIND_FLAG],
['bindKey', WRAP_BIND_KEY_FLAG],
['curry', WRAP_CURRY_FLAG],
['curryRight', WRAP_CURRY_RIGHT_FLAG],
['flip', WRAP_FLIP_FLAG],
['partial', WRAP_PARTIAL_FLAG],
['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
['rearg', WRAP_REARG_FLAG]
];
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
asyncTag = '[object AsyncFunction]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
domExcTag = '[object DOMException]',
errorTag = '[object Error]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]',
mapTag = '[object Map]',
numberTag = '[object Number]',
nullTag = '[object Null]',
objectTag = '[object Object]',
promiseTag = '[object Promise]',
proxyTag = '[object Proxy]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
symbolTag = '[object Symbol]',
undefinedTag = '[object Undefined]',
weakMapTag = '[object WeakMap]',
weakSetTag = '[object WeakSet]';
var arrayBufferTag = '[object ArrayBuffer]',
dataViewTag = '[object DataView]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to match empty string literals in compiled template source. */
var reEmptyStringLeading = /\b__p \+= '';/g,
reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
/** Used to match HTML entities and HTML characters. */
var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
reUnescapedHtml = /[&<>"']/g,
reHasEscapedHtml = RegExp(reEscapedHtml.source),
reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
/** Used to match template delimiters. */
var reEscape = /<%-([\s\S]+?)%>/g,
reEvaluate = /<%([\s\S]+?)%>/g,
reInterpolate = /<%=([\s\S]+?)%>/g;
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/,
rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
/**
* Used to match `RegExp`
* [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
*/
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
reHasRegExpChar = RegExp(reRegExpChar.source);
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/** Used to match a single whitespace character. */
var reWhitespace = /\s/;
/** Used to match wrap detail comments. */
var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
reSplitDetails = /,? & /;
/** Used to match words composed of alphanumeric characters. */
var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
/**
* Used to validate the `validate` option in `_.template` variable.
*
* Forbids characters which could potentially change the meaning of the function argument definition:
* - "()," (modification of function parameters)
* - "=" (default value)
* - "[]{}" (destructuring of function parameters)
* - "/" (beginning of a comment)
* - whitespace
*/
var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Used to match
* [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
*/
var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
/** Used to match `RegExp` flags from their coerced string values. */
var reFlags = /\w*$/;
/** 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 host constructors (Safari). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Used to detect unsigned integer values. */
var reIsUint = /^(?:0|[1-9]\d*)$/;
/** Used to match Latin Unicode letters (excluding mathematical operators). */
var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
/** Used to ensure capturing order of template delimiters. */
var reNoMatch = /($^)/;
/** Used to match unescaped characters in compiled string literals. */
var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
/** Used to compose unicode character classes. */
var rsAstralRange = '\\ud800-\\udfff',
rsComboMarksRange = '\\u0300-\\u036f',
reComboHalfMarksRange = '\\ufe20-\\ufe2f',
rsComboSymbolsRange = '\\u20d0-\\u20ff',
rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
rsDingbatRange = '\\u2700-\\u27bf',
rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
rsPunctuationRange = '\\u2000-\\u206f',
rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
rsVarRange = '\\ufe0e\\ufe0f',
rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
/** Used to compose unicode capture groups. */
var rsApos = "['\u2019]",
rsAstral = '[' + rsAstralRange + ']',
rsBreak = '[' + rsBreakRange + ']',
rsCombo = '[' + rsComboRange + ']',
rsDigits = '\\d+',
rsDingbat = '[' + rsDingbatRange + ']',
rsLower = '[' + rsLowerRange + ']',
rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
rsFitz = '\\ud83c[\\udffb-\\udfff]',
rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
rsNonAstral = '[^' + rsAstralRange + ']',
rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
rsUpper = '[' + rsUpperRange + ']',
rsZWJ = '\\u200d';
/** Used to compose unicode regexes. */
var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
reOptMod = rsModifier + '?',
rsOptVar = '[' + rsVarRange + ']?',
rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
rsSeq = rsOptVar + reOptMod + rsOptJoin,
rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
/** Used to match apostrophes. */
var reApos = RegExp(rsApos, 'g');
/**
* Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
* [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
*/
var reComboMark = RegExp(rsCombo, 'g');
/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
/** Used to match complex or compound words. */
var reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
rsOrdUpper,
rsOrdLower,
rsDigits,
rsEmoji
].join('|'), 'g');
/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
/** Used to detect strings that need a more robust regexp to match words. */
var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
/** Used to assign default `context` object properties. */
var contextProps = [
'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
'_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
];
/** Used to make template sourceURLs easier to identify. */
var templateCounter = -1;
/** 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] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
typedArrayTags[errorTag] = typedArrayTags[funcTag] =
typedArrayTags[mapTag] = typedArrayTags[numberTag] =
typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
typedArrayTags[setTag] = typedArrayTags[stringTag] =
typedArrayTags[weakMapTag] = false;
/** Used to identify `toStringTag` values supported by `_.clone`. */
var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] =
cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
cloneableTags[boolTag] = cloneableTags[dateTag] =
cloneableTags[float32Tag] = cloneableTags[float64Tag] =
cloneableTags[int8Tag] = cloneableTags[int16Tag] =
cloneableTags[int32Tag] = cloneableTags[mapTag] =
cloneableTags[numberTag] = cloneableTags[objectTag] =
cloneableTags[regexpTag] = cloneableTags[setTag] =
cloneableTags[stringTag] = cloneableTags[symbolTag] =
cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
cloneableTags[errorTag] = cloneableTags[funcTag] =
cloneableTags[weakMapTag] = false;
/** Used to map Latin Unicode letters to basic Latin letters. */
var deburredLetters = {
// Latin-1 Supplement block.
'\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
'\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
'\xc7': 'C', '\xe7': 'c',
'\xd0': 'D', '\xf0': 'd',
'\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
'\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
'\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
'\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
'\xd1': 'N', '\xf1': 'n',
'\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
'\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
'\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
'\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
'\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
'\xc6': 'Ae', '\xe6': 'ae',
'\xde': 'Th', '\xfe': 'th',
'\xdf': 'ss',
// Latin Extended-A block.
'\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
'\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
'\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
'\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
'\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
'\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
'\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
'\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
'\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
'\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
'\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
'\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
'\u0134': 'J', '\u0135': 'j',
'\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
'\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
'\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
'\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
'\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
'\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
'\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
'\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
'\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
'\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
'\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
'\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
'\u0163': 't', '\u0165': 't', '\u0167': 't',
'\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
'\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
'\u0174': 'W', '\u0175': 'w',
'\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
'\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
'\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
'\u0132': 'IJ', '\u0133': 'ij',
'\u0152': 'Oe', '\u0153': 'oe',
'\u0149': "'n", '\u017f': 's'
};
/** Used to map characters to HTML entities. */
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
/** Used to map HTML entities to characters. */
var htmlUnescapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
};
/** Used to escape characters for inclusion in compiled string literals. */
var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/** Built-in method references without a dependency on `root`. */
var freeParseFloat = parseFloat,
freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Detect free variable `exports`. */
var freeExports = true && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
/* Node.js helper references. */
var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
nodeIsDate = nodeUtil && nodeUtil.isDate,
nodeIsMap = nodeUtil && nodeUtil.isMap,
nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
nodeIsSet = nodeUtil && nodeUtil.isSet,
nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/*--------------------------------------------------------------------------*/
/**
* 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) {
switch (args.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);
}
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/**
* 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 == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.forEachRight` 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 arrayEachRight(array, iteratee) {
var length = array == null ? 0 : array.length;
while (length--) {
if (iteratee(array[length], length, array) === false) {
break;
}
}
return array;
}
/**
* A specialized version of `_.every` 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 all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
/**
* A specialized version of `_.filter` 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 {Array} Returns the new filtered array.
*/
function arrayFilter(array, predicate) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf(array, value, 0) > -1;
}
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/
function arrayIncludesWith(array, value, comparator) {
var index = -1,
length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
/**
* 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 == null ? 0 : array.length,
result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/
function arrayPush(array, values) {
var index = -1,
length = values.length,
offset = array.length;
while (++index < length) {
array[offset + index] = values[index];
}
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1,
length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/
function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[--length];
}
while (length--) {
accumulator = iteratee(accumulator, array[length], length, array);
}
return accumulator;
}
/**
* 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 == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
var asciiSize = baseProperty('length');
/**
* Converts an ASCII `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function asciiToArray(string) {
return string.split('');
}
/**
* Splits an ASCII `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function asciiWords(string) {
return string.match(reAsciiWord) || [];
}
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/
function baseFindKey(collection, predicate, eachFunc) {
var result;
eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) {
result = key;
return false;
}
});
return result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @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 value, else `-1`.
*/
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length,
index = fromIndex + (fromRight ? 1 : -1);
while ((fromRight ? index-- : ++index < length)) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @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) {
return value === value
? strictIndexOf(array, value, fromIndex)
: baseFindIndex(array, baseIsNaN, fromIndex);
}
/**
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
*/
function baseIndexOfWith(array, value, fromIndex, comparator) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (comparator(array[index], value)) {
return index;
}
}
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/
function baseIsNaN(value) {
return value !== value;
}
/**
* The base implementation of `_.mean` and `_.meanBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the mean.
*/
function baseMean(array, iteratee) {
var length = array == null ? 0 : array.length;
return length ? (baseSum(array, iteratee) / length) : NAN;
}
/**
* 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];
};
}
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/
function basePropertyOf(object) {
return function(key) {
return object == null ? undefined : object[key];
};
}
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection) {
accumulator = initAccum
? (initAccum = false, value)
: iteratee(accumulator, value, index, collection);
});
return accumulator;
}
/**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/
function baseSortBy(array, comparer) {
var length = array.length;
array.sort(comparer);
while (length--) {
array[length] = array[length].value;
}
return array;
}
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/
function baseSum(array, iteratee) {
var result,
index = -1,
length = array.length;
while (++index < length) {
var current = iteratee(array[index]);
if (current !== undefined) {
result = result === undefined ? current : (result + current);
}
}
return result;
}
/**
* 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;
}
/**
* 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]];
});
}
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/
function baseTrim(string) {
return string
? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
: string;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/
function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values 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 array of property values.
*/
function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/
function cacheHas(cache, key) {
return cache.has(key);
}
/**
* 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 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;
}
/**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/
function countHolders(array, placeholder) {
var length = array.length,
result = 0;
while (length--) {
if (array[length] === placeholder) {
++result;
}
}
return result;
}
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/
var deburrLetter = basePropertyOf(deburredLetters);
/**
* Used by `_.escape` to convert characters to HTML entities.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
var escapeHtmlChar = basePropertyOf(htmlEscapes);
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/
function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Gets the value at `key` of `object`.
*
* @private
* @param {Object} [object] The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function getValue(object, key) {
return object == null ? undefined : object[key];
}
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/
function hasUnicode(string) {
return reHasUnicode.test(string);
}
/**
* Checks if `string` contains a word composed of Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a word is found, else `false`.
*/
function hasUnicodeWord(string) {
return reHasUnicodeWord.test(string);
}
/**
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
*/
function iteratorToArray(iterator) {
var data,
result = [];
while (!(data = iterator.next()).done) {
result.push(data.value);
}
return result;
}
/**
* 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;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
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;
}
/**
* 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;
}
/**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @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 strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1,
length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
/**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @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 strictLastIndexOf(array, value, fromIndex) {
var index = fromIndex + 1;
while (index--) {
if (array[index] === value) {
return index;
}
}
return index;
}
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/
function stringSize(string) {
return hasUnicode(string)
? unicodeSize(string)
: asciiSize(string);
}
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function stringToArray(string) {
return hasUnicode(string)
? unicodeToArray(string)
: asciiToArray(string);
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {}
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/
var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
/**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/
function unicodeSize(string) {
var result = reUnicode.lastIndex = 0;
while (reUnicode.test(string)) {
++result;
}
return result;
}
/**
* Converts a Unicode `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/
function unicodeToArray(string) {
return string.match(reUnicode) || [];
}
/**
* Splits a Unicode `string` into an array of its words.
*
* @private
* @param {string} The string to inspect.
* @returns {Array} Returns the words of `string`.
*/
function unicodeWords(string) {
return string.match(reUnicodeWord) || [];
}
/*--------------------------------------------------------------------------*/
/**
* Create a new pristine `lodash` function using the `context` object.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Util
* @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `lodash` function.
* @example
*
* _.mixin({ 'foo': _.constant('foo') });
*
* var lodash = _.runInContext();
* lodash.mixin({ 'bar': lodash.constant('bar') });
*
* _.isFunction(_.foo);
* // => true
* _.isFunction(_.bar);
* // => false
*
* lodash.isFunction(lodash.foo);
* // => false
* lodash.isFunction(lodash.bar);
* // => true
*
* // Create a suped-up `defer` in Node.js.
* var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
*/
var runInContext = (function runInContext(context) {
context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
/** Built-in constructor references. */
var Array = context.Array,
Date = context.Date,
Error = context.Error,
Function = context.Function,
Math = context.Math,
Object = context.Object,
RegExp = context.RegExp,
String = context.String,
TypeError = context.TypeError;
/** Used for built-in method references. */
var arrayProto = Array.prototype,
funcProto = Function.prototype,
objectProto = Object.prototype;
/** Used to detect overreaching core-js shims. */
var coreJsData = context['__core-js_shared__'];
/** Used to resolve the decompiled source of functions. */
var funcToString = funcProto.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to generate unique IDs. */
var idCounter = 0;
/** Used to detect methods masquerading as native. */
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
return uid ? ('Symbol(src)_1.' + uid) : '';
}());
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var nativeObjectToString = objectProto.toString;
/** Used to infer the `Object` constructor. */
var objectCtorString = funcToString.call(Object);
/** Used to restore the original `_` reference in `_.noConflict`. */
var oldDash = root._;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/** Built-in value references. */
var Buffer = moduleExports ? context.Buffer : undefined,
Symbol = context.Symbol,
Uint8Array = context.Uint8Array,
allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
getPrototype = overArg(Object.getPrototypeOf, Object),
objectCreate = Object.create,
propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice,
spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
symIterator = Symbol ? Symbol.iterator : undefined,
symToStringTag = Symbol ? Symbol.toStringTag : undefined;
var defineProperty = (function() {
try {
var func = getNative(Object, 'defineProperty');
func({}, '', {});
return func;
} catch (e) {}
}());
/** Mocked built-ins. */
var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
ctxNow = Date && Date.now !== root.Date.now && Date.now,
ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeCeil = Math.ceil,
nativeFloor = Math.floor,
nativeGetSymbols = Object.getOwnPropertySymbols,
nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
nativeIsFinite = context.isFinite,
nativeJoin = arrayProto.join,
nativeKeys = overArg(Object.keys, Object),
nativeMax = Math.max,
nativeMin = Math.min,
nativeNow = Date.now,
nativeParseInt = context.parseInt,
nativeRandom = Math.random,
nativeReverse = arrayProto.reverse;
/* Built-in method references that are verified to be native. */
var DataView = getNative(context, 'DataView'),
Map = getNative(context, 'Map'),
Promise = getNative(context, 'Promise'),
Set = getNative(context, 'Set'),
WeakMap = getNative(context, 'WeakMap'),
nativeCreate = getNative(Object, 'create');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
/** Used to lookup unminified function names. */
var realNames = {};
/** Used to detect maps, sets, and weakmaps. */
var dataViewCtorString = toSource(DataView),
mapCtorString = toSource(Map),
promiseCtorString = toSource(Promise),
setCtorString = toSource(Set),
weakMapCtorString = toSource(WeakMap);
/** Used to convert symbols to primitives and strings. */
var symbolProto = Symbol ? Symbol.prototype : undefined,
symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/
function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) {
return value;
}
if (hasOwnProperty.call(value, '__wrapped__')) {
return wrapperClone(value);
}
}
return new LodashWrapper(value);
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(proto) {
if (!isObject(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object;
object.prototype = undefined;
return result;
};
}());
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/
function baseLodash() {
// No operation performed.
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/
function LodashWrapper(value, chainAll) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__chain__ = !!chainAll;
this.__index__ = 0;
this.__values__ = undefined;
}
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/
lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'escape': reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'evaluate': reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/
'interpolate': reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/
'variable': '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/
'imports': {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/
'_': lodash
}
};
// Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype;
lodash.prototype.constructor = lodash;
LodashWrapper.prototype = baseCreate(baseLodash.prototype);
LodashWrapper.prototype.constructor = LodashWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/
function LazyWrapper(value) {
this.__wrapped__ = value;
this.__actions__ = [];
this.__dir__ = 1;
this.__filtered__ = false;
this.__iteratees__ = [];
this.__takeCount__ = MAX_ARRAY_LENGTH;
this.__views__ = [];
}
/**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/
function lazyClone() {
var result = new LazyWrapper(this.__wrapped__);
result.__actions__ = copyArray(this.__actions__);
result.__dir__ = this.__dir__;
result.__filtered__ = this.__filtered__;
result.__iteratees__ = copyArray(this.__iteratees__);
result.__takeCount__ = this.__takeCount__;
result.__views__ = copyArray(this.__views__);
return result;
}
/**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/
function lazyReverse() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1;
result.__filtered__ = true;
} else {
result = this.clone();
result.__dir__ *= -1;
}
return result;
}
/**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/
function lazyValue() {
var array = this.__wrapped__.value(),
dir = this.__dir__,
isArr = isArray(array),
isRight = dir < 0,
arrLength = isArr ? array.length : 0,
view = getView(0, arrLength, this.__views__),
start = view.start,
end = view.end,
length = end - start,
index = isRight ? end : (start - 1),
iteratees = this.__iteratees__,
iterLength = iteratees.length,
resIndex = 0,
takeCount = nativeMin(length, this.__takeCount__);
if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
return baseWrapperValue(array, this.__actions__);
}
var result = [];
outer:
while (length-- && resIndex < takeCount) {
index += dir;
var iterIndex = -1,
value = array[index];
while (++iterIndex < iterLength) {
var data = iteratees[iterIndex],
iteratee = data.iteratee,
type = data.type,
computed = iteratee(value);
if (type == LAZY_MAP_FLAG) {
value = computed;
} else if (!computed) {
if (type == LAZY_FILTER_FLAG) {
continue outer;
} else {
break outer;
}
}
}
result[resIndex++] = value;
}
return result;
}
// Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype);
LazyWrapper.prototype.constructor = LazyWrapper;
/*------------------------------------------------------------------------*/
/**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Hash(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/
function hashClear() {
this.__data__ = nativeCreate ? nativeCreate(null) : {};
this.size = 0;
}
/**
* 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) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
/**
* 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.call(data, key) ? data[key] : undefined;
}
/**
* 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.call(data, key);
}
/**
* 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__;
this.size += this.has(key) ? 0 : 1;
data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
return this;
}
// Add methods to `Hash`.
Hash.prototype.clear = hashClear;
Hash.prototype['delete'] = hashDelete;
Hash.prototype.get = hashGet;
Hash.prototype.has = hashHas;
Hash.prototype.set = hashSet;
/*------------------------------------------------------------------------*/
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
/**
* 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);
}
--this.size;
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) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
/*------------------------------------------------------------------------*/
/**
* 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 == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/
function mapCacheClear() {
this.size = 0;
this.__data__ = {
'hash': new Hash,
'map': new (Map || ListCache),
'string': new Hash
};
}
/**
* 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) {
var result = getMapData(this, key)['delete'](key);
this.size -= result ? 1 : 0;
return result;
}
/**
* 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) {
var data = getMapData(this, key),
size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
// Add methods to `MapCache`.
MapCache.prototype.clear = mapCacheClear;
MapCache.prototype['delete'] = mapCacheDelete;
MapCache.prototype.get = mapCacheGet;
MapCache.prototype.has = mapCacheHas;
MapCache.prototype.set = mapCacheSet;
/*------------------------------------------------------------------------*/
/**
*
* 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 == null ? 0 : values.length;
this.__data__ = new MapCache;
while (++index < length) {
this.add(values[index]);
}
}
/**
* 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);
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);
}
// Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
SetCache.prototype.has = setCacheHas;
/*------------------------------------------------------------------------*/
/**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/
function stackClear() {
this.__data__ = new ListCache;
this.size = 0;
}
/**
* 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) {
var data = this.__data__,
result = data['delete'](key);
this.size = data.size;
return result;
}
/**
* 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);
}
/**
* 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 data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
// Add methods to `Stack`.
Stack.prototype.clear = stackClear;
Stack.prototype['delete'] = stackDelete;
Stack.prototype.get = stackGet;
Stack.prototype.has = stackHas;
Stack.prototype.set = stackSet;
/*------------------------------------------------------------------------*/
/**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/
function arrayLikeKeys(value, inherited) {
var isArr = isArray(value),
isArg = !isArr && isArguments(value),
isBuff = !isArr && !isArg && isBuffer(value),
isType = !isArr && !isArg && !isBuff && isTypedArray(value),
skipIndexes = isArr || isArg || isBuff || isType,
result = skipIndexes ? baseTimes(value.length, String) : [],
length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty.call(value, key)) &&
!(skipIndexes && (
// Safari 9 has enumerable `arguments.length` in strict mode.
key == 'length' ||
// Node.js 0.10 has enumerable non-index properties on buffers.
(isBuff && (key == 'offset' || key == 'parent')) ||
// PhantomJS 2 has enumerable non-index properties on typed arrays.
(isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
// Skip index properties.
isIndex(key, length)
))) {
result.push(key);
}
}
return result;
}
/**
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
*/
function arraySample(array) {
var length = array.length;
return length ? array[baseRandom(0, length - 1)] : undefined;
}
/**
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function arraySampleSize(array, n) {
return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
}
/**
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function arrayShuffle(array) {
return shuffleSelf(copyArray(array));
}
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignMergeValue(object, key, value) {
if ((value !== undefined && !eq(object[key], value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
(value === undefined && !(key in object))) {
baseAssignValue(object, key, value);
}
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @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;
}
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/
function baseAggregator(collection, setter, iteratee, accumulator) {
baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
});
return accumulator;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `_.assignIn` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssignIn(object, source) {
return object && copyObject(source, keysIn(source), object);
}
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/
function baseAssignValue(object, key, value) {
if (key == '__proto__' && defineProperty) {
defineProperty(object, key, {
'configurable': true,
'enumerable': true,
'value': value,
'writable': true
});
} else {
object[key] = value;
}
}
/**
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
*/
function baseAt(object, paths) {
var index = -1,
length = paths.length,
result = Array(length),
skip = object == null;
while (++index < length) {
result[index] = skip ? undefined : get(object, paths[index]);
}
return result;
}
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/
function baseClamp(number, lower, upper) {
if (number === number) {
if (upper !== undefined) {
number = number <= upper ? number : upper;
}
if (lower !== undefined) {
number = number >= lower ? number : lower;
}
}
return number;
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/
function baseClone(value, bitmask, customizer, key, object, stack) {
var result,
isDeep = bitmask & CLONE_DEEP_FLAG,
isFlat = bitmask & CLONE_FLAT_FLAG,
isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== undefined) {
return result;
}
if (!isObject(value)) {
return value;
}
var isArr = isArray(value);
if (isArr) {
result = initCloneArray(value);
if (!isDeep) {
return copyArray(value, result);
}
} else {
var tag = getTag(value),
isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) {
return cloneBuffer(value, isDeep);
}
if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
result = (isFlat || isFunc) ? {} : initCloneObject(value);
if (!isDeep) {
return isFlat
? copySymbolsIn(value, baseAssignIn(result, value))
: copySymbols(value, baseAssign(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap(value)) {
value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
}
var keysFunc = isFull
? (isFlat ? getAllKeysIn : getAllKeys)
: (isFlat ? keysIn : keys);
var props = isArr ? undefined : keysFunc(value);
arrayEach(props || value, function(subValue, key) {
if (props) {
key = subValue;
subValue = value[key];
}
// Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
return result;
}
/**
* The base implementation of `_.conforms` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
*/
function baseConforms(source) {
var props = keys(source);
return function(object) {
return baseConformsTo(object, source, props);
};
}
/**
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
*/
function baseConformsTo(object, source, props) {
var length = props.length;
if (object == null) {
return !length;
}
object = Object(object);
while (length--) {
var key = props[length],
predicate = source[key],
value = object[key];
if ((value === undefined && !(key in object)) || !predicate(value)) {
return false;
}
}
return true;
}
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/
function baseDelay(func, wait, args) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return setTimeout(function() { func.apply(undefined, args); }, wait);
}
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/
function baseDifference(array, values, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
isCommon = true,
length = array.length,
result = [],
valuesLength = values.length;
if (!length) {
return result;
}
if (iteratee) {
values = arrayMap(values, baseUnary(iteratee));
}
if (comparator) {
includes = arrayIncludesWith;
isCommon = false;
}
else if (values.length >= LARGE_ARRAY_SIZE) {
includes = cacheHas;
isCommon = false;
values = new SetCache(values);
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee == null ? value : iteratee(value);
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
}
else if (!includes(values, computed, comparator)) {
result.push(value);
}
}
return result;
}
/**
* 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);
/**
* The base implementation of `_.forEachRight` 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 baseEachRight = createBaseEach(baseForOwnRight, true);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
/**
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
*/
function baseExtremum(array, iteratee, comparator) {
var index = -1,
length = array.length;
while (++index < length) {
var value = array[index],
current = iteratee(value);
if (current != null && (computed === undefined
? (current === current && !isSymbol(current))
: comparator(current, computed)
)) {
var computed = current,
result = value;
}
}
return result;
}
/**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/
function baseFill(array, value, start, end) {
var length = array.length;
start = toInteger(start);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : toInteger(end);
if (end < 0) {
end += length;
}
end = start > end ? 0 : toLength(end);
while (start < end) {
array[start++] = value;
}
return array;
}
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/
function baseFilter(collection, predicate) {
var result = [];
baseEach(collection, function(value, index, collection) {
if (predicate(value, index, collection)) {
result.push(value);
}
});
return result;
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1,
length = array.length;
predicate || (predicate = isFlattenable);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
/**
* 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();
/**
* This function is like `baseFor` except that it iterates over properties
* in the opposite order.
*
* @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 baseForRight = createBaseFor(true);
/**
* 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);
}
/**
* The base implementation of `_.forOwnRight` 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 baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
*/
function baseFunctions(object, props) {
return arrayFilter(props, function(key) {
return isFunction(object[key]);
});
}
/**
* 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 = castPath(path, object);
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[toKey(path[index++])];
}
return (index && index == length) ? object : undefined;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
function baseGetTag(value) {
if (value == null) {
return value === undefined ? undefinedTag : nullTag;
}
return (symToStringTag && symToStringTag in Object(value))
? getRawTag(value)
: objectToString(value);
}
/**
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
*/
function baseGt(value, other) {
return value > other;
}
/**
* 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) {
return object != null && hasOwnProperty.call(object, key);
}
/**
* 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 object != null && key in Object(object);
}
/**
* The base implementation of `_.inRange` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to check.
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
*/
function baseInRange(number, start, end) {
return number >= nativeMin(start, end) && number < nativeMax(start, end);
}
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/
function baseIntersection(arrays, iteratee, comparator) {
var includes = comparator ? arrayIncludesWith : arrayIncludes,
length = arrays[0].length,
othLength = arrays.length,
othIndex = othLength,
caches = Array(othLength),
maxLength = Infinity,
result = [];
while (othIndex--) {
var array = arrays[othIndex];
if (othIndex && iteratee) {
array = arrayMap(array, baseUnary(iteratee));
}
maxLength = nativeMin(array.length, maxLength);
caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
? new SetCache(othIndex && array)
: undefined;
}
array = arrays[0];
var index = -1,
seen = caches[0];
outer:
while (++index < length && result.length < maxLength) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (!(seen
? cacheHas(seen, computed)
: includes(result, computed, comparator)
)) {
othIndex = othLength;
while (--othIndex) {
var cache = caches[othIndex];
if (!(cache
? cacheHas(cache, computed)
: includes(arrays[othIndex], computed, comparator))
) {
continue outer;
}
}
if (seen) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.invert` and `_.invertBy` which inverts
* `object` with values transformed by `iteratee` and set by `setter`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform values.
* @param {Object} accumulator The initial inverted object.
* @returns {Function} Returns `accumulator`.
*/
function baseInverter(object, setter, iteratee, accumulator) {
baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee(value), key, object);
});
return accumulator;
}
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/
function baseInvoke(object, path, args) {
path = castPath(path, object);
object = parent(object, path);
var func = object == null ? object : object[toKey(last(path))];
return func == null ? undefined : apply(func, object, args);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/
function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
*/
function baseIsArrayBuffer(value) {
return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
}
/**
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
*/
function baseIsDate(value) {
return isObjectLike(value) && baseGetTag(value) == dateTag;
}
/**
* 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 {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
}
/**
* 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = objIsArr ? arrayTag : getTag(object),
othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag;
othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack);
return (objIsArr || isTypedArray(object))
? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
: equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.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, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack);
return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
}
/**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/
function baseIsMap(value) {
return isObjectLike(value) && getTag(value) == mapTag;
}
/**
* 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, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
: result
)) {
return false;
}
}
}
return true;
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/
function baseIsNative(value) {
if (!isObject(value) || isMasked(value)) {
return false;
}
var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource(value));
}
/**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/
function baseIsRegExp(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}
/**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/
function baseIsSet(value) {
return isObjectLike(value) && getTag(value) == setTag;
}
/**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/
function baseIsTypedArray(value) {
return isObjectLike(value) &&
isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}
/**
* 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);
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeys(object) {
if (!isPrototype(object)) {
return nativeKeys(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty.call(object, key) && key != 'constructor') {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function baseKeysIn(object) {
if (!isObject(object)) {
return nativeKeysIn(object);
}
var isProto = isPrototype(object),
result = [];
for (var key in object) {
if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
/**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/
function baseLt(value, other) {
return value < other;
}
/**
* The base implementation of `_.map` 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} Returns the new mapped array.
*/
function baseMap(collection, iteratee) {
var index = -1,
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
});
return result;
}
/**
* 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);
};
}
/**
* 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, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
};
}
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMerge(object, source, srcIndex, customizer, stack) {
if (object === source) {
return;
}
baseFor(source, function(srcValue, key) {
stack || (stack = new Stack);
if (isObject(srcValue)) {
baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
}
else {
var newValue = customizer
? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
: undefined;
if (newValue === undefined) {
newValue = srcValue;
}
assignMergeValue(object, key, newValue);
}
}, keysIn);
}
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/
function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key),
srcValue = safeGet(source, key),
stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer
? customizer(objValue, srcValue, (key + ''), object, source, stack)
: undefined;
var isCommon = newValue === undefined;
if (isCommon) {
var isArr = isArray(srcValue),
isBuff = !isArr && isBuffer(srcValue),
isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue;
if (isArr || isBuff || isTyped) {
if (isArray(objValue)) {
newValue = objValue;
}
else if (isArrayLikeObject(objValue)) {
newValue = copyArray(objValue);
}
else if (isBuff) {
isCommon = false;
newValue = cloneBuffer(srcValue, true);
}
else if (isTyped) {
isCommon = false;
newValue = cloneTypedArray(srcValue, true);
}
else {
newValue = [];
}
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
newValue = objValue;
if (isArguments(objValue)) {
newValue = toPlainObject(objValue);
}
else if (!isObject(objValue) || isFunction(objValue)) {
newValue = initCloneObject(srcValue);
}
}
else {
isCommon = false;
}
}
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue);
mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
stack['delete'](srcValue);
}
assignMergeValue(object, key, newValue);
}
/**
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
*/
function baseNth(array, n) {
var length = array.length;
if (!length) {
return;
}
n += n < 0 ? length : 0;
return isIndex(n, length) ? array[n] : undefined;
}
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/
function baseOrderBy(collection, iteratees, orders) {
if (iteratees.length) {
iteratees = arrayMap(iteratees, function(iteratee) {
if (isArray(iteratee)) {
return function(value) {
return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
}
}
return iteratee;
});
} else {
iteratees = [identity];
}
var index = -1;
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
var result = baseMap(collection, function(value, key, collection) {
var criteria = arrayMap(iteratees, function(iteratee) {
return iteratee(value);
});
return { 'criteria': criteria, 'index': ++index, 'value': value };
});
return baseSortBy(result, function(object, other) {
return compareMultiple(object, other, orders);
});
}
/**
* The base implementation of `_.pick` without support for individual
* property identifiers.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @returns {Object} Returns the new object.
*/
function basePick(object, paths) {
return basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
}
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/
function basePickBy(object, paths, predicate) {
var index = -1,
length = paths.length,
result = {};
while (++index < length) {
var path = paths[index],
value = baseGet(object, path);
if (predicate(value, path)) {
baseSet(result, castPath(path, object), value);
}
}
return result;
}
/**
* 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);
};
}
/**
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
*/
function basePullAll(array, values, iteratee, comparator) {
var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
index = -1,
length = values.length,
seen = array;
if (array === values) {
values = copyArray(values);
}
if (iteratee) {
seen = arrayMap(array, baseUnary(iteratee));
}
while (++index < length) {
var fromIndex = 0,
value = values[index],
computed = iteratee ? iteratee(value) : value;
while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
if (seen !== array) {
splice.call(seen, fromIndex, 1);
}
splice.call(array, fromIndex, 1);
}
}
return array;
}
/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/
function basePullAt(array, indexes) {
var length = array ? indexes.length : 0,
lastIndex = length - 1;
while (length--) {
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
if (isIndex(index)) {
splice.call(array, index, 1);
} else {
baseUnset(array, index);
}
}
}
return array;
}
/**
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/
function baseRandom(lower, upper) {
return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @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(nativeCeil((end - start) / (step || 1)), 0),
result = Array(length);
while (length--) {
result[fromRight ? length : ++index] = start;
start += step;
}
return result;
}
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/
function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
return result;
}
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do {
if (n % 2) {
result += string;
}
n = nativeFloor(n / 2);
if (n) {
string += string;
}
} while (n);
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @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.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
*/
function baseSample(collection) {
return arraySample(values(collection));
}
/**
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/
function baseSampleSize(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
}
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseSet(object, path, value, customizer) {
if (!isObject(object)) {
return object;
}
path = castPath(path, object);
var index = -1,
length = path.length,
lastIndex = length - 1,
nested = object;
while (nested != null && ++index < length) {
var key = toKey(path[index]),
newValue = value;
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined;
if (newValue === undefined) {
newValue = isObject(objValue)
? objValue
: (isIndex(path[index + 1]) ? [] : {});
}
}
assignValue(nested, key, newValue);
nested = nested[key];
}
return object;
}
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var baseSetData = !metaMap ? identity : function(func, data) {
metaMap.set(func, data);
return func;
};
/**
* The base implementation of `setToString` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var baseSetToString = !defineProperty ? identity : function(func, string) {
return defineProperty(func, 'toString', {
'configurable': true,
'enumerable': false,
'value': constant(string),
'writable': true
});
};
/**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/
function baseShuffle(collection) {
return shuffleSelf(values(collection));
}
/**
* 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;
}
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection 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 baseSome(collection, predicate) {
var result;
baseEach(collection, function(value, index, collection) {
result = predicate(value, index, collection);
return !result;
});
return !!result;
}
/**
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndex(array, value, retHighest) {
var low = 0,
high = array == null ? low : array.length;
if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
while (low < high) {
var mid = (low + high) >>> 1,
computed = array[mid];
if (computed !== null && !isSymbol(computed) &&
(retHighest ? (computed <= value) : (computed < value))) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/
function baseSortedIndexBy(array, value, iteratee, retHighest) {
var low = 0,
high = array == null ? 0 : array.length;
if (high === 0) {
return 0;
}
value = iteratee(value);
var valIsNaN = value !== value,
valIsNull = value === null,
valIsSymbol = isSymbol(value),
valIsUndefined = value === undefined;
while (low < high) {
var mid = nativeFloor((low + high) / 2),
computed = iteratee(array[mid]),
othIsDefined = computed !== undefined,
othIsNull = computed === null,
othIsReflexive = computed === computed,
othIsSymbol = isSymbol(computed);
if (valIsNaN) {
var setLow = retHighest || othIsReflexive;
} else if (valIsUndefined) {
setLow = othIsReflexive && (retHighest || othIsDefined);
} else if (valIsNull) {
setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
} else if (valIsSymbol) {
setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
} else if (othIsNull || othIsSymbol) {
setLow = false;
} else {
setLow = retHighest ? (computed <= value) : (computed < value);
}
if (setLow) {
low = mid + 1;
} else {
high = mid;
}
}
return nativeMin(high, MAX_ARRAY_INDEX);
}
/**
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseSortedUniq(array, iteratee) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
if (!index || !eq(computed, seen)) {
var seen = computed;
result[resIndex++] = value === 0 ? 0 : value;
}
}
return result;
}
/**
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/
function baseToNumber(value) {
if (typeof value == 'number') {
return value;
}
if (isSymbol(value)) {
return NAN;
}
return +value;
}
/**
* 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 (isArray(value)) {
// Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
}
if (isSymbol(value)) {
return symbolToString ? symbolToString.call(value) : '';
}
var result = (value + '');
return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
}
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/
function baseUniq(array, iteratee, comparator) {
var index = -1,
includes = arrayIncludes,
length = array.length,
isCommon = true,
result = [],
seen = result;
if (comparator) {
isCommon = false;
includes = arrayIncludesWith;
}
else if (length >= LARGE_ARRAY_SIZE) {
var set = iteratee ? null : createSet(array);
if (set) {
return setToArray(set);
}
isCommon = false;
includes = cacheHas;
seen = new SetCache;
}
else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index],
computed = iteratee ? iteratee(value) : value;
value = (comparator || value !== 0) ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
}
else if (!includes(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/
function baseUnset(object, path) {
path = castPath(path, object);
object = parent(object, path);
return object == null || delete object[toKey(last(path))];
}
/**
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/
function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
}
/**
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/
function baseWhile(array, predicate, isDrop, fromRight) {
var length = array.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length) &&
predicate(array[index], index, array)) {}
return isDrop
? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
: baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/
function baseWrapperValue(value, actions) {
var result = value;
if (result instanceof LazyWrapper) {
result = result.value();
}
return arrayReduce(actions, function(result, action) {
return action.func.apply(action.thisArg, arrayPush([result], action.args));
}, result);
}
/**
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
*/
function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) {
return length ? baseUniq(arrays[0]) : [];
}
var index = -1,
result = Array(length);
while (++index < length) {
var array = arrays[index],
othIndex = -1;
while (++othIndex < length) {
if (othIndex != index) {
result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
}
}
}
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
}
/**
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
*/
function baseZipObject(props, values, assignFunc) {
var index = -1,
length = props.length,
valsLength = values.length,
result = {};
while (++index < length) {
var value = index < valsLength ? values[index] : undefined;
assignFunc(result, props[index], value);
}
return result;
}
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/
function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/
function castFunction(value) {
return typeof value == 'function' ? value : identity;
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/
function castPath(value, object) {
if (isArray(value)) {
return value;
}
return isKey(value, object) ? [value] : stringToPath(toString(value));
}
/**
* A `baseRest` alias which can be replaced with `identity` by module
* replacement plugins.
*
* @private
* @type {Function}
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
var castRest = baseRest;
/**
* 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);
}
/**
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
*/
var clearTimeout = ctxClearTimeout || function(id) {
return root.clearTimeout(id);
};
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length,
result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
/**
* Creates a clone of `dataView`.
*
* @private
* @param {Object} dataView The data view to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned data view.
*/
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
/**
* Creates a clone of `regexp`.
*
* @private
* @param {Object} regexp The regexp to clone.
* @returns {Object} Returns the cloned regexp.
*/
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
/**
* Creates a clone of the `symbol` object.
*
* @private
* @param {Object} symbol The symbol object to clone.
* @returns {Object} Returns the cloned symbol object.
*/
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/
function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = value !== undefined,
valIsNull = value === null,
valIsReflexive = value === value,
valIsSymbol = isSymbol(value);
var othIsDefined = other !== undefined,
othIsNull = other === null,
othIsReflexive = other === other,
othIsSymbol = isSymbol(other);
if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
(valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
(valIsNull && othIsDefined && othIsReflexive) ||
(!valIsDefined && othIsReflexive) ||
!valIsReflexive) {
return 1;
}
if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
(othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
(othIsNull && valIsDefined && valIsReflexive) ||
(!othIsDefined && valIsReflexive) ||
!othIsReflexive) {
return -1;
}
}
return 0;
}
/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/
function compareMultiple(object, other, orders) {
var index = -1,
objCriteria = object.criteria,
othCriteria = other.criteria,
length = objCriteria.length,
ordersLength = orders.length;
while (++index < length) {
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) {
return result;
}
var order = orders[index];
return result * (order == 'desc' ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgs(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersLength = holders.length,
leftIndex = -1,
leftLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(leftLength + rangeLength),
isUncurried = !isCurried;
while (++leftIndex < leftLength) {
result[leftIndex] = partials[leftIndex];
}
while (++argsIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[holders[argsIndex]] = args[argsIndex];
}
}
while (rangeLength--) {
result[leftIndex++] = args[argsIndex++];
}
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/
function composeArgsRight(args, partials, holders, isCurried) {
var argsIndex = -1,
argsLength = args.length,
holdersIndex = -1,
holdersLength = holders.length,
rightIndex = -1,
rightLength = partials.length,
rangeLength = nativeMax(argsLength - holdersLength, 0),
result = Array(rangeLength + rightLength),
isUncurried = !isCurried;
while (++argsIndex < rangeLength) {
result[argsIndex] = args[argsIndex];
}
var offset = argsIndex;
while (++rightIndex < rightLength) {
result[offset + rightIndex] = partials[rightIndex];
}
while (++holdersIndex < holdersLength) {
if (isUncurried || argsIndex < argsLength) {
result[offset + holders[holdersIndex]] = args[argsIndex++];
}
}
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;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer
? customizer(object[key], source[key], key, object, source)
: undefined;
if (newValue === undefined) {
newValue = source[key];
}
if (isNew) {
baseAssignValue(object, key, newValue);
} else {
assignValue(object, key, newValue);
}
}
return object;
}
/**
* Copies own symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbols(source, object) {
return copyObject(source, getSymbols(source), object);
}
/**
* Copies own and inherited symbols of `source` to `object`.
*
* @private
* @param {Object} source The object to copy symbols from.
* @param {Object} [object={}] The object to copy symbols to.
* @returns {Object} Returns `object`.
*/
function copySymbolsIn(source, object) {
return copyObject(source, getSymbolsIn(source), object);
}
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator,
accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee, 2), accumulator);
};
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1,
length = sources.length,
customizer = length > 1 ? sources[length - 1] : undefined,
guard = length > 2 ? sources[2] : undefined;
customizer = (assigner.length > 3 && typeof customizer == 'function')
? (length--, customizer)
: undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
/**
* 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;
};
}
/**
* 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;
};
}
/**
* Creates a function that wraps `func` to invoke it with the optional `this`
* binding of `thisArg`.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createBind(func, bitmask, thisArg) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return fn.apply(isBind ? thisArg : this, arguments);
}
return wrapper;
}
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/
function createCaseFirst(methodName) {
return function(string) {
string = toString(string);
var strSymbols = hasUnicode(string)
? stringToArray(string)
: undefined;
var chr = strSymbols
? strSymbols[0]
: string.charAt(0);
var trailing = strSymbols
? castSlice(strSymbols, 1).join('')
: string.slice(1);
return chr[methodName]() + trailing;
};
}
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/
function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/
function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch (args.length) {
case 0: return new Ctor;
case 1: return new Ctor(args[0]);
case 2: return new Ctor(args[0], args[1]);
case 3: return new Ctor(args[0], args[1], args[2]);
case 4: return new Ctor(args[0], args[1], args[2], args[3]);
case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype),
result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createCurry(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length,
placeholder = getHolder(wrapper);
while (index--) {
args[index] = arguments[index];
}
var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
? []
: replaceHolders(args, placeholder);
length -= holders.length;
if (length < arity) {
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, undefined,
args, holders, undefined, undefined, arity - length);
}
var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
return apply(fn, this, args);
}
return wrapper;
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike(collection)) {
var iteratee = getIteratee(predicate, 3);
collection = keys(collection);
predicate = function(key) { return iteratee(iterable[key], key, iterable); };
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/
function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length,
index = length,
prereq = LodashWrapper.prototype.thru;
if (fromRight) {
funcs.reverse();
}
while (index--) {
var func = funcs[index];
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
var wrapper = new LodashWrapper([], true);
}
}
index = wrapper ? index : length;
while (++index < length) {
func = funcs[index];
var funcName = getFuncName(func),
data = funcName == 'wrapper' ? getData(func) : undefined;
if (data && isLaziable(data[0]) &&
data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
!data[4].length && data[9] == 1
) {
wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
} else {
wrapper = (func.length == 1 && isLaziable(func))
? wrapper[funcName]()
: wrapper.thru(func);
}
}
return function() {
var args = arguments,
value = args[0];
if (wrapper && args.length == 1 && isArray(value)) {
return wrapper.plant(value).value();
}
var index = 0,
result = length ? funcs[index].apply(this, args) : value;
while (++index < length) {
result = funcs[index].call(this, result);
}
return result;
};
});
}
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = bitmask & WRAP_ARY_FLAG,
isBind = bitmask & WRAP_BIND_FLAG,
isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
isFlip = bitmask & WRAP_FLIP_FLAG,
Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
var length = arguments.length,
args = Array(length),
index = length;
while (index--) {
args[index] = arguments[index];
}
if (isCurried) {
var placeholder = getHolder(wrapper),
holdersCount = countHolders(args, placeholder);
}
if (partials) {
args = composeArgs(args, partials, holders, isCurried);
}
if (partialsRight) {
args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
}
length -= holdersCount;
if (isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(
func, bitmask, createHybrid, wrapper.placeholder, thisArg,
args, newHolders, argPos, ary, arity - length
);
}
var thisBinding = isBind ? thisArg : this,
fn = isBindKey ? thisBinding[func] : func;
length = args.length;
if (argPos) {
args = reorder(args, argPos);
} else if (isFlip && length > 1) {
args.reverse();
}
if (isAry && ary < length) {
args.length = ary;
}
if (this && this !== root && this instanceof wrapper) {
fn = Ctor || createCtor(fn);
}
return fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/
function createInverter(setter, toIteratee) {
return function(object, iteratee) {
return baseInverter(object, setter, toIteratee(iteratee), {});
};
}
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/
function createMathOperation(operator, defaultValue) {
return function(value, other) {
var result;
if (value === undefined && other === undefined) {
return defaultValue;
}
if (value !== undefined) {
result = value;
}
if (other !== undefined) {
if (result === undefined) {
return other;
}
if (typeof value == 'string' || typeof other == 'string') {
value = baseToString(value);
other = baseToString(other);
} else {
value = baseToNumber(value);
other = baseToNumber(other);
}
result = operator(value, other);
}
return result;
};
}
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/
function createOver(arrayFunc) {
return flatRest(function(iteratees) {
iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
return baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/
function createPadding(length, chars) {
chars = chars === undefined ? ' ' : baseToString(chars);
var charsLength = chars.length;
if (charsLength < 2) {
return charsLength ? baseRepeat(chars, length) : chars;
}
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars)
? castSlice(stringToArray(result), 0, length).join('')
: result.slice(0, length);
}
/**
* Creates a function that wraps `func` to invoke it with the `this` binding
* of `thisArg` and `partials` prepended to the arguments it receives.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} partials The arguments to prepend to those provided to
* the new function.
* @returns {Function} Returns the new wrapped function.
*/
function createPartial(func, bitmask, thisArg, partials) {
var isBind = bitmask & WRAP_BIND_FLAG,
Ctor = createCtor(func);
function wrapper() {
var argsIndex = -1,
argsLength = arguments.length,
leftIndex = -1,
leftLength = partials.length,
args = Array(leftLength + argsLength),
fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
while (++leftIndex < leftLength) {
args[leftIndex] = partials[leftIndex];
}
while (argsLength--) {
args[leftIndex++] = arguments[++argsIndex];
}
return apply(fn, isBind ? thisArg : this, args);
}
return wrapper;
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/
function createRange(fromRight) {
return function(start, end, step) {
if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
end = step = undefined;
}
// Ensure the sign of `-0` is preserved.
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
return baseRange(start, end, step, fromRight);
};
}
/**
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
*/
function createRelationalOperation(operator) {
return function(value, other) {
if (!(typeof value == 'string' && typeof other == 'string')) {
value = toNumber(value);
other = toNumber(other);
}
return operator(value, other);
};
}
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = bitmask & WRAP_CURRY_FLAG,
newHolders = isCurry ? holders : undefined,
newHoldersRight = isCurry ? undefined : holders,
newPartials = isCurry ? partials : undefined,
newPartialsRight = isCurry ? undefined : partials;
bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
}
var newData = [
func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
newHoldersRight, argPos, ary, arity
];
var result = wrapFunc.apply(undefined, newData);
if (isLaziable(func)) {
setData(result, newData);
}
result.placeholder = placeholder;
return setWrapToString(result, func, bitmask);
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/
function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
number = toNumber(number);
precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
if (precision && nativeIsFinite(number)) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e'),
value = func(pair[0] + 'e' + (+pair[1] + precision));
pair = (toString(value) + 'e').split('e');
return +(pair[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/
var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
return new Set(values);
};
/**
* 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(object);
if (tag == mapTag) {
return mapToArray(object);
}
if (tag == setTag) {
return setToPairs(object);
}
return baseToPairs(object, keysFunc(object));
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/
function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
if (!isBindKey && typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
var length = partials ? partials.length : 0;
if (!length) {
bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
partials = holders = undefined;
}
ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
arity = arity === undefined ? arity : toInteger(arity);
length -= holders ? holders.length : 0;
if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
var partialsRight = partials,
holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func);
var newData = [
func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
argPos, ary, arity
];
if (data) {
mergeData(newData, data);
}
func = newData[0];
bitmask = newData[1];
thisArg = newData[2];
partials = newData[3];
holders = newData[4];
arity = newData[9] = newData[9] === undefined
? (isBindKey ? 0 : func.length)
: nativeMax(newData[9] - length, 0);
if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
}
if (!bitmask || bitmask == WRAP_BIND_FLAG) {
var result = createBind(func, bitmask, thisArg);
} else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
result = createCurry(func, bitmask, arity);
} else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
result = createPartial(func, bitmask, thisArg, partials);
} else {
result = createHybrid.apply(undefined, newData);
}
var setter = data ? baseSetData : setData;
return setWrapToString(setter(result, newData), func, bitmask);
}
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/
function customDefaultsAssignIn(objValue, srcValue, key, object) {
if (objValue === undefined ||
(eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
return srcValue;
}
return objValue;
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/
function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
if (isObject(objValue) && isObject(srcValue)) {
// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue);
baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
stack['delete'](srcValue);
}
return objValue;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/
function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
// Check that cyclic values are equal.
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1,
result = true,
seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
stack.set(array, other);
stack.set(other, array);
// 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 (!cacheHas(seen, othIndex) &&
(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(
arrValue === othValue ||
equalFunc(arrValue, othValue, bitmask, customizer, stack)
)) {
result = false;
break;
}
}
stack['delete'](array);
stack['delete'](other);
return result;
}
/**
* 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @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, bitmask, customizer, equalFunc, 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:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == (other + '');
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
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 |= COMPARE_UNORDERED_FLAG;
// Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack['delete'](object);
return result;
case symbolTag:
if (symbolValueOf) {
return symbolValueOf.call(object) == symbolValueOf.call(other);
}
}
return false;
}
/**
* 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 {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
objProps = getAllKeys(object),
objLength = objProps.length,
othProps = getAllKeys(other),
othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
// Check that cyclic values are equal.
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
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, bitmask, customizer, 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);
stack['delete'](other);
return result;
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/
function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/
function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/
var getData = !metaMap ? noop : function(func) {
return metaMap.get(func);
};
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/
function getFuncName(func) {
var result = (func.name + ''),
array = realNames[result],
length = hasOwnProperty.call(realNames, result) ? array.length : 0;
while (length--) {
var data = array[length],
otherFunc = data.func;
if (otherFunc == null || otherFunc == func) {
return data.name;
}
}
return result;
}
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/
function getHolder(func) {
var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
return object.placeholder;
}
/**
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
*/
function getIteratee() {
var result = lodash.iteratee || iteratee;
result = result === iteratee ? baseIteratee : result;
return arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
* 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;
}
/**
* 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 = keys(object),
length = result.length;
while (length--) {
var key = result[length],
value = object[key];
result[length] = [key, value, isStrictComparable(value)];
}
return result;
}
/**
* 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 = getValue(object, key);
return baseIsNative(value) ? value : undefined;
}
/**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag),
tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
};
/**
* Creates an array of the own and inherited enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/
var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
var result = [];
while (object) {
arrayPush(result, getSymbols(object));
object = getPrototype(object);
}
return result;
};
/**
* Gets the `toStringTag` of `value`.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/
var getTag = baseGetTag;
// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
(Map && getTag(new Map) != mapTag) ||
(Promise && getTag(Promise.resolve()) != promiseTag) ||
(Set && getTag(new Set) != setTag) ||
(WeakMap && getTag(new WeakMap) != weakMapTag)) {
getTag = function(value) {
var result = baseGetTag(value),
Ctor = result == objectTag ? value.constructor : undefined,
ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) {
switch (ctorString) {
case dataViewCtorString: return dataViewTag;
case mapCtorString: return mapTag;
case promiseCtorString: return promiseTag;
case setCtorString: return setTag;
case weakMapCtorString: return weakMapTag;
}
}
return result;
};
}
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
/**
* Extracts wrapper details from the `source` body comment.
*
* @private
* @param {string} source The source to inspect.
* @returns {Array} Returns the wrapper details.
*/
function getWrapDetails(source) {
var match = source.match(reWrapDetails);
return match ? match[1].split(reSplitDetails) : [];
}
/**
* 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 = castPath(path, object);
var index = -1,
length = path.length,
result = false;
while (++index < length) {
var key = toKey(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength(length) && isIndex(key, length) &&
(isArray(object) || isArguments(object));
}
/**
* Initializes an array clone.
*
* @private
* @param {Array} array The array to clone.
* @returns {Array} Returns the initialized clone.
*/
function initCloneArray(array) {
var length = array.length,
result = new array.constructor(length);
// Add properties assigned by `RegExp#exec`.
if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
result.index = array.index;
result.input = array.input;
}
return result;
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneObject(object) {
return (typeof object.constructor == 'function' && !isPrototype(object))
? baseCreate(getPrototype(object))
: {};
}
/**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return cloneDataView(object, isDeep);
case float32Tag: case float64Tag:
case int8Tag: case int16Tag: case int32Tag:
case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return cloneRegExp(object);
case setTag:
return new Ctor;
case symbolTag:
return cloneSymbol(object);
}
}
/**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/
function insertWrapDetails(source, details) {
var length = details.length;
if (!length) {
return source;
}
var lastIndex = length - 1;
details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
details = details.join(length > 2 ? ', ' : ' ');
return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/
function isFlattenable(value) {
return isArray(value) || isArguments(value) ||
!!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* 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) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length &&
(type == 'number' ||
(type != 'symbol' && reIsUint.test(value))) &&
(value > -1 && value % 1 == 0 && value < length);
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)
) {
return eq(object[index], value);
}
return false;
}
/**
* 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));
}
/**
* 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);
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/
function isLaziable(func) {
var funcName = getFuncName(func),
other = lodash[funcName];
if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
return false;
}
if (func === other) {
return true;
}
var data = getData(other);
return !!data && func === data[0];
}
/**
* Checks if `func` has its source masked.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` is masked, else `false`.
*/
function isMasked(func) {
return !!maskSrcKey && (maskSrcKey in func);
}
/**
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
*/
var isMaskable = coreJsData ? isFunction : stubFalse;
/**
* 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;
return value === proto;
}
/**
* 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 `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)));
};
}
/**
* A specialized version of `_.memoize` which clears the memoized function's
* cache when it exceeds `MAX_MEMOIZE_SIZE`.
*
* @private
* @param {Function} func The function to have its output memoized.
* @returns {Function} Returns the new memoized function.
*/
function memoizeCapped(func) {
var result = memoize(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
/**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/
function mergeData(data, source) {
var bitmask = data[1],
srcBitmask = source[1],
newBitmask = bitmask | srcBitmask,
isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
var isCombo =
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
// Exit early if metadata can't be merged.
if (!(isCommon || isCombo)) {
return data;
}
// Use source `thisArg` if available.
if (srcBitmask & WRAP_BIND_FLAG) {
data[2] = source[2];
// Set when currying a bound function.
newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
}
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value;
data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
value = source[5];
if (value) {
partials = data[5];
data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
}
// Use source `argPos` if available.
value = source[7];
if (value) {
data[7] = value;
}
// Use source `ary` if it's smaller.
if (srcBitmask & WRAP_ARY_FLAG) {
data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
}
// Use source `arity` if one is not provided.
if (data[9] == null) {
data[9] = source[9];
}
// Use source `func` and merge bitmasks.
data[0] = source[0];
data[1] = newBitmask;
return data;
}
/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
/**
* Converts `value` to a string using `Object.prototype.toString`.
*
* @private
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
*/
function objectToString(value) {
return nativeObjectToString.call(value);
}
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/
function overRest(func, start, transform) {
start = nativeMax(start === undefined ? (func.length - 1) : 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];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply(func, this, otherArgs);
};
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/
function reorder(array, indexes) {
var arrLength = array.length,
length = nativeMin(indexes.length, arrLength),
oldArray = copyArray(array);
while (length--) {
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/
function safeGet(object, key) {
if (key === 'constructor' && typeof object[key] === 'function') {
return;
}
if (key == '__proto__') {
return;
}
return object[key];
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/
var setData = shortOut(baseSetData);
/**
* A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @returns {number|Object} Returns the timer id or timeout object.
*/
var setTimeout = ctxSetTimeout || function(func, wait) {
return root.setTimeout(func, wait);
};
/**
* Sets the `toString` method of `func` to return `string`.
*
* @private
* @param {Function} func The function to modify.
* @param {Function} string The `toString` result.
* @returns {Function} Returns `func`.
*/
var setToString = shortOut(baseSetToString);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/
function setWrapToString(wrapper, reference, bitmask) {
var source = (reference + '');
return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
}
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/
function shortOut(func) {
var count = 0,
lastCalled = 0;
return function() {
var stamp = nativeNow(),
remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(undefined, arguments);
};
}
/**
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
*/
function shuffleSelf(array, size) {
var index = -1,
length = array.length,
lastIndex = length - 1;
size = size === undefined ? length : size;
while (++index < size) {
var rand = baseRandom(index, lastIndex),
value = array[rand];
array[rand] = array[index];
array[index] = value;
}
array.length = size;
return array;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/
var stringToPath = memoizeCapped(function(string) {
var result = [];
if (string.charCodeAt(0) === 46 /* . */) {
result.push('');
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
});
return result;
});
/**
* 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) ? '-0' : result;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return (func + '');
} catch (e) {}
}
return '';
}
/**
* Updates wrapper `details` based on `bitmask` flags.
*
* @private
* @returns {Array} details The details to modify.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Array} Returns `details`.
*/
function updateWrapDetails(details, bitmask) {
arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
details.push(value);
}
});
return details.sort();
}
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/
function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) {
return wrapper.clone();
}
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
result.__actions__ = copyArray(wrapper.__actions__);
result.__index__ = wrapper.__index__;
result.__values__ = wrapper.__values__;
return result;
}
/*------------------------------------------------------------------------*/
/**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/
function chunk(array, size, guard) {
if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
size = 1;
} else {
size = nativeMax(toInteger(size), 0);
}
var length = array == null ? 0 : array.length;
if (!length || size < 1) {
return [];
}
var index = 0,
resIndex = 0,
result = Array(nativeCeil(length / size));
while (index < length) {
result[resIndex++] = baseSlice(array, index, (index += size));
}
return result;
}
/**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/
function compact(array) {
var index = -1,
length = array == null ? 0 : array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
/**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/
function concat() {
var length = arguments.length;
if (!length) {
return [];
}
var args = Array(length - 1),
array = arguments[0],
index = length;
while (index--) {
args[index - 1] = arguments[index];
}
return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
}
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/
var difference = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
: [];
});
/**
* This method is like `_.difference` except that it accepts `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `_.pullAllBy`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2]
*
* // The `_.property` iteratee shorthand.
* _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var differenceBy = baseRest(function(array, values) {
var iteratee = last(values);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
*/
var differenceWith = baseRest(function(array, values) {
var comparator = last(values);
if (isArrayLikeObject(comparator)) {
comparator = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
: [];
});
/**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/
function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true, true)
: [];
}
/**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/
function dropWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), true)
: [];
}
/**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
*/
function fill(array, value, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
start = 0;
end = length;
}
return baseFill(array, value, start, end);
}
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseFindIndex(array, getIteratee(predicate, 3), index);
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/
function findLastIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length - 1;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = fromIndex < 0
? nativeMax(length + index, 0)
: nativeMin(index, length - 1);
}
return baseFindIndex(array, getIteratee(predicate, 3), index, true);
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
/**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/
function flattenDeep(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, INFINITY) : [];
}
/**
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
*/
function flattenDepth(array, depth) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(array, depth);
}
/**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/
function fromPairs(pairs) {
var index = -1,
length = pairs == null ? 0 : pairs.length,
result = {};
while (++index < length) {
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/
function head(array) {
return (array && array.length) ? array[0] : undefined;
}
/**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger(fromIndex);
if (index < 0) {
index = nativeMax(length + index, 0);
}
return baseIndexOf(array, value, index);
}
/**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/
function initial(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 0, -1) : [];
}
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/
var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped)
: [];
});
/**
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
*/
var intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
if (iteratee === last(mapped)) {
iteratee = undefined;
} else {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, getIteratee(iteratee, 2))
: [];
});
/**
* This method is like `_.intersection` except that it accepts `comparator`
* which is invoked to compare elements of `arrays`. The order and references
* of result values are determined by the first array. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.intersectionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }]
*/
var intersectionWith = baseRest(function(arrays) {
var comparator = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
comparator = typeof comparator == 'function' ? comparator : undefined;
if (comparator) {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, undefined, comparator)
: [];
});
/**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/
function join(array, separator) {
return array == null ? '' : nativeJoin.call(array, separator);
}
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = length;
if (fromIndex !== undefined) {
index = toInteger(fromIndex);
index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
}
return value === value
? strictLastIndexOf(array, value, index)
: baseFindIndex(array, baseIsNaN, index, true);
}
/**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
*/
function nth(array, n) {
return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
}
/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/
var pull = baseRest(pullAll);
/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/
function pullAll(array, values) {
return (array && array.length && values && values.length)
? basePullAll(array, values)
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, getIteratee(iteratee, 2))
: array;
}
/**
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
*/
function pullAllWith(array, values, comparator) {
return (array && array.length && values && values.length)
? basePullAll(array, values, undefined, comparator)
: array;
}
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/
var pullAt = flatRest(function(array, indexes) {
var length = array == null ? 0 : array.length,
result = baseAt(array, indexes);
basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending));
return result;
});
/**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/
function remove(array, predicate) {
var result = [];
if (!(array && array.length)) {
return result;
}
var index = -1,
indexes = [],
length = array.length;
predicate = getIteratee(predicate, 3);
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result.push(value);
indexes.push(index);
}
}
basePullAt(array, indexes);
return result;
}
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function reverse(array) {
return array == null ? array : nativeReverse.call(array);
}
/**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @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 slice(array, start, end) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
start = 0;
end = length;
}
else {
start = start == null ? 0 : toInteger(start);
end = end === undefined ? length : toInteger(end);
}
return baseSlice(array, start, end);
}
/**
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*/
function sortedIndex(array, value) {
return baseSortedIndex(array, value);
}
/**
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/
function sortedIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
}
/**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/
function sortedIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
*/
function sortedLastIndex(array, value) {
return baseSortedIndex(array, value, true);
}
/**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
*/
function sortedLastIndexBy(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
}
/**
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
*/
function sortedLastIndexOf(array, value) {
var length = array == null ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value, true) - 1;
if (eq(array[index], value)) {
return index;
}
}
return -1;
}
/**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/
function sortedUniq(array) {
return (array && array.length)
? baseSortedUniq(array)
: [];
}
/**
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
*/
function sortedUniqBy(array, iteratee) {
return (array && array.length)
? baseSortedUniq(array, getIteratee(iteratee, 2))
: [];
}
/**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
*/
function tail(array) {
var length = array == null ? 0 : array.length;
return length ? baseSlice(array, 1, length) : [];
}
/**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/
function take(array, n, guard) {
if (!(array && array.length)) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
return baseSlice(array, 0, n < 0 ? 0 : n);
}
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}
/**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
*/
function takeRightWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3), false, true)
: [];
}
/**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
*/
function takeWhile(array, predicate) {
return (array && array.length)
? baseWhile(array, getIteratee(predicate, 3))
: [];
}
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/
var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
});
/**
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. Result values are chosen from the first
* array in which the value occurs. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
var unionBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
});
/**
* This method is like `_.union` except that it accepts `comparator` which
* is invoked to compare elements of `arrays`. Result values are chosen from
* the first array in which the value occurs. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.unionWith(objects, others, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var unionWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
});
/**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/
function uniq(array) {
return (array && array.length) ? baseUniq(array) : [];
}
/**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
function uniqBy(array, iteratee) {
return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
}
/**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/
function uniqWith(array, comparator) {
comparator = typeof comparator == 'function' ? comparator : undefined;
return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
}
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
*/
function unzip(array) {
if (!(array && array.length)) {
return [];
}
var length = 0;
array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) {
length = nativeMax(group.length, length);
return true;
}
});
return baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}
/**
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/
function unzipWith(array, iteratee) {
if (!(array && array.length)) {
return [];
}
var result = unzip(array);
if (iteratee == null) {
return result;
}
return arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/
var without = baseRest(function(array, values) {
return isArrayLikeObject(array)
? baseDifference(array, values)
: [];
});
/**
* Creates an array of unique values that is the
* [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
* of the given arrays. The order of result values is determined by the order
* they occur in the arrays.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.without
* @example
*
* _.xor([2, 1], [2, 3]);
* // => [1, 3]
*/
var xor = baseRest(function(arrays) {
return baseXor(arrayFilter(arrays, isArrayLikeObject));
});
/**
* This method is like `_.xor` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which by which they're compared. The order of result values is determined
* by the order they occur in the arrays. The iteratee is invoked with one
* argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [1.2, 3.4]
*
* // The `_.property` iteratee shorthand.
* _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 2 }]
*/
var xorBy = baseRest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
});
/**
* This method is like `_.xor` except that it accepts `comparator` which is
* invoked to compare elements of `arrays`. The order of result values is
* determined by the order they occur in the arrays. The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
* var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.xorWith(objects, others, _.isEqual);
* // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
*/
var xorWith = baseRest(function(arrays) {
var comparator = last(arrays);
comparator = typeof comparator == 'function' ? comparator : undefined;
return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
});
/**
* Creates an array of grouped elements, the first of which contains the
* first elements of the given arrays, the second of which contains the
* second elements of the given arrays, and so on.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*/
var zip = baseRest(unzip);
/**
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
*/
function zipObject(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}
/**
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
*/
function zipObjectDeep(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}
/**
* This method is like `_.zip` except that it accepts `iteratee` to specify
* how grouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {...Array} [arrays] The arrays to process.
* @param {Function} [iteratee=_.identity] The function to combine
* grouped values.
* @returns {Array} Returns the new array of grouped elements.
* @example
*
* _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
* return a + b + c;
* });
* // => [111, 222]
*/
var zipWith = baseRest(function(arrays) {
var length = arrays.length,
iteratee = length > 1 ? arrays[length - 1] : undefined;
iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
return unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/
/**
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
*/
function chain(value) {
var result = lodash(value);
result.__chain__ = true;
return result;
}
/**
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/
function tap(value, interceptor) {
interceptor(value);
return value;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/
function thru(value, interceptor) {
return interceptor(value);
}
/**
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
*/
var wrapperAt = flatRest(function(paths) {
var length = paths.length,
start = length ? paths[0] : 0,
value = this.__wrapped__,
interceptor = function(object) { return baseAt(object, paths); };
if (length > 1 || this.__actions__.length ||
!(value instanceof LazyWrapper) || !isIndex(start)) {
return this.thru(interceptor);
}
value = value.slice(start, +start + (length ? 1 : 0));
value.__actions__.push({
'func': thru,
'args': [interceptor],
'thisArg': undefined
});
return new LodashWrapper(value, this.__chain__).thru(function(array) {
if (length && !array.length) {
array.push(undefined);
}
return array;
});
});
/**
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/
function wrapperChain() {
return chain(this);
}
/**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/
function wrapperCommit() {
return new LodashWrapper(this.value(), this.__chain__);
}
/**
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
*/
function wrapperNext() {
if (this.__values__ === undefined) {
this.__values__ = toArray(this.value());
}
var done = this.__index__ >= this.__values__.length,
value = done ? undefined : this.__values__[this.__index__++];
return { 'done': done, 'value': value };
}
/**
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
*/
function wrapperToIterator() {
return this;
}
/**
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
*/
function wrapperPlant(value) {
var result,
parent = this;
while (parent instanceof baseLodash) {
var clone = wrapperClone(parent);
clone.__index__ = 0;
clone.__values__ = undefined;
if (result) {
previous.__wrapped__ = clone;
} else {
result = clone;
}
var previous = clone;
parent = parent.__wrapped__;
}
previous.__wrapped__ = value;
return result;
}
/**
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/
function wrapperReverse() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
if (this.__actions__.length) {
wrapped = new LazyWrapper(this);
}
wrapped = wrapped.reverse();
wrapped.__actions__.push({
'func': thru,
'args': [reverse],
'thisArg': undefined
});
return new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}
/**
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/
function wrapperValue() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}
/*------------------------------------------------------------------------*/
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the number of times the key was returned by `iteratee`. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.5.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': 1, '6': 2 }
*
* // The `_.property` iteratee shorthand.
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
++result[key];
} else {
baseAssignValue(result, key, 1);
}
});
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/
function filter(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, getIteratee(predicate, 3));
}
/**
* Iterates over elements of `collection`, returning the first element
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false },
* { 'user': 'pebbles', 'age': 1, 'active': true }
* ];
*
* _.find(users, function(o) { return o.age < 40; });
* // => object for 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.find(users, { 'age': 1, 'active': true });
* // => object for 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.find(users, ['active', false]);
* // => object for 'fred'
*
* // The `_.property` iteratee shorthand.
* _.find(users, 'active');
* // => object for 'barney'
*/
var find = createFind(findIndex);
/**
* This method is like `_.find` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=collection.length-1] The index to search from.
* @returns {*} Returns the matched element, else `undefined`.
* @example
*
* _.findLast([1, 2, 3, 4], function(n) {
* return n % 2 == 1;
* });
* // => 3
*/
var findLast = createFind(findLastIndex);
/**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMap(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/
function flatMapDeep(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}
/**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
*/
function flatMapDepth(collection, iteratee, depth) {
depth = depth === undefined ? 1 : toInteger(depth);
return baseFlatten(map(collection, iteratee), depth);
}
/**
* 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
*
* _.forEach([1, 2], 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, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @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 _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
*/
function forEachRight(collection, iteratee) {
var func = isArray(collection) ? arrayEachRight : baseEachRight;
return func(collection, getIteratee(iteratee, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/
var groupBy = createAggregator(function(result, value, key) {
if (hasOwnProperty.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue(result, key, [value]);
}
});
/**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection);
fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax(length + fromIndex, 0);
}
return isString(collection)
? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
: (!!length && baseIndexOf(collection, value, fromIndex) > -1);
}
/**
* Invokes the method at `path` of each element in `collection`, returning
* an array of the results of each invoked method. Any additional arguments
* are provided to each invoked method. If `path` is a function, it's invoked
* for, and `this` bound to, each element in `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array|Function|string} path The path of the method to invoke or
* the function invoked per iteration.
* @param {...*} [args] The arguments to invoke each method with.
* @returns {Array} Returns the array of results.
* @example
*
* _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
* // => [[1, 5, 7], [1, 2, 3]]
*
* _.invokeMap([123, 456], String.prototype.split, '');
* // => [['1', '2', '3'], ['4', '5', '6']]
*/
var invokeMap = baseRest(function(collection, path, args) {
var index = -1,
isFunc = typeof path == 'function',
result = isArrayLike(collection) ? Array(collection.length) : [];
baseEach(collection, function(value) {
result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
});
return result;
});
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The corresponding value of
* each key is the last element responsible for generating the key. The
* iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* var array = [
* { 'dir': 'left', 'code': 97 },
* { 'dir': 'right', 'code': 100 }
* ];
*
* _.keyBy(array, function(o) {
* return String.fromCharCode(o.code);
* });
* // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
*
* _.keyBy(array, 'dir');
* // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
*/
var keyBy = createAggregator(function(result, value, key) {
baseAssignValue(result, key, value);
});
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/
function map(collection, iteratee) {
var func = isArray(collection) ? arrayMap : baseMap;
return func(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
*/
var partition = createAggregator(function(result, value, key) {
result[key ? 0 : 1].push(value);
}, function() { return [[], []]; });
/**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/
function reduce(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}
/**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/
function reduceRight(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce,
initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}
/**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/
function reject(collection, predicate) {
var func = isArray(collection) ? arrayFilter : baseFilter;
return func(collection, negate(getIteratee(predicate, 3)));
}
/**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/
function sample(collection) {
var func = isArray(collection) ? arraySample : baseSample;
return func(collection);
}
/**
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
*/
function sampleSize(collection, n, guard) {
if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
var func = isArray(collection) ? arraySampleSize : baseSampleSize;
return func(collection, n);
}
/**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/
function shuffle(collection) {
var func = isArray(collection) ? arrayShuffle : baseShuffle;
return func(collection);
}
/**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/
function size(collection) {
if (collection == null) {
return 0;
}
if (isArrayLike(collection)) {
return isString(collection) ? stringSize(collection) : collection.length;
}
var tag = getTag(collection);
if (tag == mapTag || tag == setTag) {
return collection.size;
}
return baseKeys(collection).length;
}
/**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/
function some(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
if (guard && isIterateeCall(collection, predicate, guard)) {
predicate = undefined;
}
return func(collection, getIteratee(predicate, 3));
}
/**
* Creates an array of elements, sorted in ascending order by the results of
* running each element in a collection thru each iteratee. This method
* performs a stable sort, that is, it preserves the original sort order of
* equal elements. The iteratees are invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to sort by.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 30 },
* { 'user': 'barney', 'age': 34 }
* ];
*
* _.sortBy(users, [function(o) { return o.user; }]);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
*
* _.sortBy(users, ['user', 'age']);
* // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
*/
var sortBy = baseRest(function(collection, iteratees) {
if (collection == null) {
return [];
}
var length = iteratees.length;
if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
iteratees = [];
} else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
iteratees = [iteratees[0]];
}
return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
});
/*------------------------------------------------------------------------*/
/**
* Gets the timestamp of the number of milliseconds that have elapsed since
* the Unix epoch (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Date
* @returns {number} Returns the timestamp.
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => Logs the number of milliseconds it took for the deferred invocation.
*/
var now = ctxNow || function() {
return root.Date.now();
};
/*------------------------------------------------------------------------*/
/**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
*/
function after(n, func) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n < 1) {
return func.apply(this, arguments);
}
};
}
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/
function ary(func, n, guard) {
n = guard ? undefined : n;
n = (func && n == null) ? func.length : n;
return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/
function before(n, func) {
var result;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
n = toInteger(n);
return function() {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/
var bind = baseRest(function(func, thisArg, partials) {
var bitmask = WRAP_BIND_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(func, bitmask, thisArg, partials, holders);
});
/**
* Creates a function that invokes the method at `object[key]` with `partials`
* prepended to the arguments it receives.
*
* This method differs from `_.bind` by allowing bound functions to reference
* methods that may be redefined or don't yet exist. See
* [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
* for more details.
*
* The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* @static
* @memberOf _
* @since 0.10.0
* @category Function
* @param {Object} object The object to invoke the method on.
* @param {string} key The key of the method.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* var object = {
* 'user': 'fred',
* 'greet': function(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
* };
*
* var bound = _.bindKey(object, 'greet', 'hi');
* bound('!');
* // => 'hi fred!'
*
* object.greet = function(greeting, punctuation) {
* return greeting + 'ya ' + this.user + punctuation;
* };
*
* bound('!');
* // => 'hiya fred!'
*
* // Bound with placeholders.
* var bound = _.bindKey(object, 'greet', _, '!');
* bound('hi');
* // => 'hiya fred!'
*/
var bindKey = baseRest(function(object, key, partials) {
var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bindKey));
bitmask |= WRAP_PARTIAL_FLAG;
}
return createWrap(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/
function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curry.placeholder;
return result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/
function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
result.placeholder = curryRight.placeholder;
return result;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/
function debounce(func, wait, options) {
var lastArgs,
lastThis,
maxWait,
result,
timerId,
lastCallTime,
lastInvokeTime = 0,
leading = false,
maxing = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = toNumber(wait) || 0;
if (isObject(options)) {
leading = !!options.leading;
maxing = 'maxWait' in options;
maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function invokeFunc(time) {
var args = lastArgs,
thisArg = lastThis;
lastArgs = lastThis = undefined;
lastInvokeTime = time;
result = func.apply(thisArg, args);
return result;
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time;
// Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait);
// Invoke the leading edge.
return leading ? invokeFunc(time) : result;
}
function remainingWait(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime,
timeWaiting = wait - timeSinceLastCall;
return maxing
? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting;
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime,
timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
}
function timerExpired() {
var time = now();
if (shouldInvoke(time)) {
return trailingEdge(time);
}
// Restart the timer.
timerId = setTimeout(timerExpired, remainingWait(time));
}
function trailingEdge(time) {
timerId = undefined;
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time);
}
lastArgs = lastThis = undefined;
return result;
}
function cancel() {
if (timerId !== undefined) {
clearTimeout(timerId);
}
lastInvokeTime = 0;
lastArgs = lastCallTime = lastThis = timerId = undefined;
}
function flush() {
return timerId === undefined ? result : trailingEdge(now());
}
function debounced() {
var time = now(),
isInvoking = shouldInvoke(time);
lastArgs = arguments;
lastThis = this;
lastCallTime = time;
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime);
}
if (maxing) {
// Handle invocations in a tight loop.
clearTimeout(timerId);
timerId = setTimeout(timerExpired, wait);
return invokeFunc(lastCallTime);
}
}
if (timerId === undefined) {
timerId = setTimeout(timerExpired, wait);
}
return result;
}
debounced.cancel = cancel;
debounced.flush = flush;
return debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/
var defer = baseRest(function(func, args) {
return baseDelay(func, 1, args);
});
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => Logs 'later' after one second.
*/
var delay = baseRest(function(func, wait, args) {
return baseDelay(func, toNumber(wait) || 0, args);
});
/**
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/
function flip(func) {
return createWrap(func, WRAP_FLIP_FLAG);
}
/**
* 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/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `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 != null && typeof resolver != 'function')) {
throw new TypeError(FUNC_ERROR_TEXT);
}
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) || cache;
return result;
};
memoized.cache = new (memoize.Cache || MapCache);
return memoized;
}
// Expose `MapCache`.
memoize.Cache = MapCache;
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/
function negate(predicate) {
if (typeof predicate != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return function() {
var args = arguments;
switch (args.length) {
case 0: return !predicate.call(this);
case 1: return !predicate.call(this, args[0]);
case 2: return !predicate.call(this, args[0], args[1]);
case 3: return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
/**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/
function once(func) {
return before(2, func);
}
/**
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
*/
var overArgs = castRest(function(func, transforms) {
transforms = (transforms.length == 1 && isArray(transforms[0]))
? arrayMap(transforms[0], baseUnary(getIteratee()))
: arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
var funcsLength = transforms.length;
return baseRest(function(args) {
var index = -1,
length = nativeMin(args.length, funcsLength);
while (++index < length) {
args[index] = transforms[index].call(this, args[index]);
}
return apply(func, this, args);
});
});
/**
* Creates a function that invokes `func` with `partials` prepended to the
* arguments it receives. This method is like `_.bind` except it does **not**
* alter the `this` binding.
*
* The `_.partial.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 0.2.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var sayHelloTo = _.partial(greet, 'hello');
* sayHelloTo('fred');
* // => 'hello fred'
*
* // Partially applied with placeholders.
* var greetFred = _.partial(greet, _, 'fred');
* greetFred('hi');
* // => 'hi fred'
*/
var partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
});
/**
* This method is like `_.partial` except that partially applied arguments
* are appended to the arguments it receives.
*
* The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for partially applied arguments.
*
* **Note:** This method doesn't set the "length" property of partially
* applied functions.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Function
* @param {Function} func The function to partially apply arguments to.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new partially applied function.
* @example
*
* function greet(greeting, name) {
* return greeting + ' ' + name;
* }
*
* var greetFred = _.partialRight(greet, 'fred');
* greetFred('hi');
* // => 'hi fred'
*
* // Partially applied with placeholders.
* var sayHelloTo = _.partialRight(greet, 'hello', _);
* sayHelloTo('fred');
* // => 'hello fred'
*/
var partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
});
/**
* Creates a function that invokes `func` with arguments arranged according
* to the specified `indexes` where the argument value at the first index is
* provided as the first argument, the argument value at the second index is
* provided as the second argument, and so on.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to rearrange arguments for.
* @param {...(number|number[])} indexes The arranged argument indexes.
* @returns {Function} Returns the new function.
* @example
*
* var rearged = _.rearg(function(a, b, c) {
* return [a, b, c];
* }, [2, 0, 1]);
*
* rearged('b', 'c', 'a')
* // => ['a', 'b', 'c']
*/
var rearg = flatRest(function(func, indexes) {
return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
});
/**
* 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 = start === undefined ? start : toInteger(start);
return baseRest(func, start);
}
/**
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/
function spread(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = start == null ? 0 : nativeMax(toInteger(start), 0);
return baseRest(function(args) {
var array = args[start],
otherArgs = castSlice(args, 0, start);
if (array) {
arrayPush(otherArgs, array);
}
return apply(func, this, otherArgs);
});
}
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, {
'leading': leading,
'maxWait': wait,
'trailing': trailing
});
}
/**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/
function unary(func) {
return ary(func, 1);
}
/**
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, & pebbles</p>'
*/
function wrap(value, wrapper) {
return partial(castFunction(wrapper), value);
}
/*------------------------------------------------------------------------*/
/**
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
*/
function castArray() {
if (!arguments.length) {
return [];
}
var value = arguments[0];
return isArray(value) ? value : [value];
}
/**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/
function clone(value) {
return baseClone(value, CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
}
/**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/
function cloneDeep(value) {
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
}
/**
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
*/
function cloneDeepWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
}
/**
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
*/
function conformsTo(object, source) {
return source == null || baseConformsTo(object, source, keys(source));
}
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.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 = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.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);
}
/**
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
*/
var gt = createRelationalOperation(baseGt);
/**
* Checks if `value` is greater than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than or equal to
* `other`, else `false`.
* @see _.lte
* @example
*
* _.gte(3, 1);
* // => true
*
* _.gte(3, 3);
* // => true
*
* _.gte(1, 3);
* // => false
*/
var gte = createRelationalOperation(function(value, other) {
return value >= other;
});
/**
* 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 an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
!propertyIsEnumerable.call(value, 'callee');
};
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(document.body.children);
* // => false
*
* _.isArray('abc');
* // => false
*
* _.isArray(_.noop);
* // => false
*/
var isArray = Array.isArray;
/**
* Checks if `value` is classified as an `ArrayBuffer` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
* @example
*
* _.isArrayBuffer(new ArrayBuffer(2));
* // => true
*
* _.isArrayBuffer(new Array(2));
* // => false
*/
var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
/**
* 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(value.length) && !isFunction(value);
}
/**
* 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);
}
/**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/
function isBoolean(value) {
return value === true || value === false ||
(isObjectLike(value) && baseGetTag(value) == boolTag);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/
var isBuffer = nativeIsBuffer || stubFalse;
/**
* Checks if `value` is classified as a `Date` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
* @example
*
* _.isDate(new Date);
* // => true
*
* _.isDate('Mon April 23 2012');
* // => false
*/
var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
/**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/
function isElement(value) {
return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
}
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @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 (value == null) {
return true;
}
if (isArrayLike(value) &&
(isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
isBuffer(value) || isTypedArray(value) || isArguments(value))) {
return !value.length;
}
var tag = getTag(value);
if (tag == mapTag || tag == setTag) {
return !value.size;
}
if (isPrototype(value)) {
return !baseKeys(value).length;
}
for (var key in value) {
if (hasOwnProperty.call(value, key)) {
return false;
}
}
return true;
}
/**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.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 = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/
function isEqual(value, other) {
return baseIsEqual(value, other);
}
/**
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
*/
function isEqualWith(value, other, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
var result = customizer ? customizer(value, other) : undefined;
return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
}
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/
function isError(value) {
if (!isObjectLike(value)) {
return false;
}
var tag = baseGetTag(value);
return tag == errorTag || tag == domExcTag ||
(typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
}
/**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/
function isFinite(value) {
return typeof value == 'number' && nativeIsFinite(value);
}
/**
* 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 a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
if (!isObject(value)) {
return false;
}
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/
function isInteger(value) {
return typeof value == 'number' && value == toInteger(value);
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.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 the
* [language type](http://www.ecma-international.org/ecma-262/7.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 != null && (type == 'object' || type == 'function');
}
/**
* 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 != null && typeof value == 'object';
}
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/
var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
/**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/
function isMatch(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}
/**
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
*/
function isMatchWith(object, source, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseIsMatch(object, source, getMatchData(source), customizer);
}
/**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/
function isNaN(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}
/**
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @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 (isMaskable(value)) {
throw new Error(CORE_ERROR_TEXT);
}
return baseIsNative(value);
}
/**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/
function isNull(value) {
return value === null;
}
/**
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
*/
function isNil(value) {
return value == null;
}
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/
function isNumber(value) {
return typeof value == 'number' ||
(isObjectLike(value) && baseGetTag(value) == numberTag);
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
return false;
}
var proto = getPrototype(value);
if (proto === null) {
return true;
}
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor == 'function' && Ctor instanceof Ctor &&
funcToString.call(Ctor) == objectCtorString;
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/
var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
/**
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
*/
function isSafeInteger(value) {
return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as a `Set` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
* @example
*
* _.isSet(new Set);
* // => true
*
* _.isSet(new WeakSet);
* // => false
*/
var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
/**
* 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 a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' ||
(!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
}
/**
* 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 a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/
function isSymbol(value) {
return typeof value == 'symbol' ||
(isObjectLike(value) && baseGetTag(value) == symbolTag);
}
/**
* 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 a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
/**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/
function isUndefined(value) {
return value === undefined;
}
/**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/
function isWeakMap(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}
/**
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
*/
function isWeakSet(value) {
return isObjectLike(value) && baseGetTag(value) == weakSetTag;
}
/**
* Checks if `value` is less than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
* @see _.gt
* @example
*
* _.lt(1, 3);
* // => true
*
* _.lt(3, 3);
* // => false
*
* _.lt(3, 1);
* // => false
*/
var lt = createRelationalOperation(baseLt);
/**
* Checks if `value` is less than or equal to `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than or equal to
* `other`, else `false`.
* @see _.gte
* @example
*
* _.lte(1, 3);
* // => true
*
* _.lte(3, 3);
* // => true
*
* _.lte(3, 1);
* // => false
*/
var lte = createRelationalOperation(function(value, other) {
return value <= other;
});
/**
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
*/
function toArray(value) {
if (!value) {
return [];
}
if (isArrayLike(value)) {
return isString(value) ? stringToArray(value) : copyArray(value);
}
if (symIterator && value[symIterator]) {
return iteratorToArray(value[symIterator]());
}
var tag = getTag(value),
func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
return func(value);
}
/**
* 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 method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.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;
}
/**
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
*/
function toLength(value) {
return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
}
/**
* 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 = typeof value.valueOf == 'function' ? value.valueOf() : value;
value = isObject(other) ? (other + '') : other;
}
if (typeof value != 'string') {
return value === 0 ? value : +value;
}
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return (isBinary || reIsOctal.test(value))
? freeParseInt(value.slice(2), isBinary ? 2 : 8)
: (reIsBadHex.test(value) ? NAN : +value);
}
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
/**
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
*/
function toSafeInteger(value) {
return value
? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
: (value === 0 ? value : 0);
}
/**
* 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 convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/
function toString(value) {
return value == null ? '' : baseToString(value);
}
/*------------------------------------------------------------------------*/
/**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/
var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
assignValue(object, key, source[key]);
}
}
});
/**
* This method is like `_.assign` except that it iterates over own and
* inherited source properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assign
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assignIn({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
*/
var assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
});
/**
* This method is like `_.assignIn` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias extendWith
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignInWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
});
/**
* This method is like `_.assign` except that it accepts `customizer`
* which is invoked to produce the assigned values. If `customizer` returns
* `undefined`, assignment is handled by the method instead. The `customizer`
* is invoked with five arguments: (objValue, srcValue, key, object, source).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @see _.assignInWith
* @example
*
* function customizer(objValue, srcValue) {
* return _.isUndefined(objValue) ? srcValue : objValue;
* }
*
* var defaults = _.partialRight(_.assignWith, customizer);
*
* defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keys(source), object, customizer);
});
/**
* Creates an array of values corresponding to `paths` of `object`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Array} Returns the picked values.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _.at(object, ['a[0].b.c', 'a[1]']);
* // => [3, 4]
*/
var at = flatRest(baseAt);
/**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties) {
var result = baseCreate(prototype);
return properties == null ? result : baseAssign(result, properties);
}
/**
* Assigns own and inherited enumerable string keyed properties of source
* objects to the destination object for all destination properties that
* resolve to `undefined`. Source objects are applied from left to right.
* Once a property is set, additional values of the same property are ignored.
*
* **Note:** This method mutates `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaultsDeep
* @example
*
* _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
* // => { 'a': 1, 'b': 2 }
*/
var defaults = baseRest(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : undefined;
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === undefined ||
(eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
object[key] = source[key];
}
}
}
return object;
});
/**
* This method is like `_.defaults` except that it recursively assigns
* default properties.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.defaults
* @example
*
* _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
* // => { 'a': { 'b': 2, 'c': 3 } }
*/
var defaultsDeep = baseRest(function(args) {
args.push(undefined, customDefaultsMerge);
return apply(mergeWith, undefined, args);
});
/**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/
function findKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
}
/**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/
function findLastKey(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
}
/**
* Iterates over own and inherited 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 _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/
function forIn(object, iteratee) {
return object == null
? object
: baseFor(object, getIteratee(iteratee, 3), keysIn);
}
/**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.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 _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
*/
function forInRight(object, iteratee) {
return object == null
? object
: baseForRight(object, getIteratee(iteratee, 3), keysIn);
}
/**
* 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, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.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 _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
*/
function forOwnRight(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}
/**
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
*/
function functions(object) {
return object == null ? [] : baseFunctions(object, keys(object));
}
/**
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
*/
function functionsIn(object) {
return object == null ? [] : baseFunctions(object, keysIn(object));
}
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned 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;
}
/**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @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 = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/
function has(object, path) {
return object != null && hasPath(object, path, baseHas);
}
/**
* 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);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/
var invert = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
result[value] = key;
}, constant(identity));
/**
* This method is like `_.invert` except that the inverted object is generated
* from the results of running each element of `object` thru `iteratee`. The
* corresponding inverted value of each inverted key is an array of keys
* responsible for generating the inverted value. The iteratee is invoked
* with one argument: (value).
*
* @static
* @memberOf _
* @since 4.1.0
* @category Object
* @param {Object} object The object to invert.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invertBy(object);
* // => { '1': ['a', 'c'], '2': ['b'] }
*
* _.invertBy(object, function(value) {
* return 'group' + value;
* });
* // => { 'group1': ['a', 'c'], 'group2': ['b'] }
*/
var invertBy = createInverter(function(result, value, key) {
if (value != null &&
typeof value.toString != 'function') {
value = nativeObjectToString.call(value);
}
if (hasOwnProperty.call(result, value)) {
result[value].push(key);
} else {
result[value] = [key];
}
}, getIteratee);
/**
* Invokes the method at `path` of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
* @example
*
* var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
*
* _.invoke(object, 'a[0].b.c.slice', 1, 3);
* // => [2, 3]
*/
var invoke = baseRest(baseInvoke);
/**
* 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/7.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) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @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;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
}
/**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/
function mapKeys(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
});
return result;
}
/**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/
function mapValues(object, iteratee) {
var result = {};
iteratee = getIteratee(iteratee, 3);
baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
});
return result;
}
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/
var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
});
/**
* This method is like `_.merge` except that it accepts `customizer` which
* is invoked to produce the merged values of the destination and source
* properties. If `customizer` returns `undefined`, merging is handled by the
* method instead. The `customizer` is invoked with six arguments:
* (objValue, srcValue, key, object, source, stack).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} sources The source objects.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* function customizer(objValue, srcValue) {
* if (_.isArray(objValue)) {
* return objValue.concat(srcValue);
* }
* }
*
* var object = { 'a': [1], 'b': [2] };
* var other = { 'a': [3], 'b': [4] };
*
* _.mergeWith(object, other, customizer);
* // => { 'a': [1, 3], 'b': [2, 4] }
*/
var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
});
/**
* The opposite of `_.pick`; this method creates an object composed of the
* own and inherited enumerable property paths of `object` that are not omitted.
*
* **Note:** This method is considerably slower than `_.pick`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to omit.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omit(object, ['a', 'c']);
* // => { 'b': '2' }
*/
var omit = flatRest(function(object, paths) {
var result = {};
if (object == null) {
return result;
}
var isDeep = false;
paths = arrayMap(paths, function(path) {
path = castPath(path, object);
isDeep || (isDeep = path.length > 1);
return path;
});
copyObject(object, getAllKeysIn(object), result);
if (isDeep) {
result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
}
var length = paths.length;
while (length--) {
baseUnset(result, paths[length]);
}
return result;
});
/**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return truthy for. The predicate is invoked with two
* arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/
function omitBy(object, predicate) {
return pickBy(object, negate(getIteratee(predicate)));
}
/**
* Creates an object composed of the picked `object` properties.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The source object.
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pick(object, ['a', 'c']);
* // => { 'a': 1, 'c': 3 }
*/
var pick = flatRest(function(object, paths) {
return object == null ? {} : basePick(object, paths);
});
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [prop];
});
predicate = getIteratee(predicate);
return basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
/**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/
function result(object, path, defaultValue) {
path = castPath(path, object);
var index = -1,
length = path.length;
// Ensure the loop is entered when path is empty.
if (!length) {
length = 1;
object = undefined;
}
while (++index < length) {
var value = object == null ? undefined : object[toKey(path[index])];
if (value === undefined) {
index = length;
value = defaultValue;
}
object = isFunction(value) ? value.call(object) : value;
}
return object;
}
/**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/
function set(object, path, value) {
return object == null ? object : baseSet(object, path, value);
}
/**
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
*/
function setWith(object, path, value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseSet(object, path, value, customizer);
}
/**
* 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);
/**
* Creates an array of own and inherited 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 entriesIn
* @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;
*
* _.toPairsIn(new Foo);
* // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
*/
var toPairsIn = createToPairs(keysIn);
/**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/
function transform(object, iteratee, accumulator) {
var isArr = isArray(object),
isArrLike = isArr || isBuffer(object) || isTypedArray(object);
iteratee = getIteratee(iteratee, 4);
if (accumulator == null) {
var Ctor = object && object.constructor;
if (isArrLike) {
accumulator = isArr ? new Ctor : [];
}
else if (isObject(object)) {
accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
else {
accumulator = {};
}
}
(isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
});
return accumulator;
}
/**
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*/
function unset(object, path) {
return object == null ? true : baseUnset(object, path);
}
/**
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
*/
function update(object, path, updater) {
return object == null ? object : baseUpdate(object, path, castFunction(updater));
}
/**
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
*/
function updateWith(object, path, updater, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
}
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/
function values(object) {
return object == null ? [] : baseValues(object, keys(object));
}
/**
* Creates an array of the own and inherited enumerable string keyed property
* values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/
function valuesIn(object) {
return object == null ? [] : baseValues(object, keysIn(object));
}
/*------------------------------------------------------------------------*/
/**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
*/
function clamp(number, lower, upper) {
if (upper === undefined) {
upper = lower;
lower = undefined;
}
if (upper !== undefined) {
upper = toNumber(upper);
upper = upper === upper ? upper : 0;
}
if (lower !== undefined) {
lower = toNumber(lower);
lower = lower === lower ? lower : 0;
}
return baseClamp(toNumber(number), lower, upper);
}
/**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/
function inRange(number, start, end) {
start = toFinite(start);
if (end === undefined) {
end = start;
start = 0;
} else {
end = toFinite(end);
}
number = toNumber(number);
return baseInRange(number, start, end);
}
/**
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/
function random(lower, upper, floating) {
if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
upper = floating = undefined;
}
if (floating === undefined) {
if (typeof upper == 'boolean') {
floating = upper;
upper = undefined;
}
else if (typeof lower == 'boolean') {
floating = lower;
lower = undefined;
}
}
if (lower === undefined && upper === undefined) {
lower = 0;
upper = 1;
}
else {
lower = toFinite(lower);
if (upper === undefined) {
upper = lower;
lower = 0;
} else {
upper = toFinite(upper);
}
}
if (lower > upper) {
var temp = lower;
lower = upper;
upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
}
return baseRandom(lower, upper);
}
/*------------------------------------------------------------------------*/
/**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/
var camelCase = createCompounder(function(result, word, index) {
word = word.toLowerCase();
return result + (index ? capitalize(word) : word);
});
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/
function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/
function deburr(string) {
string = toString(string);
return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
/**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/
function endsWith(string, target, position) {
string = toString(string);
target = baseToString(target);
var length = string.length;
position = position === undefined
? length
: baseClamp(toInteger(position), 0, length);
var end = position;
position -= target.length;
return position >= 0 && string.slice(position, end) == target;
}
/**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function escape(string) {
string = toString(string);
return (string && reHasUnescapedHtml.test(string))
? string.replace(reUnescapedHtml, escapeHtmlChar)
: string;
}
/**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/
function escapeRegExp(string) {
string = toString(string);
return (string && reHasRegExpChar.test(string))
? string.replace(reRegExpChar, '\\$&')
: string;
}
/**
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
*/
var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
});
/**
* Converts `string`, as space separated words, to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.lowerCase('--Foo-Bar--');
* // => 'foo bar'
*
* _.lowerCase('fooBar');
* // => 'foo bar'
*
* _.lowerCase('__FOO_BAR__');
* // => 'foo bar'
*/
var lowerCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toLowerCase();
});
/**
* Converts the first character of `string` to lower case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.lowerFirst('Fred');
* // => 'fred'
*
* _.lowerFirst('FRED');
* // => 'fRED'
*/
var lowerFirst = createCaseFirst('toLowerCase');
/**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/
function pad(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
if (!length || strLength >= length) {
return string;
}
var mid = (length - strLength) / 2;
return (
createPadding(nativeFloor(mid), chars) +
string +
createPadding(nativeCeil(mid), chars)
);
}
/**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/
function padEnd(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (string + createPadding(length - strLength, chars))
: string;
}
/**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
*/
function padStart(string, length, chars) {
string = toString(string);
length = toInteger(length);
var strLength = length ? stringSize(string) : 0;
return (length && strLength < length)
? (createPadding(length - strLength, chars) + string)
: string;
}
/**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/
function parseInt(string, radix, guard) {
if (guard || radix == null) {
radix = 0;
} else if (radix) {
radix = +radix;
}
return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
}
/**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/
function repeat(string, n, guard) {
if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
n = 1;
} else {
n = toInteger(n);
}
return baseRepeat(toString(string), n);
}
/**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/
function replace() {
var args = arguments,
string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}
/**
* Converts `string` to
* [snake case](https://en.wikipedia.org/wiki/Snake_case).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the snake cased string.
* @example
*
* _.snakeCase('Foo Bar');
* // => 'foo_bar'
*
* _.snakeCase('fooBar');
* // => 'foo_bar'
*
* _.snakeCase('--FOO-BAR--');
* // => 'foo_bar'
*/
var snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
});
/**
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
*/
function split(string, separator, limit) {
if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
separator = limit = undefined;
}
limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
if (!limit) {
return [];
}
string = toString(string);
if (string && (
typeof separator == 'string' ||
(separator != null && !isRegExp(separator))
)) {
separator = baseToString(separator);
if (!separator && hasUnicode(string)) {
return castSlice(stringToArray(string), 0, limit);
}
}
return string.split(separator, limit);
}
/**
* Converts `string` to
* [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
*
* @static
* @memberOf _
* @since 3.1.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the start cased string.
* @example
*
* _.startCase('--foo-bar--');
* // => 'Foo Bar'
*
* _.startCase('fooBar');
* // => 'Foo Bar'
*
* _.startCase('__FOO_BAR__');
* // => 'FOO BAR'
*/
var startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
});
/**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/
function startsWith(string, target, position) {
string = toString(string);
position = position == null
? 0
: baseClamp(toInteger(position), 0, string.length);
target = baseToString(target);
return string.slice(position, position + target.length) == target;
}
/**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/
function template(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
if (guard && isIterateeCall(string, options, guard)) {
options = undefined;
}
string = toString(string);
options = assignInWith({}, options, settings, customDefaultsAssignIn);
var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
importsKeys = keys(imports),
importsValues = baseValues(imports, importsKeys);
var isEscaping,
isEvaluating,
index = 0,
interpolate = options.interpolate || reNoMatch,
source = "__p += '";
// Compile the regexp to match each delimiter.
var reDelimiters = RegExp(
(options.escape || reNoMatch).source + '|' +
interpolate.source + '|' +
(interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
(options.evaluate || reNoMatch).source + '|$'
, 'g');
// Use a sourceURL for easier debugging.
// The sourceURL gets injected into the source that's eval-ed, so be careful
// to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
// and escape the comment, thus injecting code that gets evaled.
var sourceURL = '//# sourceURL=' +
(hasOwnProperty.call(options, 'sourceURL')
? (options.sourceURL + '').replace(/\s/g, ' ')
: ('lodash.templateSources[' + (++templateCounter) + ']')
) + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
interpolateValue || (interpolateValue = esTemplateValue);
// Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
// Replace delimiters with snippets.
if (escapeValue) {
isEscaping = true;
source += "' +\n__e(" + escapeValue + ") +\n'";
}
if (evaluateValue) {
isEvaluating = true;
source += "';\n" + evaluateValue + ";\n__p += '";
}
if (interpolateValue) {
source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
}
index = offset + match.length;
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return match;
});
source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (!variable) {
source = 'with (obj) {\n' + source + '\n}\n';
}
// Throw an error if a forbidden character was found in `variable`, to prevent
// potential command injection attacks.
else if (reForbiddenIdentifierChars.test(variable)) {
throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT);
}
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
.replace(reEmptyStringMiddle, '$1')
.replace(reEmptyStringTrailing, '$1;');
// Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' +
(variable
? ''
: 'obj || (obj = {});\n'
) +
"var __t, __p = ''" +
(isEscaping
? ', __e = _.escape'
: ''
) +
(isEvaluating
? ', __j = Array.prototype.join;\n' +
"function print() { __p += __j.call(arguments, '') }\n"
: ';\n'
) +
source +
'return __p\n}';
var result = attempt(function() {
return Function(importsKeys, sourceURL + 'return ' + source)
.apply(undefined, importsValues);
});
// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source;
if (isError(result)) {
throw result;
}
return result;
}
/**
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
*/
function toLower(value) {
return toString(value).toLowerCase();
}
/**
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
*/
function toUpper(value) {
return toString(value).toUpperCase();
}
/**
* 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 baseTrim(string);
}
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('');
}
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.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
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.slice(0, trimmedEndIndex(string) + 1);
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.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
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}
/**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/
function truncate(string, options) {
var length = DEFAULT_TRUNC_LENGTH,
omission = DEFAULT_TRUNC_OMISSION;
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length;
omission = 'omission' in options ? baseToString(options.omission) : omission;
}
string = toString(string);
var strLength = string.length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) {
return string;
}
var end = length - stringSize(omission);
if (end < 1) {
return omission;
}
var result = strSymbols
? castSlice(strSymbols, 0, end).join('')
: string.slice(0, end);
if (separator === undefined) {
return result + omission;
}
if (strSymbols) {
end += (result.length - end);
}
if (isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match,
substring = result;
if (!separator.global) {
separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
}
separator.lastIndex = 0;
while ((match = separator.exec(substring))) {
var newEnd = match.index;
}
result = result.slice(0, newEnd === undefined ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
if (index > -1) {
result = result.slice(0, index);
}
}
return result + omission;
}
/**
* The inverse of `_.escape`; this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/
function unescape(string) {
string = toString(string);
return (string && reHasEscapedHtml.test(string))
? string.replace(reEscapedHtml, unescapeHtmlChar)
: string;
}
/**
* Converts `string`, as space separated words, to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.upperCase('--foo-bar');
* // => 'FOO BAR'
*
* _.upperCase('fooBar');
* // => 'FOO BAR'
*
* _.upperCase('__foo_bar__');
* // => 'FOO BAR'
*/
var upperCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toUpperCase();
});
/**
* Converts the first character of `string` to upper case.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.upperFirst('fred');
* // => 'Fred'
*
* _.upperFirst('FRED');
* // => 'FRED'
*/
var upperFirst = createCaseFirst('toUpperCase');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/
function words(string, pattern, guard) {
string = toString(string);
pattern = guard ? undefined : pattern;
if (pattern === undefined) {
return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
}
return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/
/**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/
var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
});
/**
* Binds methods of an object to the object itself, overwriting the existing
* method.
*
* **Note:** This method doesn't set the "length" property of bound functions.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Object} object The object to bind and assign the bound methods to.
* @param {...(string|string[])} methodNames The object method names to bind.
* @returns {Object} Returns `object`.
* @example
*
* var view = {
* 'label': 'docs',
* 'click': function() {
* console.log('clicked ' + this.label);
* }
* };
*
* _.bindAll(view, ['click']);
* jQuery(element).on('click', view.click);
* // => Logs 'clicked docs' when clicked.
*/
var bindAll = flatRest(function(object, methodNames) {
arrayEach(methodNames, function(key) {
key = toKey(key);
baseAssignValue(object, key, bind(object[key], object));
});
return object;
});
/**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/
function cond(pairs) {
var length = pairs == null ? 0 : pairs.length,
toIteratee = getIteratee();
pairs = !length ? [] : arrayMap(pairs, function(pair) {
if (typeof pair[1] != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
return [toIteratee(pair[0]), pair[1]];
});
return baseRest(function(args) {
var index = -1;
while (++index < length) {
var pair = pairs[index];
if (apply(pair[0], this, args)) {
return apply(pair[1], this, args);
}
}
});
}
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/
function constant(value) {
return function() {
return value;
};
}
/**
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
*/
function defaultTo(value, defaultValue) {
return (value == null || value !== value) ? defaultValue : value;
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
*/
var flow = createFlow();
/**
* This method is like `_.flow` except that it creates a function that
* invokes the given functions from right to left.
*
* @static
* @since 3.0.0
* @memberOf _
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flow
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flowRight([square, _.add]);
* addSquare(1, 2);
* // => 9
*/
var flowRight = createFlow(true);
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/
function identity(value) {
return value;
}
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/
function iteratee(func) {
return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matches(source) {
return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
}
/**
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/
function matchesProperty(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
}
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/
var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
});
/**
* The opposite of `_.method`; this method creates a function that invokes
* the method at a given path of `object`. Any additional arguments are
* provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Object} object The object to query.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var array = _.times(3, _.constant),
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.methodOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.methodOf(object));
* // => [2, 0]
*/
var methodOf = baseRest(function(object, args) {
return function(path) {
return baseInvoke(object, path, args);
};
});
/**
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/
function mixin(object, source, options) {
var props = keys(source),
methodNames = baseFunctions(source, props);
if (options == null &&
!(isObject(source) && (methodNames.length || !props.length))) {
options = source;
source = object;
object = this;
methodNames = baseFunctions(source, keys(source));
}
var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
isFunc = isFunction(object);
arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func;
if (isFunc) {
object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__),
actions = result.__actions__ = copyArray(this.__actions__);
actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
result.__chain__ = chainAll;
return result;
}
return func.apply(object, arrayPush([this.value()], arguments));
};
}
});
return object;
}
/**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/
function noConflict() {
if (root._ === this) {
root._ = oldDash;
}
return this;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
/**
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
*/
function nthArg(n) {
n = toInteger(n);
return baseRest(function(args) {
return baseNth(args, n);
});
}
/**
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
*/
var over = createOver(arrayMap);
/**
* Creates a function that checks if **all** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overEvery([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => false
*
* func(NaN);
* // => false
*/
var overEvery = createOver(arrayEvery);
/**
* Creates a function that checks if **any** of the `predicates` return
* truthy when invoked with the arguments it receives.
*
* Following shorthands are possible for providing predicates.
* Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
* Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [predicates=[_.identity]]
* The predicates to check.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.overSome([Boolean, isFinite]);
*
* func('1');
* // => true
*
* func(null);
* // => true
*
* func(NaN);
* // => false
*
* var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
* var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
*/
var overSome = createOver(arraySome);
/**
* 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 opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
*/
function propertyOf(object) {
return function(path) {
return object == null ? undefined : baseGet(object, path);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/
var range = createRange();
/**
* This method is like `_.range` except that it populates values in
* descending order.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.range
* @example
*
* _.rangeRight(4);
* // => [3, 2, 1, 0]
*
* _.rangeRight(-4);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 5);
* // => [4, 3, 2, 1]
*
* _.rangeRight(0, 20, 5);
* // => [15, 10, 5, 0]
*
* _.rangeRight(0, -4, -1);
* // => [-3, -2, -1, 0]
*
* _.rangeRight(1, 4, 0);
* // => [1, 1, 1]
*
* _.rangeRight(0);
* // => []
*/
var rangeRight = createRange(true);
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/
function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/
function stubFalse() {
return false;
}
/**
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
*/
function stubObject() {
return {};
}
/**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/
function stubString() {
return '';
}
/**
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
*/
function stubTrue() {
return true;
}
/**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/
function times(n, iteratee) {
n = toInteger(n);
if (n < 1 || n > MAX_SAFE_INTEGER) {
return [];
}
var index = MAX_ARRAY_LENGTH,
length = nativeMin(n, MAX_ARRAY_LENGTH);
iteratee = getIteratee(iteratee);
n -= MAX_ARRAY_LENGTH;
var result = baseTimes(length, iteratee);
while (++index < n) {
iteratee(index);
}
return result;
}
/**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/
function toPath(value) {
if (isArray(value)) {
return arrayMap(value, toKey);
}
return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
}
/**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/
function uniqueId(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}
/*------------------------------------------------------------------------*/
/**
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/
var add = createMathOperation(function(augend, addend) {
return augend + addend;
}, 0);
/**
* Computes `number` rounded up to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round up.
* @param {number} [precision=0] The precision to round up to.
* @returns {number} Returns the rounded up number.
* @example
*
* _.ceil(4.006);
* // => 5
*
* _.ceil(6.004, 2);
* // => 6.01
*
* _.ceil(6040, -2);
* // => 6100
*/
var ceil = createRound('ceil');
/**
* Divide two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} dividend The first number in a division.
* @param {number} divisor The second number in a division.
* @returns {number} Returns the quotient.
* @example
*
* _.divide(6, 4);
* // => 1.5
*/
var divide = createMathOperation(function(dividend, divisor) {
return dividend / divisor;
}, 1);
/**
* Computes `number` rounded down to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round down.
* @param {number} [precision=0] The precision to round down to.
* @returns {number} Returns the rounded down number.
* @example
*
* _.floor(4.006);
* // => 4
*
* _.floor(0.046, 2);
* // => 0.04
*
* _.floor(4060, -2);
* // => 4000
*/
var floor = createRound('floor');
/**
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
*/
function max(array) {
return (array && array.length)
? baseExtremum(array, identity, baseGt)
: undefined;
}
/**
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
*/
function maxBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
: undefined;
}
/**
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
*/
function mean(array) {
return baseMean(array, identity);
}
/**
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
*/
function meanBy(array, iteratee) {
return baseMean(array, getIteratee(iteratee, 2));
}
/**
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
*/
function min(array) {
return (array && array.length)
? baseExtremum(array, identity, baseLt)
: undefined;
}
/**
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
*/
function minBy(array, iteratee) {
return (array && array.length)
? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
: undefined;
}
/**
* Multiply two numbers.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {number} multiplier The first number in a multiplication.
* @param {number} multiplicand The second number in a multiplication.
* @returns {number} Returns the product.
* @example
*
* _.multiply(6, 4);
* // => 24
*/
var multiply = createMathOperation(function(multiplier, multiplicand) {
return multiplier * multiplicand;
}, 1);
/**
* Computes `number` rounded to `precision`.
*
* @static
* @memberOf _
* @since 3.10.0
* @category Math
* @param {number} number The number to round.
* @param {number} [precision=0] The precision to round to.
* @returns {number} Returns the rounded number.
* @example
*
* _.round(4.006);
* // => 4
*
* _.round(4.006, 2);
* // => 4.01
*
* _.round(4060, -2);
* // => 4100
*/
var round = createRound('round');
/**
* Subtract two numbers.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {number} minuend The first number in a subtraction.
* @param {number} subtrahend The second number in a subtraction.
* @returns {number} Returns the difference.
* @example
*
* _.subtract(6, 4);
* // => 2
*/
var subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
/**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/
function sum(array) {
return (array && array.length)
? baseSum(array, identity)
: 0;
}
/**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/
function sumBy(array, iteratee) {
return (array && array.length)
? baseSum(array, getIteratee(iteratee, 2))
: 0;
}
/*------------------------------------------------------------------------*/
// Add methods that return wrapped values in chain sequences.
lodash.after = after;
lodash.ary = ary;
lodash.assign = assign;
lodash.assignIn = assignIn;
lodash.assignInWith = assignInWith;
lodash.assignWith = assignWith;
lodash.at = at;
lodash.before = before;
lodash.bind = bind;
lodash.bindAll = bindAll;
lodash.bindKey = bindKey;
lodash.castArray = castArray;
lodash.chain = chain;
lodash.chunk = chunk;
lodash.compact = compact;
lodash.concat = concat;
lodash.cond = cond;
lodash.conforms = conforms;
lodash.constant = constant;
lodash.countBy = countBy;
lodash.create = create;
lodash.curry = curry;
lodash.curryRight = curryRight;
lodash.debounce = debounce;
lodash.defaults = defaults;
lodash.defaultsDeep = defaultsDeep;
lodash.defer = defer;
lodash.delay = delay;
lodash.difference = difference;
lodash.differenceBy = differenceBy;
lodash.differenceWith = differenceWith;
lodash.drop = drop;
lodash.dropRight = dropRight;
lodash.dropRightWhile = dropRightWhile;
lodash.dropWhile = dropWhile;
lodash.fill = fill;
lodash.filter = filter;
lodash.flatMap = flatMap;
lodash.flatMapDeep = flatMapDeep;
lodash.flatMapDepth = flatMapDepth;
lodash.flatten = flatten;
lodash.flattenDeep = flattenDeep;
lodash.flattenDepth = flattenDepth;
lodash.flip = flip;
lodash.flow = flow;
lodash.flowRight = flowRight;
lodash.fromPairs = fromPairs;
lodash.functions = functions;
lodash.functionsIn = functionsIn;
lodash.groupBy = groupBy;
lodash.initial = initial;
lodash.intersection = intersection;
lodash.intersectionBy = intersectionBy;
lodash.intersectionWith = intersectionWith;
lodash.invert = invert;
lodash.invertBy = invertBy;
lodash.invokeMap = invokeMap;
lodash.iteratee = iteratee;
lodash.keyBy = keyBy;
lodash.keys = keys;
lodash.keysIn = keysIn;
lodash.map = map;
lodash.mapKeys = mapKeys;
lodash.mapValues = mapValues;
lodash.matches = matches;
lodash.matchesProperty = matchesProperty;
lodash.memoize = memoize;
lodash.merge = merge;
lodash.mergeWith = mergeWith;
lodash.method = method;
lodash.methodOf = methodOf;
lodash.mixin = mixin;
lodash.negate = negate;
lodash.nthArg = nthArg;
lodash.omit = omit;
lodash.omitBy = omitBy;
lodash.once = once;
lodash.orderBy = orderBy;
lodash.over = over;
lodash.overArgs = overArgs;
lodash.overEvery = overEvery;
lodash.overSome = overSome;
lodash.partial = partial;
lodash.partialRight = partialRight;
lodash.partition = partition;
lodash.pick = pick;
lodash.pickBy = pickBy;
lodash.property = property;
lodash.propertyOf = propertyOf;
lodash.pull = pull;
lodash.pullAll = pullAll;
lodash.pullAllBy = pullAllBy;
lodash.pullAllWith = pullAllWith;
lodash.pullAt = pullAt;
lodash.range = range;
lodash.rangeRight = rangeRight;
lodash.rearg = rearg;
lodash.reject = reject;
lodash.remove = remove;
lodash.rest = rest;
lodash.reverse = reverse;
lodash.sampleSize = sampleSize;
lodash.set = set;
lodash.setWith = setWith;
lodash.shuffle = shuffle;
lodash.slice = slice;
lodash.sortBy = sortBy;
lodash.sortedUniq = sortedUniq;
lodash.sortedUniqBy = sortedUniqBy;
lodash.split = split;
lodash.spread = spread;
lodash.tail = tail;
lodash.take = take;
lodash.takeRight = takeRight;
lodash.takeRightWhile = takeRightWhile;
lodash.takeWhile = takeWhile;
lodash.tap = tap;
lodash.throttle = throttle;
lodash.thru = thru;
lodash.toArray = toArray;
lodash.toPairs = toPairs;
lodash.toPairsIn = toPairsIn;
lodash.toPath = toPath;
lodash.toPlainObject = toPlainObject;
lodash.transform = transform;
lodash.unary = unary;
lodash.union = union;
lodash.unionBy = unionBy;
lodash.unionWith = unionWith;
lodash.uniq = uniq;
lodash.uniqBy = uniqBy;
lodash.uniqWith = uniqWith;
lodash.unset = unset;
lodash.unzip = unzip;
lodash.unzipWith = unzipWith;
lodash.update = update;
lodash.updateWith = updateWith;
lodash.values = values;
lodash.valuesIn = valuesIn;
lodash.without = without;
lodash.words = words;
lodash.wrap = wrap;
lodash.xor = xor;
lodash.xorBy = xorBy;
lodash.xorWith = xorWith;
lodash.zip = zip;
lodash.zipObject = zipObject;
lodash.zipObjectDeep = zipObjectDeep;
lodash.zipWith = zipWith;
// Add aliases.
lodash.entries = toPairs;
lodash.entriesIn = toPairsIn;
lodash.extend = assignIn;
lodash.extendWith = assignInWith;
// Add methods to `lodash.prototype`.
mixin(lodash, lodash);
/*------------------------------------------------------------------------*/
// Add methods that return unwrapped values in chain sequences.
lodash.add = add;
lodash.attempt = attempt;
lodash.camelCase = camelCase;
lodash.capitalize = capitalize;
lodash.ceil = ceil;
lodash.clamp = clamp;
lodash.clone = clone;
lodash.cloneDeep = cloneDeep;
lodash.cloneDeepWith = cloneDeepWith;
lodash.cloneWith = cloneWith;
lodash.conformsTo = conformsTo;
lodash.deburr = deburr;
lodash.defaultTo = defaultTo;
lodash.divide = divide;
lodash.endsWith = endsWith;
lodash.eq = eq;
lodash.escape = escape;
lodash.escapeRegExp = escapeRegExp;
lodash.every = every;
lodash.find = find;
lodash.findIndex = findIndex;
lodash.findKey = findKey;
lodash.findLast = findLast;
lodash.findLastIndex = findLastIndex;
lodash.findLastKey = findLastKey;
lodash.floor = floor;
lodash.forEach = forEach;
lodash.forEachRight = forEachRight;
lodash.forIn = forIn;
lodash.forInRight = forInRight;
lodash.forOwn = forOwn;
lodash.forOwnRight = forOwnRight;
lodash.get = get;
lodash.gt = gt;
lodash.gte = gte;
lodash.has = has;
lodash.hasIn = hasIn;
lodash.head = head;
lodash.identity = identity;
lodash.includes = includes;
lodash.indexOf = indexOf;
lodash.inRange = inRange;
lodash.invoke = invoke;
lodash.isArguments = isArguments;
lodash.isArray = isArray;
lodash.isArrayBuffer = isArrayBuffer;
lodash.isArrayLike = isArrayLike;
lodash.isArrayLikeObject = isArrayLikeObject;
lodash.isBoolean = isBoolean;
lodash.isBuffer = isBuffer;
lodash.isDate = isDate;
lodash.isElement = isElement;
lodash.isEmpty = isEmpty;
lodash.isEqual = isEqual;
lodash.isEqualWith = isEqualWith;
lodash.isError = isError;
lodash.isFinite = isFinite;
lodash.isFunction = isFunction;
lodash.isInteger = isInteger;
lodash.isLength = isLength;
lodash.isMap = isMap;
lodash.isMatch = isMatch;
lodash.isMatchWith = isMatchWith;
lodash.isNaN = isNaN;
lodash.isNative = isNative;
lodash.isNil = isNil;
lodash.isNull = isNull;
lodash.isNumber = isNumber;
lodash.isObject = isObject;
lodash.isObjectLike = isObjectLike;
lodash.isPlainObject = isPlainObject;
lodash.isRegExp = isRegExp;
lodash.isSafeInteger = isSafeInteger;
lodash.isSet = isSet;
lodash.isString = isString;
lodash.isSymbol = isSymbol;
lodash.isTypedArray = isTypedArray;
lodash.isUndefined = isUndefined;
lodash.isWeakMap = isWeakMap;
lodash.isWeakSet = isWeakSet;
lodash.join = join;
lodash.kebabCase = kebabCase;
lodash.last = last;
lodash.lastIndexOf = lastIndexOf;
lodash.lowerCase = lowerCase;
lodash.lowerFirst = lowerFirst;
lodash.lt = lt;
lodash.lte = lte;
lodash.max = max;
lodash.maxBy = maxBy;
lodash.mean = mean;
lodash.meanBy = meanBy;
lodash.min = min;
lodash.minBy = minBy;
lodash.stubArray = stubArray;
lodash.stubFalse = stubFalse;
lodash.stubObject = stubObject;
lodash.stubString = stubString;
lodash.stubTrue = stubTrue;
lodash.multiply = multiply;
lodash.nth = nth;
lodash.noConflict = noConflict;
lodash.noop = noop;
lodash.now = now;
lodash.pad = pad;
lodash.padEnd = padEnd;
lodash.padStart = padStart;
lodash.parseInt = parseInt;
lodash.random = random;
lodash.reduce = reduce;
lodash.reduceRight = reduceRight;
lodash.repeat = repeat;
lodash.replace = replace;
lodash.result = result;
lodash.round = round;
lodash.runInContext = runInContext;
lodash.sample = sample;
lodash.size = size;
lodash.snakeCase = snakeCase;
lodash.some = some;
lodash.sortedIndex = sortedIndex;
lodash.sortedIndexBy = sortedIndexBy;
lodash.sortedIndexOf = sortedIndexOf;
lodash.sortedLastIndex = sortedLastIndex;
lodash.sortedLastIndexBy = sortedLastIndexBy;
lodash.sortedLastIndexOf = sortedLastIndexOf;
lodash.startCase = startCase;
lodash.startsWith = startsWith;
lodash.subtract = subtract;
lodash.sum = sum;
lodash.sumBy = sumBy;
lodash.template = template;
lodash.times = times;
lodash.toFinite = toFinite;
lodash.toInteger = toInteger;
lodash.toLength = toLength;
lodash.toLower = toLower;
lodash.toNumber = toNumber;
lodash.toSafeInteger = toSafeInteger;
lodash.toString = toString;
lodash.toUpper = toUpper;
lodash.trim = trim;
lodash.trimEnd = trimEnd;
lodash.trimStart = trimStart;
lodash.truncate = truncate;
lodash.unescape = unescape;
lodash.uniqueId = uniqueId;
lodash.upperCase = upperCase;
lodash.upperFirst = upperFirst;
// Add aliases.
lodash.each = forEach;
lodash.eachRight = forEachRight;
lodash.first = head;
mixin(lodash, (function() {
var source = {};
baseForOwn(lodash, function(func, methodName) {
if (!hasOwnProperty.call(lodash.prototype, methodName)) {
source[methodName] = func;
}
});
return source;
}()), { 'chain': false });
/*------------------------------------------------------------------------*/
/**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/
lodash.VERSION = VERSION;
// Assign default placeholders.
arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
lodash[methodName].placeholder = lodash;
});
// Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach(['drop', 'take'], function(methodName, index) {
LazyWrapper.prototype[methodName] = function(n) {
n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
var result = (this.__filtered__ && !index)
? new LazyWrapper(this)
: this.clone();
if (result.__filtered__) {
result.__takeCount__ = nativeMin(n, result.__takeCount__);
} else {
result.__views__.push({
'size': nativeMin(n, MAX_ARRAY_LENGTH),
'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
});
}
return result;
};
LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
});
// Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
var type = index + 1,
isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
result.__iteratees__.push({
'iteratee': getIteratee(iteratee, 3),
'type': type
});
result.__filtered__ = result.__filtered__ || isFilter;
return result;
};
});
// Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach(['head', 'last'], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
});
// Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach(['initial', 'tail'], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
};
});
LazyWrapper.prototype.compact = function() {
return this.filter(identity);
};
LazyWrapper.prototype.find = function(predicate) {
return this.filter(predicate).head();
};
LazyWrapper.prototype.findLast = function(predicate) {
return this.reverse().find(predicate);
};
LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
if (typeof path == 'function') {
return new LazyWrapper(this);
}
return this.map(function(value) {
return baseInvoke(value, path, args);
});
});
LazyWrapper.prototype.reject = function(predicate) {
return this.filter(negate(getIteratee(predicate)));
};
LazyWrapper.prototype.slice = function(start, end) {
start = toInteger(start);
var result = this;
if (result.__filtered__ && (start > 0 || end < 0)) {
return new LazyWrapper(result);
}
if (start < 0) {
result = result.takeRight(-start);
} else if (start) {
result = result.drop(start);
}
if (end !== undefined) {
end = toInteger(end);
result = end < 0 ? result.dropRight(-end) : result.take(end - start);
}
return result;
};
LazyWrapper.prototype.takeRightWhile = function(predicate) {
return this.reverse().takeWhile(predicate).reverse();
};
LazyWrapper.prototype.toArray = function() {
return this.take(MAX_ARRAY_LENGTH);
};
// Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
isTaker = /^(?:head|last)$/.test(methodName),
lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
retUnwrapped = isTaker || /^find/.test(methodName);
if (!lodashFunc) {
return;
}
lodash.prototype[methodName] = function() {
var value = this.__wrapped__,
args = isTaker ? [1] : arguments,
isLazy = value instanceof LazyWrapper,
iteratee = args[0],
useLazy = isLazy || isArray(value);
var interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([value], args));
return (isTaker && chainAll) ? result[0] : result;
};
if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
// Avoid lazy use if the iteratee has a "length" value other than `1`.
isLazy = useLazy = false;
}
var chainAll = this.__chain__,
isHybrid = !!this.__actions__.length,
isUnwrapped = retUnwrapped && !chainAll,
onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
return new LodashWrapper(result, chainAll);
}
if (isUnwrapped && onlyLazy) {
return func.apply(this, args);
}
result = this.thru(interceptor);
return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
};
});
// Add `Array` methods to `lodash.prototype`.
arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
var func = arrayProto[methodName],
chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
};
});
// Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name + '';
if (!hasOwnProperty.call(realNames, key)) {
realNames[key] = [];
}
realNames[key].push({ 'name': methodName, 'func': lodashFunc });
}
});
realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
'name': 'wrapper',
'func': undefined
}];
// Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone = lazyClone;
LazyWrapper.prototype.reverse = lazyReverse;
LazyWrapper.prototype.value = lazyValue;
// Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at = wrapperAt;
lodash.prototype.chain = wrapperChain;
lodash.prototype.commit = wrapperCommit;
lodash.prototype.next = wrapperNext;
lodash.prototype.plant = wrapperPlant;
lodash.prototype.reverse = wrapperReverse;
lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
// Add lazy aliases.
lodash.prototype.first = lodash.prototype.head;
if (symIterator) {
lodash.prototype[symIterator] = wrapperToIterator;
}
return lodash;
});
/*--------------------------------------------------------------------------*/
// Export lodash.
var _ = runInContext();
// Some AMD build optimizers, like r.js, check for condition patterns like:
if (true) {
// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _;
// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return _;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
// Check for `exports` after `define` in case a build optimizer adds it.
else {}
}.call(this));
/***/ }),
/***/ "./resources/css/app.css":
/*!*******************************!*\
!*** ./resources/css/app.css ***!
\*******************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "./node_modules/process/browser.js":
/*!*****************************************!*\
!*** ./node_modules/process/browser.js ***!
\*****************************************/
/***/ ((module) => {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(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) {
runTimeout(drainQueue);
}
};
// 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.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/***/ "./node_modules/axios/package.json":
/*!*****************************************!*\
!*** ./node_modules/axios/package.json ***!
\*****************************************/
/***/ ((module) => {
"use strict";
module.exports = JSON.parse('{"_from":"axios@^0.21","_id":"axios@0.21.4","_inBundle":false,"_integrity":"sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==","_location":"/axios","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"axios@^0.21","name":"axios","escapedName":"axios","rawSpec":"^0.21","saveSpec":null,"fetchSpec":"^0.21"},"_requiredBy":["#DEV:/"],"_resolved":"https://registry.npmjs.org/axios/-/axios-0.21.4.tgz","_shasum":"c67b90dc0568e5c1cf2b0b858c43ba28e2eda575","_spec":"axios@^0.21","_where":"C:\\\\wamp64\\\\www\\\\system-management-school","author":{"name":"Matt Zabriskie"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"bugs":{"url":"https://github.com/axios/axios/issues"},"bundleDependencies":false,"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}],"dependencies":{"follow-redirects":"^1.14.0"},"deprecated":false,"description":"Promise based HTTP client for the browser and node.js","devDependencies":{"coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^8.2.1","sinon":"^4.5.0","terser-webpack-plugin":"^4.2.3","typescript":"^4.0.5","url-search-params":"^0.10.0","webpack":"^4.44.2","webpack-dev-server":"^3.11.0"},"homepage":"https://axios-http.com","jsdelivr":"dist/axios.min.js","keywords":["xhr","http","ajax","promise","node"],"license":"MIT","main":"index.js","name":"axios","repository":{"type":"git","url":"git+https://github.com/axios/axios.git"},"scripts":{"build":"NODE_ENV=production grunt build","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","examples":"node ./examples/server.js","fix":"eslint --fix lib/**/*.js","postversion":"git push && git push --tags","preversion":"npm test","start":"node ./sandbox/server.js","test":"grunt test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"},"typings":"./index.d.ts","unpkg":"dist/axios.min.js","version":"0.21.4"}');
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ id: moduleId,
/******/ loaded: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/chunk loaded */
/******/ (() => {
/******/ var deferred = [];
/******/ __webpack_require__.O = (result, chunkIds, fn, priority) => {
/******/ if(chunkIds) {
/******/ priority = priority || 0;
/******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];
/******/ deferred[i] = [chunkIds, fn, priority];
/******/ return;
/******/ }
/******/ var notFulfilled = Infinity;
/******/ for (var i = 0; i < deferred.length; i++) {
/******/ var [chunkIds, fn, priority] = deferred[i];
/******/ var fulfilled = true;
/******/ for (var j = 0; j < chunkIds.length; j++) {
/******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {
/******/ chunkIds.splice(j--, 1);
/******/ } else {
/******/ fulfilled = false;
/******/ if(priority < notFulfilled) notFulfilled = priority;
/******/ }
/******/ }
/******/ if(fulfilled) {
/******/ deferred.splice(i--, 1)
/******/ var r = fn();
/******/ if (r !== undefined) result = r;
/******/ }
/******/ }
/******/ return result;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/define property getters */
/******/ (() => {
/******/ // define getter functions for harmony exports
/******/ __webpack_require__.d = (exports, definition) => {
/******/ for(var key in definition) {
/******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ }
/******/ }
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/global */
/******/ (() => {
/******/ __webpack_require__.g = (function() {
/******/ if (typeof globalThis === 'object') return globalThis;
/******/ try {
/******/ return this || new Function('return this')();
/******/ } catch (e) {
/******/ if (typeof window === 'object') return window;
/******/ }
/******/ })();
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/node module decorator */
/******/ (() => {
/******/ __webpack_require__.nmd = (module) => {
/******/ module.paths = [];
/******/ if (!module.children) module.children = [];
/******/ return module;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/jsonp chunk loading */
/******/ (() => {
/******/ // no baseURI
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ "/js/app": 0,
/******/ "css/app": 0
/******/ };
/******/
/******/ // no chunk on demand loading
/******/
/******/ // no prefetching
/******/
/******/ // no preloaded
/******/
/******/ // no HMR
/******/
/******/ // no HMR manifest
/******/
/******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);
/******/
/******/ // install a JSONP callback for chunk loading
/******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ var [chunkIds, moreModules, runtime] = data;
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ for(moduleId in moreModules) {
/******/ if(__webpack_require__.o(moreModules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) var result = runtime(__webpack_require__);
/******/ }
/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[chunkIds[i]] = 0;
/******/ }
/******/ return __webpack_require__.O(result);
/******/ }
/******/
/******/ var chunkLoadingGlobal = self["webpackChunk"] = self["webpackChunk"] || [];
/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ })();
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module depends on other loaded chunks and execution need to be delayed
/******/ __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/js/app.js")))
/******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/css/app.css")))
/******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__);
/******/
/******/ })()
;
|
PayPal.Donation.Button({
env:'production',
hosted_button_id:'RN5Y7F6P6AZCU',
image: {
src:'https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif',
alt:'Donate with PayPal button',
title:'PayPal - The safer, easier way to pay online!',
}
}).render('#donate-button');
|
import { inject as service } from "@ember/service";
import Component from "@ember/component";
import config from "../config/environment";
import { action } from "@ember/object";
export default class NavbarComponent extends Component {
@service intl;
languages = config.languages;
fallbackLanguage = config.fallbackLanguage;
@action
setLanguage(language) {
if (this.languages.includes(language)) {
localStorage.setItem("language", language);
this.intl.setLocale([language, this.fallbackLanguage]);
window.location.reload(true);
}
}
}
|
'use strict';
var cybersourceRestApi = require('cybersource-rest-client');
var path = require('path');
var filePath = path.resolve('Data/Configuration.js');
var configuration = require(filePath);
var capturePayment = require('../Capture/capture-payment');
function void_capture(callback) {
try {
var configObject = new configuration();
var apiClient = new cybersourceRestApi.ApiClient();
var requestObj = new cybersourceRestApi.VoidCaptureRequest();
var clientReferenceInformation = new cybersourceRestApi.Ptsv2paymentsidreversalsClientReferenceInformation();
clientReferenceInformation.code = 'test_void';
requestObj.clientReferenceInformation = clientReferenceInformation;
var instance = new cybersourceRestApi.VoidApi(configObject, apiClient);
capturePayment.capture_payment(function (error, data) {
if (data) {
var id = data['id'];
console.log('\n*************** Void Capture ********************* ');
console.log('\nCapture ID passing to voidCapture : ' + id);
instance.voidCapture(requestObj, id, function (error, data, response) {
if (error) {
console.log('\nError : ' + JSON.stringify(error));
}
else if (data) {
console.log('\nData : ' + JSON.stringify(data));
}
console.log('\nResponse : ' + JSON.stringify(response));
console.log('\nResponse Code of Void a Capture : ' + JSON.stringify(response['status']));
callback(error, data, response);
});
}
});
}
catch (error) {
console.log('\nException on calling the API : ' + error);
}
}
if (require.main === module) {
void_capture(function () {
console.log('\nVoidCapture end.');
});
}
module.exports.void_capture = void_capture;
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[109],{248:function(e,r,t){"use strict";t.r(r),t.d(r,"frontMatter",(function(){return i})),t.d(r,"metadata",(function(){return c})),t.d(r,"rightToc",(function(){return s})),t.d(r,"default",(function(){return u}));var n=t(2),o=t(9),a=(t(0),t(332)),i={id:"comparison",title:"Comparison"},c={id:"version-v0.3/further-reading/comparison",isDocsHomePage:!1,title:"Comparison",description:"This document will provide you with an overview of how ORY Kratos compares to",source:"@site/versioned_docs/version-v0.3/further-reading/comparison.md",permalink:"/kratos/docs/further-reading/comparison",editUrl:"https://github.com/ory/kratos/edit/master/docs/versioned_docs/version-v0.3/further-reading/comparison.md",version:"v0.3",lastUpdatedBy:"aeneasr",lastUpdatedAt:1589548840,sidebar:"version-v0.3/docs",previous:{title:"SDKs",permalink:"/kratos/docs/sdk"}},s=[],p={rightToc:s};function u(e){var r=e.components,t=Object(o.a)(e,["components"]);return Object(a.b)("wrapper",Object(n.a)({},p,t,{components:r,mdxType:"MDXLayout"}),Object(a.b)("p",null,"This document will provide you with an overview of how ORY Kratos compares to\nother projects and products."))}u.isMDXComponent=!0},332:function(e,r,t){"use strict";t.d(r,"a",(function(){return l})),t.d(r,"b",(function(){return m}));var n=t(0),o=t.n(n);function a(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function i(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter((function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable}))),t.push.apply(t,n)}return t}function c(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?i(Object(t),!0).forEach((function(r){a(e,r,t[r])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):i(Object(t)).forEach((function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))}))}return e}function s(e,r){if(null==e)return{};var t,n,o=function(e,r){if(null==e)return{};var t,n,o={},a=Object.keys(e);for(n=0;n<a.length;n++)t=a[n],r.indexOf(t)>=0||(o[t]=e[t]);return o}(e,r);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n<a.length;n++)t=a[n],r.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(e,t)&&(o[t]=e[t])}return o}var p=o.a.createContext({}),u=function(e){var r=o.a.useContext(p),t=r;return e&&(t="function"==typeof e?e(r):c(c({},r),e)),t},l=function(e){var r=u(e.components);return o.a.createElement(p.Provider,{value:r},e.children)},d={inlineCode:"code",wrapper:function(e){var r=e.children;return o.a.createElement(o.a.Fragment,{},r)}},f=o.a.forwardRef((function(e,r){var t=e.components,n=e.mdxType,a=e.originalType,i=e.parentName,p=s(e,["components","mdxType","originalType","parentName"]),l=u(t),f=n,m=l["".concat(i,".").concat(f)]||l[f]||d[f]||a;return t?o.a.createElement(m,c(c({ref:r},p),{},{components:t})):o.a.createElement(m,c({ref:r},p))}));function m(e,r){var t=arguments,n=r&&r.mdxType;if("string"==typeof e||n){var a=t.length,i=new Array(a);i[0]=f;var c={};for(var s in r)hasOwnProperty.call(r,s)&&(c[s]=r[s]);c.originalType=e,c.mdxType="string"==typeof e?e:n,i[1]=c;for(var p=2;p<a;p++)i[p]=t[p];return o.a.createElement.apply(null,i)}return o.a.createElement.apply(null,t)}f.displayName="MDXCreateElement"}}]);
|
let playCount = 0;
socket.on('chatkey', (word) => {
if (!isGameEnabled) {
return;
}
if (chatFirstKey) {
chatFirstKey = false;
// start chat timer
chatStartTime = Date.now();
}
const chatWordsElement = document.getElementById('chat-words');
console.log(word);
if (word === chatWords[0]) {
//chatCompletedCharacters += chatCharacters[0];
chatCompletedWords.push(chatWords[0]);
// chatCharacters.shift();
chatWords.shift();
// chatWords = chatWords.substr(1);
chatDone = chatWords.length === 0;
const updatedChatWords = `<span class="correct">${chatCompletedWords.join(' ')}</span> ${!chatDone ? chatWords.join(' ') : ''}`;
chatWordsElement.innerHTML = updatedChatWords;
if (chatDone) {
chatFirstKey = true;
console.log(`Chat finished in ${(Date.now() - chatStartTime) / 1000} seconds`);
}
} else {
if (!chatDone) {
const updatedChatWords = `<span class="correct">${chatCompletedWords.join(' ')}</span> <span class="incorrect">${chatWords[0]}</span> ${chatWords.slice(1).join(' ')}`;
chatWordsElement.innerHTML = updatedChatWords;
}
}
});
socket.on('newPlayer', (userInfo) => {
if (!userInfo) return;
playCount++
const playerList = document.getElementById('player-area');
const profileImageContainer = document.createElement('div');
profileImageContainer.className = 'profileImageContainer';
const playerCount = document.getElementById('playerCountInfo');
playerCount.innerText = playCount < 2 ? `${playCount} player` : `${playCount} players`;
const nameTag = document.createElement('div');
nameTag.className = 'nameTag';
nameTag.innerText = userInfo.displayName;
const img = document.createElement('img');
img.className = 'playerImage';
img.src = userInfo.profileImageUrl;
img.alt = userInfo.displayName;
img.title = userInfo.displayName;
profileImageContainer.appendChild(img);
profileImageContainer.appendChild(nameTag);
playerList.appendChild(profileImageContainer);
});
function startGameForChat() {
socket.emit('startgame');
}
|
var expect = require("chai").expect;
module.exports = function (helpers) {
var component = helpers.mount(require.resolve("./index"), {
colors: ["red", "green", "blue"]
});
var liEls = component.el.querySelectorAll("li");
helpers.triggerMouseEvent(liEls[0], "mouseover");
expect(component.color).to.equal("red");
helpers.triggerMouseEvent(liEls[1], "mouseover");
expect(component.color).to.equal("green");
helpers.triggerMouseEvent(liEls[2], "mouseover");
expect(component.color).to.equal("blue");
};
|
import { createGlobalStyle } from "styled-components"
const GlobalStyle = createGlobalStyle`
h1 {
color: #9963BA;
}
`
export default GlobalStyle
|
/*
* Copyright (c) 2014-2021 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
const frisby = require('frisby')
const Joi = frisby.Joi
const insecurity = require('../../lib/insecurity')
const API_URL = 'http://localhost:3000/api'
const authHeader = { Authorization: 'Bearer ' + insecurity.authorize(), 'content-type': 'application/json' }
describe('/api/SecurityAnswers', () => {
it('GET all security answers is forbidden via public API even when authenticated', () => {
return frisby.get(API_URL + '/SecurityAnswers', { headers: authHeader })
.expect('status', 401)
})
it('POST new security answer for existing user fails from unique constraint', () => {
return frisby.post(API_URL + '/SecurityAnswers', {
headers: authHeader,
body: {
UserId: 1,
SecurityQuestionId: 1,
answer: 'Horst'
}
})
.expect('status', 400)
.expect('header', 'content-type', /application\/json/)
.expect('json', 'message', 'Validation error')
})
})
describe('/api/SecurityAnswers/:id', () => {
it('GET existing security answer by id is forbidden via public API even when authenticated', () => {
return frisby.get(API_URL + '/SecurityAnswers/1', { headers: authHeader })
.expect('status', 401)
})
it('POST security answer for a newly registered user', () => {
return frisby.post(API_URL + '/Users', {
email: 'new.user@te.st',
password: '12345'
}, { json: true })
.expect('status', 201)
.then(({ json }) => {
return frisby.post(API_URL + '/SecurityAnswers', {
headers: authHeader,
body: {
UserId: json.id,
SecurityQuestionId: 1,
answer: 'Horst'
}
})
.expect('status', 201)
.expect('header', 'content-type', /application\/json/)
.expect('jsonTypes', 'data', {
id: Joi.number(),
createdAt: Joi.string(),
updatedAt: Joi.string()
})
})
})
it('PUT update existing security answer is forbidden via public API even when authenticated', () => {
return frisby.put(API_URL + '/SecurityAnswers/1', {
headers: authHeader,
body: {
answer: 'Blurp'
}
})
.expect('status', 401)
})
it('DELETE existing security answer is forbidden via public API even when authenticated', () => {
return frisby.del(API_URL + '/SecurityAnswers/1', { headers: authHeader })
.expect('status', 401)
})
})
|
/**
* @author Ed Spencer
*
* Readers are used to interpret data to be loaded into a {@link Ext.data.Model Model} instance or a {@link
* Ext.data.Store Store} - often in response to an AJAX request. In general there is usually no need to create
* a Reader instance directly, since a Reader is almost always used together with a {@link Ext.data.proxy.Proxy Proxy},
* and is configured using the Proxy's {@link Ext.data.proxy.Proxy#cfg-reader reader} configuration property:
*
* Ext.create('Ext.data.Store', {
* model: 'User',
* proxy: {
* type: 'ajax',
* url : 'users.json',
* reader: {
* type: 'json',
* rootPorperty: 'users'
* }
* },
* });
*
* The above reader is configured to consume a JSON string that looks something like this:
*
* {
* "success": true,
* "users": [
* { "name": "User 1" },
* { "name": "User 2" }
* ]
* }
*
*
* # Loading Nested Data
*
* Readers have the ability to automatically load deeply-nested data objects based on the {@link Ext.data.association.Association
* associations} configured on each Model. Below is an example demonstrating the flexibility of these associations in a
* fictional CRM system which manages a User, their Orders, OrderItems and Products. First we'll define the models:
*
* Ext.define("User", {
* extend: 'Ext.data.Model',
* config: {
* fields: [
* 'id', 'name'
* ],
*
* hasMany: {model: 'Order', name: 'orders'},
*
* proxy: {
* type: 'rest',
* url : 'users.json',
* reader: {
* type: 'json',
* root: 'users'
* }
* }
* }
* });
*
* Ext.define("Order", {
* extend: 'Ext.data.Model',
* config: {
* fields: [
* 'id', 'total'
* ],
*
* hasMany : {model: 'OrderItem', name: 'orderItems', associationKey: 'order_items'},
* belongsTo: 'User'
* }
* });
*
* Ext.define("OrderItem", {
* extend: 'Ext.data.Model',
* config: {
* fields: [
* 'id', 'price', 'quantity', 'order_id', 'product_id'
* ],
*
* belongsTo: ['Order', {model: 'Product', associationKey: 'product'}]
* }
* });
*
* Ext.define("Product", {
* extend: 'Ext.data.Model',
* fields: [
* 'id', 'name'
* ],
*
* hasMany: 'OrderItem'
* });
*
* This may be a lot to take in - basically a User has many Orders, each of which is composed of several OrderItems.
* Finally, each OrderItem has a single Product. This allows us to consume data like this:
*
* {
* "users": [
* {
* "id": 123,
* "name": "Ed",
* "orders": [
* {
* "id": 50,
* "total": 100,
* "order_items": [
* {
* "id" : 20,
* "price" : 40,
* "quantity": 2,
* "product" : {
* "id": 1000,
* "name": "MacBook Pro"
* }
* },
* {
* "id" : 21,
* "price" : 20,
* "quantity": 3,
* "product" : {
* "id": 1001,
* "name": "iPhone"
* }
* }
* ]
* }
* ]
* }
* ]
* }
*
* The JSON response is deeply nested - it returns all Users (in this case just 1 for simplicity's sake), all of the
* Orders for each User (again just 1 in this case), all of the OrderItems for each Order (2 order items in this case),
* and finally the Product associated with each OrderItem. Now we can read the data and use it as follows:
*
* var store = Ext.create('Ext.data.Store', {
* model: "User"
* });
*
* store.load({
* callback: function() {
* //the user that was loaded
* var user = store.first();
*
* console.log("Orders for " + user.get('name') + ":")
*
* //iterate over the Orders for each User
* user.orders().each(function(order) {
* console.log("Order ID: " + order.getId() + ", which contains items:");
*
* //iterate over the OrderItems for each Order
* order.orderItems().each(function(orderItem) {
* //we know that the Product data is already loaded, so we can use the synchronous getProduct
* //usually, we would use the asynchronous version (see {@link Ext.data.association.BelongsTo})
* var product = orderItem.getProduct();
*
* console.log(orderItem.get('quantity') + ' orders of ' + product.get('name'));
* });
* });
* }
* });
*
* Running the code above results in the following:
*
* Orders for Ed:
* Order ID: 50, which contains items:
* 2 orders of MacBook Pro
* 3 orders of iPhone
*/
Ext.define('Ext.data.reader.Reader', {
requires: [
'Ext.data.ResultSet'
],
alternateClassName: ['Ext.data.Reader', 'Ext.data.DataReader'],
mixins: ['Ext.mixin.Observable'],
// private
isReader: true,
config: {
/**
* @cfg {String} idProperty
* Name of the property within a row object that contains a record identifier value. Defaults to The id of the
* model. If an idProperty is explicitly specified it will override that of the one specified on the model
*/
idProperty: undefined,
/**
* @cfg {String} clientIdProperty
* The name of the property with a response that contains the existing client side id for a record that we are reading.
*/
clientIdProperty: 'clientId',
/**
* @cfg {String} totalProperty
* Name of the property from which to retrieve the total number of records in the dataset. This is only needed if
* the whole dataset is not passed in one go, but is being paged from the remote server. Defaults to total.
*/
totalProperty: 'total',
/**
* @cfg {String} successProperty
* Name of the property from which to retrieve the success attribute. Defaults to success. See
* {@link Ext.data.proxy.Server}.{@link Ext.data.proxy.Server#exception exception} for additional information.
*/
successProperty: 'success',
/**
* @cfg {String} messageProperty
* The name of the property which contains a response message. This property is optional.
*/
messageProperty: null,
/**
* @cfg {String} rootProperty
* The name of the property which contains the Array of row objects. For JSON reader it's dot-separated list
* of property names. For XML reader it's a CSS selector. For array reader it's not applicable.
*
* By default the natural root of the data will be used. The root Json array, the root XML element, or the array.
*
* The data packet value for this property should be an empty array to clear the data or show no data.
*/
rootProperty: '',
/**
* @cfg {Boolean} implicitIncludes
* True to automatically parse models nested within other models in a response object. See the
* Ext.data.reader.Reader intro docs for full explanation. Defaults to true.
*/
implicitIncludes: true,
model: undefined
},
constructor: function(config) {
this.initConfig(config);
},
/**
* @property {Object} metaData
* The raw meta data that was most recently read, if any. Meta data can include existing
* Reader config options like {@link #idProperty}, {@link #totalProperty}, etc. that get
* automatically applied to the Reader, and those can still be accessed directly from the Reader
* if needed. However, meta data is also often used to pass other custom data to be processed
* by application code. For example, it is common when reconfiguring the data model of a grid to
* also pass a corresponding column model config to be applied to the grid. Any such data will
* not get applied to the Reader directly (it just gets passed through and is ignored by Ext).
* This metaData property gives you access to all meta data that was passed, including any such
* custom data ignored by the reader.
*
* This is a read-only property, and it will get replaced each time a new meta data object is
* passed to the reader.
*/
fieldCount: 0,
applyModel: function(model) {
if (typeof model == 'string') {
model = Ext.data.ModelManager.getModel(model);
if (!model) {
Ext.Logger.error('Model with name ' + arguments[0] + ' doesnt exist.');
}
}
if (model && !model.prototype.isModel && Ext.isObject(model)) {
model = Ext.data.ModelManager.registerType(model.storeId || model.id || Ext.id(), model);
}
return model;
},
applyIdProperty: function(idProperty) {
if (!idProperty && this.getModel()) {
idProperty = this.getModel().getIdProperty();
}
return idProperty;
},
updateModel: function(model) {
if (model) {
if (!this.getIdProperty()) {
this.setIdProperty(model.getIdProperty());
}
this.buildExtractors();
}
},
createAccessor: Ext.emptyFn,
createFieldAccessExpression: function() {
return 'undefined';
},
/**
* @private
* This builds optimized functions for retrieving record data and meta data from an object.
* Subclasses may need to implement their own getRoot function.
*/
buildExtractors: function() {
if (!this.getModel()) {
return;
}
var me = this,
totalProp = me.getTotalProperty(),
successProp = me.getSuccessProperty(),
messageProp = me.getMessageProperty();
//build the extractors for all the meta data
if (totalProp) {
me.getTotal = me.createAccessor(totalProp);
}
if (successProp) {
me.getSuccess = me.createAccessor(successProp);
}
if (messageProp) {
me.getMessage = me.createAccessor(messageProp);
}
me.extractRecordData = me.buildRecordDataExtractor();
},
/**
* @private
* Return a function which will read a raw row object in the format this Reader accepts, and populates
* a record's data object with converted data values.
*
* The returned function must be passed the following parameters:
*
* - dest A record's empty data object into which the new field value properties are injected.
* - source A raw row data object of whatever type this Reader consumes
* - record The record which is being populated.
*
*/
buildRecordDataExtractor: function() {
var me = this,
model = me.getModel(),
fields = model.getFields(),
ln = fields.length,
fieldVarName = [],
clientIdProp = me.getModel().getClientIdProperty(),
prefix = '__field',
code = [
'var me = this,\n',
' fields = me.getModel().getFields(),\n',
' idProperty = me.getIdProperty(),\n',
' idPropertyIsFn = (typeof idProperty == "function"),',
' value,\n',
' internalId'
], i, field, varName, fieldName;
fields = fields.items;
for (i = 0; i < ln; i++) {
field = fields[i];
fieldName = field.getName();
if (fieldName === model.getIdProperty()) {
fieldVarName[i] = 'idField';
} else {
fieldVarName[i] = prefix + i;
}
code.push(',\n ', fieldVarName[i], ' = fields.get("', field.getName(), '")');
}
code.push(';\n\n return function(source) {\n var dest = {};\n');
code.push(' if (idPropertyIsFn) {\n');
code.push(' idField.setMapping(idProperty);\n');
code.push(' }\n');
for (i = 0; i < ln; i++) {
field = fields[i];
varName = fieldVarName[i];
fieldName = field.getName();
if (fieldName === model.getIdProperty() && field.getMapping() === null && model.getIdProperty() !== this.getIdProperty()) {
field.setMapping(this.getIdProperty());
}
// createFieldAccessExpression must be implemented in subclasses to extract data from the source object in the correct way.
code.push(' try {\n');
code.push(' value = ', me.createFieldAccessExpression(field, varName, 'source'), ';\n');
code.push(' if (value !== undefined) {\n');
code.push(' dest["' + field.getName() + '"] = value;\n');
code.push(' }\n');
code.push(' } catch(e){}\n');
}
// set the client id as the internalId of the record.
// clientId handles the case where a client side record did not previously exist on the server,
// so the server is passing back a client id that can be used to pair the server side record up with the client record
if (clientIdProp) {
code.push(' internalId = ' + me.createFieldAccessExpression(Ext.create('Ext.data.Field', {name: clientIdProp}), null, 'source') + ';\n');
code.push(' if (internalId !== undefined) {\n');
code.push(' dest["_clientId"] = internalId;\n }\n');
}
code.push(' return dest;\n');
code.push(' };');
// Here we are creating a new Function and invoking it immediately in the scope of this Reader
// It declares several vars capturing the configured context of this Reader, and returns a function
// which, when passed a record data object, a raw data row in the format this Reader is configured to read,
// and the record which is being created, will populate the record's data object from the raw row data.
return Ext.functionFactory(code.join('')).call(me);
},
getFields: function() {
return this.getModel().getFields().items;
},
/**
* @private
* By default this function just returns what is passed to it. It can be overridden in a subclass
* to return something else. See XmlReader for an example.
* @param {Object} data The data object
* @return {Object} The normalized data object
*/
getData: function(data) {
return data;
},
/**
* Takes a raw response object (as passed to this.read) and returns the useful data segment of it.
* This must be implemented by each subclass
* @param {Object} response The response object
* @return {Object} The useful data from the response
*/
getResponseData: function(response) {
return response;
},
/**
* @private
* This will usually need to be implemented in a subclass. Given a generic data object (the type depends on the type
* of data we are reading), this function should return the object as configured by the Reader's 'root' meta data config.
* See XmlReader's getRoot implementation for an example. By default the same data object will simply be returned.
* @param {Object} data The data object
* @return {Object} The same data object
*/
getRoot: function(data) {
return data;
},
/**
* Reads the given response object. This method normalizes the different types of response object that may be passed
* to it, before handing off the reading of records to the {@link #readRecords} function.
* @param {Object} response The response object. This may be either an XMLHttpRequest object or a plain JS object
* @return {Ext.data.ResultSet} The parsed ResultSet object
*/
read: function(response) {
var data = response,
Model = this.getModel(),
resultSet, records, i, ln, record;
if (response) {
data = this.getResponseData(response);
}
if (data) {
resultSet = this.readRecords(data);
records = resultSet.getRecords();
for (i = 0, ln = records.length; i < ln; i++) {
record = records[i];
records[i] = new Model(record.data, record.id, record.node);
}
return resultSet;
} else {
return this.nullResultSet;
}
},
process: function(response) {
var data = response;
if (response) {
data = this.getResponseData(response);
}
if (data) {
return this.readRecords(data);
} else {
return this.nullResultSet;
}
},
/**
* Abstracts common functionality used by all Reader subclasses. Each subclass is expected to call this function
* before running its own logic and returning the Ext.data.ResultSet instance. For most Readers additional
* processing should not be needed.
* @param {Object} data The raw data object
* @return {Ext.data.ResultSet} A ResultSet object
*/
readRecords: function(data) {
var me = this;
/**
* @property {Object} rawData
* The raw data object that was last passed to readRecords. Stored for further processing if needed
*/
me.rawData = data;
data = me.getData(data);
if (data.metaData) {
me.onMetaChange(data.metaData);
}
// <debug>
if (!me.getModel()) {
Ext.Logger.warn('In order to read record data, a Reader needs to have a Model defined on it.');
}
// </debug>
// If we pass an array as the data, we dont use getRoot on the data.
// Instead the root equals to the data.
var root = Ext.isArray(data) ? data : me.getRoot(data),
success = true,
recordCount = 0,
total, value, records, message;
if (me.getTotalProperty()) {
value = parseInt(me.getTotal(data), 10);
if (!isNaN(value)) {
total = value;
}
}
if (me.getSuccessProperty()) {
value = me.getSuccess(data);
if (value === false || value === 'false') {
success = false;
}
}
if (me.getMessageProperty()) {
message = me.getMessage(data);
}
if (root) {
records = me.extractData(root);
recordCount = records.length;
} else {
recordCount = 0;
records = [];
}
return new Ext.data.ResultSet({
total : total,
count : recordCount,
records: records,
success: success,
message: message
});
},
/**
* Returns extracted, type-cast rows of data.
* @param {Object[]/Object} root from server response
* @private
*/
extractData : function(root) {
var me = this,
records = [],
length = root.length,
model = me.getModel(),
idProperty = model.getIdProperty(),
fieldsCollection = model.getFields(),
node, i, data, id, clientId;
/*
* We check here whether the fields are dirty since the last read.
* This works around an issue when a Model is used for both a Tree and another
* source, because the tree decorates the model with extra fields and it causes
* issues because the readers aren't notified.
*/
if (fieldsCollection.isDirty) {
me.buildExtractors(true);
delete fieldsCollection.isDirty;
}
if (!root.length && Ext.isObject(root)) {
root = [root];
length = 1;
}
for (i = 0; i < length; i++) {
clientId = null;
id = null;
node = root[i];
// When you use a Memory proxy, and you set data: [] to contain record instances
// this node will already be a record. In this case we should not try to extract
// the record data from the object, but just use the record data attribute.
if (node.isModel) {
data = node.data;
} else {
data = me.extractRecordData(node);
}
if (data._clientId !== undefined) {
clientId = data._clientId;
delete data._clientId;
}
if (data[idProperty] !== undefined) {
id = data[idProperty];
}
if (me.getImplicitIncludes()) {
me.readAssociated(data, node);
}
records.push({
clientId: clientId,
id: id,
data: data,
node: node
});
}
return records;
},
/**
* @private
* Loads a record's associations from the data object. This prepopulates hasMany and belongsTo associations
* on the record provided.
* @param {Ext.data.Model} record The record to load associations for
* @param {Object} data The data object
* @return {String} Return value description
*/
readAssociated: function(data, node) {
var associations = this.getModel().associations.items,
i = 0,
length = associations.length,
association, associationData, associationKey;
for (; i < length; i++) {
association = associations[i];
associationKey = association.getAssociationKey();
associationData = this.getAssociatedDataRoot(node, associationKey);
if (associationData) {
data[associationKey] = associationData;
}
}
},
/**
* @private
* Used internally by `readAssociated`. Given a data object (which could be json, xml etc) for a specific
* record, this should return the relevant part of that data for the given association name. This is only really
* needed to support the XML Reader, which has to do a query to get the associated data object
* @param {Object} data The raw data object
* @param {String} associationName The name of the association to get data for (uses associationKey if present)
* @return {Object} The root
*/
getAssociatedDataRoot: function(data, associationName) {
return data[associationName];
},
/**
* @private
* Reconfigures the meta data tied to this Reader
*/
onMetaChange : function(meta) {
var fields = meta.fields,
me = this,
newModel, config, idProperty;
// save off the raw meta data
me.metaData = meta;
// set any reader-specific configs from meta if available
if (meta.rootProperty !== undefined) {
me.setRootProperty(meta.rootProperty);
}
else if (meta.root !== undefined) {
me.setRootProperty(meta.root);
}
if (meta.idProperty !== undefined) {
me.setIdProperty(meta.idProperty);
}
if (meta.totalProperty !== undefined) {
me.setTotalProperty(meta.totalProperty);
}
if (meta.successProperty !== undefined) {
me.setSuccessProperty(meta.successProperty);
}
if (meta.messageProperty !== undefined) {
me.setMessageProperty(meta.messageProperty);
}
if (fields) {
if (me.getModel()) {
me.getModel().setFields(fields);
me.buildExtractors();
}
else {
idProperty = me.getIdProperty();
config = {fields: fields};
if (idProperty) {
config.idProperty = idProperty;
}
newModel = Ext.define("Ext.data.reader.MetaModel" + Ext.id(), {
extend: 'Ext.data.Model',
config: config
});
me.setModel(newModel);
}
}
else {
me.buildExtractors();
}
}
// Convert old properties in data into a config object
// <deprecated product=touch since=2.0>
,onClassExtended: function(cls, data, hooks) {
var Component = this,
defaultConfig = Component.prototype.config,
config = data.config || {},
key;
for (key in defaultConfig) {
if (key in data) {
config[key] = data[key];
delete data[key];
// <debug warn>
Ext.Logger.deprecate(key + ' is deprecated as a property directly on the Reader prototype. ' +
'Please put it inside the config object.');
// </debug>
}
}
data.config = config;
}
// </deprecated>
}, function() {
Ext.apply(this.prototype, {
// Private. Empty ResultSet to return when response is falsy (null|undefined|empty string)
nullResultSet: new Ext.data.ResultSet({
total : 0,
count : 0,
records: [],
success: false
})
});
//<deprecated product=touch since=2.0>
/**
* @cfg {String} root
* The name of the property which contains the Array of row objects. For JSON reader it's dot-separated list
* of property names. For XML reader it's a CSS selector. For array reader it's not applicable.
*
* By default the natural root of the data will be used. The root Json array, the root XML element, or the array.
*
* The data packet value for this property should be an empty array to clear the data or show no data.
*
* @deprecated 2.0.0 Please use the {@link #rootProperty} configuration instead.
*/
this.override({
constructor: function(config) {
config = config || {};
if (config.root) {
// <debug>
Ext.Logger.deprecate('root has been deprecated as a configuration on Reader. Please use rootProperty instead.');
// </debug>
config.rootProperty = config.root;
delete config.root;
}
this.callOverridden([config]);
}
});
//</deprecated>
});
|
/* eslint-disable camelcase, key-spacing, no-multi-spaces, array-bracket-spacing */
const ffi = require('ffi-napi');
const ref = require('ref');
const dlfcn = new ffi.Library(null, {
dlopen: ['pointer', ['string', 'int']]
});
const libobjc = new ffi.Library('libobjc', {
// Selectors
sel_getUid : ['pointer', ['string' ]],
sel_getName: ['string', ['pointer']],
// Classes
objc_getClass : ['pointer', ['string' ]],
object_getClass : ['pointer', ['pointer']],
object_isClass : ['bool', ['pointer']],
class_getName : ['string', ['pointer']],
class_getClassMethod : ['pointer', ['pointer', 'pointer']],
class_getInstanceMethod: ['pointer', ['pointer', 'pointer']],
class_addMethod : ['bool', ['pointer', 'pointer', 'pointer', 'string']],
class_replaceMethod : ['pointer', ['pointer', 'pointer', 'pointer', 'string']],
objc_allocateClassPair : ['pointer', ['pointer', 'string', 'int']],
objc_registerClassPair : ['void', ['pointer']],
// Methods
method_getImplementation : ['pointer', ['pointer']],
method_getTypeEncoding : ['string', ['pointer']],
method_copyReturnType : ['string', ['pointer']],
method_copyArgumentType : ['string', ['pointer', 'int']],
method_getNumberOfArguments : ['int', ['pointer']],
method_exchangeImplementations: ['void', ['pointer', 'pointer']],
method_setImplementation : ['pointer', ['pointer', 'pointer']],
// IMP
imp_implementationWithBlock: ['pointer', ['pointer']]
});
libobjc.objc_msgSend = ffi.DynamicLibrary().get('objc_msgSend'); // eslint-disable-line new-cap
const msgSend = (returnType, argumentTypes) => {
return ffi.ForeignFunction(libobjc.objc_msgSend, returnType, argumentTypes); // eslint-disable-line new-cap
};
const classExists = classname => !libobjc.objc_getClass(classname).isNull();
const getSymbol = name => new ffi.DynamicLibrary().get(name);
const getSymbolAsId = name => {
try {
const symbol = getSymbol(name);
symbol.type = ref.refType(ref.refType(ref.types.void));
return symbol.deref();
} catch (err) {
return null;
}
};
dlfcn.dlopen('/System/Library/Frameworks/Foundation.framework/Foundation', ffi.DynamicLibrary.FLAGS.RTLD_LAZY);
module.exports = libobjc;
module.exports.msgSend = msgSend;
module.exports.classExists = classExists;
module.exports.getSymbol = getSymbol;
module.exports.getSymbolAsId = getSymbolAsId;
|
let KidsProductData=[
{brand:"Gap",img:"./images/img1.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Gap",img:"./images/img2.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Gap",img:"./images/img3.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Gap",img:"./images/img4.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Gap",img:"./images/img5.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Baby Moo",img:"./images/img1.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Baby Moo",img:"./images/img2.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Baby Moo",img:"./images/img3.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Baby Moo",img:"./images/img4.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Baby Moo",img:"./images/img5.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Kanitroot",img:"./images/img1.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Kanitroot",img:"./images/img2.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Kanitroot",img:"./images/img3.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Kanitroot",img:"./images/img4.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Kanitroot",img:"./images/img5.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Bee Bay",img:"./images/img1.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Bee Bay",img:"./images/img2.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Bee Bay",img:"./images/img3.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Bee Bay",img:"./images/img4.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Bee Bay",img:"./images/img5.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Pepe Jeans",img:"./images/img1.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Pepe Jeans",img:"./images/img2.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Pepe Jeans",img:"./images/img3.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Pepe Jeans",img:"./images/img4.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Pepe Jeans",img:"./images/img5.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Puma",img:"./images/img1.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Puma",img:"./images/img2.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Puma",img:"./images/img3.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Puma",img:"./images/img4.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]},
{brand:"Puma",img:"./images/img5.jpg",price:100,detail:"Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto, sequi.",size:["L"],Extra:[]}
]
let products=document.getElementById("products");
function ShowProducts(data){
let count=0;
data.forEach(element => {
let card= document.createElement("div");
card.setAttribute("class","card");
let img=document.createElement("div");
img.setAttribute("class", "card-img");
img.style.backgroundImage=`url(${element.img})`
card.appendChild(img);
let text=document.createElement("div");
text.setAttribute("class","card-text");
let h3=document.createElement("h3");
h3.textContent=element.brand.toUpperCase();
text.appendChild(h3);
let p=document.createElement("p");
p.textContent=element.detail;
p.setAttribute("class","card-text-detail")
text.appendChild(p);
let p2=document.createElement("p");
p2.textContent="Price:- $"+element.price;
p2.setAttribute("class","card-text-price")
text.appendChild(p2);
card.appendChild(text);
products.appendChild(card);
count++;
});
products.style.height=`${count/3*450}px`
}
ShowProducts(KidsProductData);
|
export function jfFileDrop() {
return {
scope: {
jfFileUploader: '=',
jfFileDisabled: '=ngDisabled',
addCallback: '&jfAddingFileCallback'
},
restrict: 'E',
templateUrl: 'directives/jf_file_drop/jf_file_drop.html',
link: ($scope) => {
$scope.jfFileUploader.onAfterAddingFile = (fileItem) => {
$scope.jfFileUploader.queue = [fileItem];
$scope.addCallback({fileItem: fileItem});
}
}
}
}
|
/* istanbul instrument in package npmdoc_bearcat */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - init-before
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
switch (local.modeJs) {
// re-init local from window.local
case 'browser':
local = local.global.utility2.objectSetDefault(
local.global.utility2_rollup || local.global.local,
local.global.utility2
);
break;
// re-init local from example.js
case 'node':
local = (local.global.utility2_rollup || require('utility2'))
.requireReadme();
break;
}
// export local
local.global.local = local;
}());
// run shared js-env code - function
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - function
case 'browser':
break;
// run node js-env code - function
case 'node':
break;
}
// run shared js-env code - init-after
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - init-after
case 'browser':
local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
options,
onError
) {
/*
* this function will test browsers's null-case handling-behavior-behavior
*/
onError(null, options);
};
// run tests
local.nop(local.modeTest &&
document.querySelector('#testRunButton1') &&
document.querySelector('#testRunButton1').click());
break;
// run node js-env code - init-after
/* istanbul ignore next */
case 'node':
local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
options,
onError
) {
/*
* this function will test buildApidoc's default handling-behavior-behavior
*/
options = { modulePathList: module.paths };
local.buildApidoc(options, onError);
};
local.testCase_buildApp_default = local.testCase_buildApp_default || function (
options,
onError
) {
/*
* this function will test buildApp's default handling-behavior-behavior
*/
local.testCase_buildReadme_default(options, local.onErrorThrow);
local.testCase_buildLib_default(options, local.onErrorThrow);
local.testCase_buildTest_default(options, local.onErrorThrow);
local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
options = [];
local.buildApp(options, onError);
};
local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
function (options, onError) {
/*
* this function will test buildCustomOrg's default handling-behavior
*/
options = {};
local.buildCustomOrg(options, onError);
};
local.testCase_buildLib_default = local.testCase_buildLib_default || function (
options,
onError
) {
/*
* this function will test buildLib's default handling-behavior
*/
options = {};
local.buildLib(options, onError);
};
local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
options,
onError
) {
/*
* this function will test buildReadme's default handling-behavior-behavior
*/
options = {};
local.buildReadme(options, onError);
};
local.testCase_buildTest_default = local.testCase_buildTest_default || function (
options,
onError
) {
/*
* this function will test buildTest's default handling-behavior
*/
options = {};
local.buildTest(options, onError);
};
local.testCase_webpage_default = local.testCase_webpage_default || function (
options,
onError
) {
/*
* this function will test webpage's default handling-behavior
*/
options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
local.browserTest(options, onError);
};
// run test-server
local.testRunServer(local);
break;
}
}());
|
export const consumerKey = '9cfdd65a4b1003cceff8e6ca5a416c18eddba0f635d567f6f535fa6a6f75515c';
export const consumerSecret = '49da65cd2ac206974395b84021076900532fef8555295f5c96bc90dd2f66964a';
|
/* Flot Dependency: jquery.colorhelpers.js
* Plugin for jQuery for working with colors.
* Version 1.1.
* Inspiration from jQuery color animation plugin by John Resig.
* Released under the MIT license by Ole Laursen, October 2009.
*/
/* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
/*
Flot: A Javascript plotting library for jQuery, version 0.8.3.
Copyright (c) 2007-2014 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
(function($) {
// Cache the prototype hasOwnProperty for faster access
var hasOwnProperty = Object.prototype.hasOwnProperty;
// A shim to provide 'detach' to jQuery versions prior to 1.4. Using a DOM
// operation produces the same effect as detach, i.e. removing the element
// without touching its jQuery data.
// Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.
if (!$.fn.detach) {
$.fn.detach = function() {
return this.each(function() {
if (this.parentNode) {
this.parentNode.removeChild( this );
}
});
};
}
///////////////////////////////////////////////////////////////////////////
// The Canvas object is a wrapper around an HTML5 <canvas> tag.
//
// @constructor
// @param {string} cls List of classes to apply to the canvas.
// @param {element} container Element onto which to append the canvas.
//
// Requiring a container is a little iffy, but unfortunately canvas
// operations don't work unless the canvas is attached to the DOM.
function Canvas(cls, container) {
var element = container.children("." + cls)[0];
if (element == null) {
element = document.createElement("canvas");
element.className = cls;
$(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
.appendTo(container);
// If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
if (!element.getContext) {
if (window.G_vmlCanvasManager) {
element = window.G_vmlCanvasManager.initElement(element);
} else {
throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
}
}
}
this.element = element;
var context = this.context = element.getContext("2d");
// Determine the screen's ratio of physical to device-independent
// pixels. This is the ratio between the canvas width that the browser
// advertises and the number of pixels actually present in that space.
// The iPhone 4, for example, has a device-independent width of 320px,
// but its screen is actually 640px wide. It therefore has a pixel
// ratio of 2, while most normal devices have a ratio of 1.
var devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio =
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
this.pixelRatio = devicePixelRatio / backingStoreRatio;
// Size the canvas to match the internal dimensions of its container
this.resize(container.width(), container.height());
// Collection of HTML div layers for text overlaid onto the canvas
this.textContainer = null;
this.text = {};
// Cache of text fragments and metrics, so we can avoid expensively
// re-calculating them when the plot is re-rendered in a loop.
this._textCache = {};
}
// Resizes the canvas to the given dimensions.
//
// @param {number} width New width of the canvas, in pixels.
// @param {number} width New height of the canvas, in pixels.
Canvas.prototype.resize = function(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
}
var element = this.element,
context = this.context,
pixelRatio = this.pixelRatio;
// Resize the canvas, increasing its density based on the display's
// pixel ratio; basically giving it more pixels without increasing the
// size of its element, to take advantage of the fact that retina
// displays have that many more pixels in the same advertised space.
// Resizing should reset the state (excanvas seems to be buggy though)
if (this.width != width) {
element.width = width * pixelRatio;
element.style.width = width + "px";
this.width = width;
}
if (this.height != height) {
element.height = height * pixelRatio;
element.style.height = height + "px";
this.height = height;
}
// Save the context, so we can reset in case we get replotted. The
// restore ensure that we're really back at the initial state, and
// should be safe even if we haven't saved the initial state yet.
context.restore();
context.save();
// Scale the coordinate space to match the display density; so even though we
// may have twice as many pixels, we still want lines and other drawing to
// appear at the same size; the extra pixels will just make them crisper.
context.scale(pixelRatio, pixelRatio);
};
// Clears the entire canvas area, not including any overlaid HTML text
Canvas.prototype.clear = function() {
this.context.clearRect(0, 0, this.width, this.height);
};
// Finishes rendering the canvas, including managing the text overlay.
Canvas.prototype.render = function() {
var cache = this._textCache;
// For each text layer, add elements marked as active that haven't
// already been rendered, and remove those that are no longer active.
for (var layerKey in cache) {
if (hasOwnProperty.call(cache, layerKey)) {
var layer = this.getTextLayer(layerKey),
layerCache = cache[layerKey];
layer.hide();
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey];
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var positions = styleCache[key].positions;
for (var i = 0, position; position = positions[i]; i++) {
if (position.active) {
if (!position.rendered) {
layer.append(position.element);
position.rendered = true;
}
} else {
positions.splice(i--, 1);
if (position.rendered) {
position.element.detach();
}
}
}
if (positions.length == 0) {
delete styleCache[key];
}
}
}
}
}
layer.show();
}
}
};
// Creates (if necessary) and returns the text overlay container.
//
// @param {string} classes String of space-separated CSS classes used to
// uniquely identify the text layer.
// @return {object} The jQuery-wrapped text-layer div.
Canvas.prototype.getTextLayer = function(classes) {
var layer = this.text[classes];
// Create the text layer if it doesn't exist
if (layer == null) {
// Create the text layer container, if it doesn't exist
if (this.textContainer == null) {
this.textContainer = $("<div class='flot-text'></div>")
.css({
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
'font-size': "smaller",
color: "#545454"
})
.insertAfter(this.element);
}
layer = this.text[classes] = $("<div></div>")
.addClass(classes)
.css({
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0
})
.appendTo(this.textContainer);
}
return layer;
};
// Creates (if necessary) and returns a text info object.
//
// The object looks like this:
//
// {
// width: Width of the text's wrapper div.
// height: Height of the text's wrapper div.
// element: The jQuery-wrapped HTML div containing the text.
// positions: Array of positions at which this text is drawn.
// }
//
// The positions array contains objects that look like this:
//
// {
// active: Flag indicating whether the text should be visible.
// rendered: Flag indicating whether the text is currently visible.
// element: The jQuery-wrapped HTML div containing the text.
// x: X coordinate at which to draw the text.
// y: Y coordinate at which to draw the text.
// }
//
// Each position after the first receives a clone of the original element.
//
// The idea is that that the width, height, and general 'identity' of the
// text is constant no matter where it is placed; the placements are a
// secondary property.
//
// Canvas maintains a cache of recently-used text info objects; getTextInfo
// either returns the cached element or creates a new entry.
//
// @param {string} layer A string of space-separated CSS classes uniquely
// identifying the layer containing this text.
// @param {string} text Text string to retrieve info for.
// @param {(string|object)=} font Either a string of space-separated CSS
// classes or a font-spec object, defining the text's font and style.
// @param {number=} angle Angle at which to rotate the text, in degrees.
// Angle is currently unused, it will be implemented in the future.
// @param {number=} width Maximum width of the text before it wraps.
// @return {object} a text info object.
Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
var textStyle, layerCache, styleCache, info;
// Cast the value to a string, in case we were given a number or such
text = "" + text;
// If the font is a font-spec object, generate a CSS font definition
if (typeof font === "object") {
textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
} else {
textStyle = font;
}
// Retrieve (or create) the cache for the text's layer and styles
layerCache = this._textCache[layer];
if (layerCache == null) {
layerCache = this._textCache[layer] = {};
}
styleCache = layerCache[textStyle];
if (styleCache == null) {
styleCache = layerCache[textStyle] = {};
}
info = styleCache[text];
// If we can't find a matching element in our cache, create a new one
if (info == null) {
var element = $("<div></div>").html(text)
.css({
position: "absolute",
'max-width': width,
top: -9999
})
.appendTo(this.getTextLayer(layer));
if (typeof font === "object") {
element.css({
font: textStyle,
color: font.color
});
} else if (typeof font === "string") {
element.addClass(font);
}
info = styleCache[text] = {
width: element.outerWidth(true),
height: element.outerHeight(true),
element: element,
positions: []
};
element.detach();
}
return info;
};
// Adds a text string to the canvas text overlay.
//
// The text isn't drawn immediately; it is marked as rendering, which will
// result in its addition to the canvas on the next render pass.
//
// @param {string} layer A string of space-separated CSS classes uniquely
// identifying the layer containing this text.
// @param {number} x X coordinate at which to draw the text.
// @param {number} y Y coordinate at which to draw the text.
// @param {string} text Text string to draw.
// @param {(string|object)=} font Either a string of space-separated CSS
// classes or a font-spec object, defining the text's font and style.
// @param {number=} angle Angle at which to rotate the text, in degrees.
// Angle is currently unused, it will be implemented in the future.
// @param {number=} width Maximum width of the text before it wraps.
// @param {string=} halign Horizontal alignment of the text; either "left",
// "center" or "right".
// @param {string=} valign Vertical alignment of the text; either "top",
// "middle" or "bottom".
Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
var info = this.getTextInfo(layer, text, font, angle, width),
positions = info.positions;
// Tweak the div's position to match the text's alignment
if (halign == "center") {
x -= info.width / 2;
} else if (halign == "right") {
x -= info.width;
}
if (valign == "middle") {
y -= info.height / 2;
} else if (valign == "bottom") {
y -= info.height;
}
// Determine whether this text already exists at this position.
// If so, mark it for inclusion in the next render pass.
for (var i = 0, position; position = positions[i]; i++) {
if (position.x == x && position.y == y) {
position.active = true;
return;
}
}
// If the text doesn't exist at this position, create a new entry
// For the very first position we'll re-use the original element,
// while for subsequent ones we'll clone it.
position = {
active: true,
rendered: false,
element: positions.length ? info.element.clone() : info.element,
x: x,
y: y
};
positions.push(position);
// Move the element to its final position within the container
position.element.css({
top: Math.round(y),
left: Math.round(x),
'text-align': halign // In case the text wraps
});
};
// Removes one or more text strings from the canvas text overlay.
//
// If no parameters are given, all text within the layer is removed.
//
// Note that the text is not immediately removed; it is simply marked as
// inactive, which will result in its removal on the next render pass.
// This avoids the performance penalty for 'clear and redraw' behavior,
// where we potentially get rid of all text on a layer, but will likely
// add back most or all of it later, as when redrawing axes, for example.
//
// @param {string} layer A string of space-separated CSS classes uniquely
// identifying the layer containing this text.
// @param {number=} x X coordinate of the text.
// @param {number=} y Y coordinate of the text.
// @param {string=} text Text string to remove.
// @param {(string|object)=} font Either a string of space-separated CSS
// classes or a font-spec object, defining the text's font and style.
// @param {number=} angle Angle at which the text is rotated, in degrees.
// Angle is currently unused, it will be implemented in the future.
Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
if (text == null) {
var layerCache = this._textCache[layer];
if (layerCache != null) {
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey];
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var positions = styleCache[key].positions;
for (var i = 0, position; position = positions[i]; i++) {
position.active = false;
}
}
}
}
}
}
} else {
var positions = this.getTextInfo(layer, text, font, angle).positions;
for (var i = 0, position; position = positions[i]; i++) {
if (position.x == x && position.y == y) {
position.active = false;
}
}
}
};
///////////////////////////////////////////////////////////////////////////
// The top-level container for the entire plot.
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var series = [],
options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85, // set to 0 to avoid background
sorted: null // default to no legend sorting
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null // number or [number, "unit"]
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
// Omit 'zero', so we can later default its value to
// match that of the 'fill' option.
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null,
align: "left", // "left", "right", or "center"
horizontal: false,
zero: true
},
shadowSize: 3,
highlightColor: null
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: null, // set if different from the grid color
tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
margin: 0, // distance from the canvas edge to the grid
labelMargin: 5, // in pixels
axisMargin: 8, // in pixels
borderWidth: 2, // in pixels
minBorderMargin: null, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 10 // how far the mouse can be away to activate an item
},
interaction: {
redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
},
hooks: {}
},
surface = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
processOffset: [],
drawBackground: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return surface.element; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
};
};
plot.shutdown = shutdown;
plot.destroy = function () {
shutdown();
placeholder.removeData("plot").empty();
series = [];
options = null;
surface = null;
overlay = null;
eventHolder = null;
ctx = null;
octx = null;
xaxes = [];
yaxes = [];
hooks = null;
highlights = [];
plot = null;
};
plot.resize = function () {
var width = placeholder.width(),
height = placeholder.height();
surface.resize(width, height);
overlay.resize(width, height);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
// References to key classes, allowing plugins to modify them
var classes = {
Canvas: Canvas
};
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot, classes);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
$.extend(true, options, opts);
// $.extend merges arrays, rather than replacing them. When less
// colors are provided than the size of the default palette, we
// end up with those colors plus the remaining defaults, which is
// not expected behavior; avoid it by replacing them here.
if (opts && opts.colors) {
options.colors = opts.colors;
}
if (options.xaxis.color == null)
options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
if (options.yaxis.color == null)
options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// Fill in defaults for axis options, including any unspecified
// font-spec fields, if a font-spec was provided.
// If no x/y axis options were provided, create one of each anyway,
// since the rest of the code assumes that they exist.
var i, axisOptions, axisCount,
fontSize = placeholder.css("font-size"),
fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
fontDefaults = {
style: placeholder.css("font-style"),
size: Math.round(0.8 * fontSizeDefault),
variant: placeholder.css("font-variant"),
weight: placeholder.css("font-weight"),
family: placeholder.css("font-family")
};
axisCount = options.xaxes.length || 1;
for (i = 0; i < axisCount; ++i) {
axisOptions = options.xaxes[i];
if (axisOptions && !axisOptions.tickColor) {
axisOptions.tickColor = axisOptions.color;
}
axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
options.xaxes[i] = axisOptions;
if (axisOptions.font) {
axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
if (!axisOptions.font.color) {
axisOptions.font.color = axisOptions.color;
}
if (!axisOptions.font.lineHeight) {
axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
}
}
}
axisCount = options.yaxes.length || 1;
for (i = 0; i < axisCount; ++i) {
axisOptions = options.yaxes[i];
if (axisOptions && !axisOptions.tickColor) {
axisOptions.tickColor = axisOptions.color;
}
axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
options.yaxes[i] = axisOptions;
if (axisOptions.font) {
axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
if (!axisOptions.font.color) {
axisOptions.font.color = axisOptions.color;
}
if (!axisOptions.font.lineHeight) {
axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
}
}
}
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
// Override the inherit to allow the axis to auto-scale
if (options.x2axis.min == null) {
options.xaxes[1].min = null;
}
if (options.x2axis.max == null) {
options.xaxes[1].max = null;
}
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
// Override the inherit to allow the axis to auto-scale
if (options.y2axis.min == null) {
options.yaxes[1].min = null;
}
if (options.y2axis.max == null) {
options.yaxes[1].max = null;
}
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
if (options.highlightColor != null)
options.series.highlightColor = options.highlightColor;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var neededColors = series.length, maxIndex = -1, i;
// Subtract the number of series that already have fixed colors or
// color indexes from the number that we still need to generate.
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
neededColors--;
if (typeof sc == "number" && sc > maxIndex) {
maxIndex = sc;
}
}
}
// If any of the series have fixed color indexes, then we need to
// generate at least as many colors as the highest index.
if (neededColors <= maxIndex) {
neededColors = maxIndex + 1;
}
// Generate all the colors, using first the option colors and then
// variations on those colors once they're exhausted.
var c, colors = [], colorPool = options.colors,
colorPoolSize = colorPool.length, variation = 0;
for (i = 0; i < neededColors; i++) {
c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
// Each time we exhaust the colors in the pool we adjust
// a scaling factor used to produce more variations on
// those colors. The factor alternates negative/positive
// to produce lighter/darker colors.
// Reset the variation after every few cycles, or else
// it will end up producing only white or black colors.
if (i % colorPoolSize == 0 && i) {
if (variation >= 0) {
if (variation < 0.5) {
variation = -variation - 0.2;
} else variation = 0;
} else variation = -variation;
}
colors[i] = c.scale('rgb', 1 + variation);
}
// Finalize the series options, filling in their colors
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// If nothing was provided for lines.zero, default it to match
// lines.fill, since areas by default should extend to zero.
if (s.lines.zero == null) {
s.lines.zero = !!s.lines.fill;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p,
data, format;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
data = s.data;
format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
var insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.autoscale !== false) {
if (f.x) {
updateAxis(s.xaxis, val, val);
}
if (f.y) {
updateAxis(s.yaxis, val, val);
}
}
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points;
ps = s.datapoints.pointsize;
format = s.datapoints.format;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta;
switch (s.bars.align) {
case "left":
delta = 0;
break;
case "right":
delta = -s.bars.barWidth;
break;
default:
delta = -s.bars.barWidth / 2;
}
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function setupCanvases() {
// Make sure the placeholder is clear of everything except canvases
// from a previous plot in this container that we'll try to re-use.
placeholder.css("padding", 0) // padding messes up the positioning
.children().filter(function(){
return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base');
}).remove();
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
surface = new Canvas("flot-base", placeholder);
overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features
ctx = surface.context;
octx = overlay.context;
// define which element we're listening for events on
eventHolder = $(overlay.element).unbind();
// If we're re-using a plot object, shut down the old one
var existing = placeholder.data("plot");
if (existing) {
existing.shutdown();
overlay.clear();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
// Use bind, rather than .mouseleave, because we officially
// still support jQuery 1.2.6, which doesn't define a shortcut
// for mouseenter or mouseleave. This was a bug/oversight that
// was fixed somewhere around 1.3.x. We can return to using
// .mouseleave when we drop support for 1.2.6.
eventHolder.bind("mouseleave", onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options,
ticks = axis.ticks || [],
labelWidth = opts.labelWidth || 0,
labelHeight = opts.labelHeight || 0,
maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null),
legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
font = opts.font || "flot-tick-label tickLabel";
for (var i = 0; i < ticks.length; ++i) {
var t = ticks[i];
if (!t.label)
continue;
var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
labelWidth = Math.max(labelWidth, info.width);
labelHeight = Math.max(labelHeight, info.height);
}
axis.labelWidth = opts.labelWidth || labelWidth;
axis.labelHeight = opts.labelHeight || labelHeight;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset; this first phase only looks at one
// dimension per axis, the other dimension depends on the
// other axes so will have to wait
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
isXAxis = axis.direction === "x",
tickLength = axis.options.tickLength,
axisMargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
innermost = true,
outermost = true,
first = true,
found = false;
// Determine the axis's position in its direction and on its side
$.each(isXAxis ? xaxes : yaxes, function(i, a) {
if (a && (a.show || a.reserveSpace)) {
if (a === axis) {
found = true;
} else if (a.options.position === pos) {
if (found) {
outermost = false;
} else {
innermost = false;
}
}
if (!found) {
first = false;
}
}
});
// The outermost axis on each side has no margin
if (outermost) {
axisMargin = 0;
}
// The ticks for the first axis in each direction stretch across
if (tickLength == null) {
tickLength = first ? "full" : 5;
}
if (!isNaN(+tickLength))
padding += +tickLength;
if (isXAxis) {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axisMargin;
axis.box = { top: surface.height - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axisMargin, height: lh };
plotOffset.top += lh + axisMargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axisMargin, width: lw };
plotOffset.left += lw + axisMargin;
}
else {
plotOffset.right += lw + axisMargin;
axis.box = { left: surface.width - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// now that all axis boxes have been placed in one
// dimension, we can set the remaining dimension coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left - axis.labelWidth / 2;
axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
}
else {
axis.box.top = plotOffset.top - axis.labelHeight / 2;
axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
}
}
function adjustLayoutForThingsStickingOut() {
// possibly adjust plot offset to ensure everything stays
// inside the canvas and isn't clipped off
var minMargin = options.grid.minBorderMargin,
axis, i;
// check stuff from the plot (FIXME: this should just read
// a value from the series, otherwise it's impossible to
// customize)
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
}
var margins = {
left: minMargin,
right: minMargin,
top: minMargin,
bottom: minMargin
};
// check axis labels, note we don't check the actual
// labels but instead use the overall width/height to not
// jump as much around with replots
$.each(allAxes(), function (_, axis) {
if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
if (axis.direction === "x") {
margins.left = Math.max(margins.left, axis.labelWidth / 2);
margins.right = Math.max(margins.right, axis.labelWidth / 2);
} else {
margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
margins.top = Math.max(margins.top, axis.labelHeight / 2);
}
}
});
plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
}
function setupGrid() {
var i, axes = allAxes(), showGrid = options.grid.show;
// Initialize the plot's offset from the edge of the canvas
for (var a in plotOffset) {
var margin = options.grid.margin || 0;
plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
}
executeHooks(hooks.processOffset, [plotOffset]);
// If the grid is visible, add its border width to the offset
for (var a in plotOffset) {
if(typeof(options.grid.borderWidth) == "object") {
plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
}
else {
plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
}
}
$.each(axes, function (_, axis) {
var axisOpts = axis.options;
axis.show = axisOpts.show == null ? axis.used : axisOpts.show;
axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace;
setRange(axis);
});
if (showGrid) {
var allocatedAxes = $.grep(axes, function (axis) {
return axis.show || axis.reserveSpace;
});
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions calculated, we can compute the
// axis bounding boxes, start from the outside
// (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
adjustLayoutForThingsStickingOut();
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
}
plotWidth = surface.width - plotOffset.left - plotOffset.right;
plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
// now we got the proper plot dimensions, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (showGrid) {
drawAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
var delta = (axis.max - axis.min) / noTicks,
dec = -Math.floor(Math.log(delta) / Math.LN10),
maxDec = opts.tickDecimals;
if (maxDec != null && dec > maxDec) {
dec = maxDec;
}
var magn = Math.pow(10, -dec),
norm = delta / magn, // norm is between 1.0 and 10.0
size;
if (norm < 1.5) {
size = 1;
} else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
} else if (norm < 7.5) {
size = 5;
} else {
size = 10;
}
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize) {
size = opts.minTickSize;
}
axis.delta = delta;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
// Time mode was moved to a plug-in in 0.8, and since so many people use it
// we'll add an especially friendly reminder to make sure they included it.
if (opts.mode == "time" && !axis.tickGenerator) {
throw new Error("Time mode requires the flot.time plugin.");
}
// Flot supports base-10 axes; any other mode else is handled by a plug-in,
// like flot.time.js.
if (!axis.tickGenerator) {
axis.tickGenerator = function (axis) {
var ticks = [],
start = floorInBase(axis.min, axis.tickSize),
i = 0,
v = Number.NaN,
prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
axis.tickFormatter = function (value, axis) {
var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
var formatted = "" + Math.round(value * factor) / factor;
// If tickDecimals was specified, ensure that we have exactly that
// much precision; otherwise default to the value's own precision.
if (axis.tickDecimals != null) {
var decimal = formatted.indexOf(".");
var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
if (precision < axis.tickDecimals) {
return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
}
}
return formatted;
};
}
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = axis.tickGenerator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
axis.tickGenerator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (!axis.mode && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
ts = axis.tickGenerator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks(axis);
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
surface.clear();
executeHooks(hooks.drawBackground, [ctx]);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData) {
drawGrid();
}
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i]]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData) {
drawGrid();
}
surface.render();
// A draw implies that either the axes or data have changed, so we
// should probably update the overlay highlights as well.
triggerRedrawOverlay();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (var i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i, axes, bw, bc;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
var xequal = xrange.from === xrange.to,
yequal = yrange.from === yrange.to;
if (xequal && yequal) {
continue;
}
// then draw
xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
yrange.to = Math.floor(yrange.axis.p2c(yrange.to));
if (xequal || yequal) {
var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
subPixel = lineWidth % 2 ? 0.5 : 0;
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = lineWidth;
if (xequal) {
ctx.moveTo(xrange.to + subPixel, yrange.from);
ctx.lineTo(xrange.to + subPixel, yrange.to);
} else {
ctx.moveTo(xrange.from, yrange.to + subPixel);
ctx.lineTo(xrange.to, yrange.to + subPixel);
}
ctx.stroke();
} else {
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
axes = allAxes();
bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue;
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.strokeStyle = axis.options.color;
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth + 1;
else
yoff = plotHeight + 1;
if (ctx.lineWidth == 1) {
if (axis.direction == "x") {
y = Math.floor(y) + 0.5;
} else {
x = Math.floor(x) + 0.5;
}
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.strokeStyle = axis.options.tickColor;
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (isNaN(v) || v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full"
&& ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
// If either borderWidth or borderColor is an object, then draw the border
// line by line instead of as one rectangle
bc = options.grid.borderColor;
if(typeof bw == "object" || typeof bc == "object") {
if (typeof bw !== "object") {
bw = {top: bw, right: bw, bottom: bw, left: bw};
}
if (typeof bc !== "object") {
bc = {top: bc, right: bc, bottom: bc, left: bc};
}
if (bw.top > 0) {
ctx.strokeStyle = bc.top;
ctx.lineWidth = bw.top;
ctx.beginPath();
ctx.moveTo(0 - bw.left, 0 - bw.top/2);
ctx.lineTo(plotWidth, 0 - bw.top/2);
ctx.stroke();
}
if (bw.right > 0) {
ctx.strokeStyle = bc.right;
ctx.lineWidth = bw.right;
ctx.beginPath();
ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
ctx.stroke();
}
if (bw.bottom > 0) {
ctx.strokeStyle = bc.bottom;
ctx.lineWidth = bw.bottom;
ctx.beginPath();
ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
ctx.lineTo(0, plotHeight + bw.bottom / 2);
ctx.stroke();
}
if (bw.left > 0) {
ctx.strokeStyle = bc.left;
ctx.lineWidth = bw.left;
ctx.beginPath();
ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
ctx.lineTo(0- bw.left/2, 0);
ctx.stroke();
}
}
else {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
}
ctx.restore();
}
function drawAxisLabels() {
$.each(allAxes(), function (_, axis) {
var box = axis.box,
legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
font = axis.options.font || "flot-tick-label tickLabel",
tick, x, y, halign, valign;
// Remove text before checking for axis.show and ticks.length;
// otherwise plugins, like flot-tickrotor, that draw their own
// tick labels will end up with both theirs and the defaults.
surface.removeText(layer);
if (!axis.show || axis.ticks.length == 0)
return;
for (var i = 0; i < axis.ticks.length; ++i) {
tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
if (axis.direction == "x") {
halign = "center";
x = plotOffset.left + axis.p2c(tick.v);
if (axis.position == "bottom") {
y = box.top + box.padding;
} else {
y = box.top + box.height - box.padding;
valign = "bottom";
}
} else {
valign = "middle";
y = plotOffset.top + axis.p2c(tick.v);
if (axis.position == "left") {
x = box.left + box.width - box.padding;
halign = "right";
} else {
x = box.left + box.padding;
}
}
surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
}
});
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
// If the user sets the line width to 0, we change it to a very
// small value. A line width of 0 seems to force the default of 1.
// Doing the conditional here allows the shadow setting to still be
// optional even with a lineWidth of 0.
if( lw == 0 )
lw = 0.0001;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.fillStyle = fillStyleCallback(bottom, top);
c.fillRect(left, top, right - left, bottom - top)
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom);
if (drawLeft)
c.lineTo(left, top);
else
c.moveTo(left, top);
if (drawTop)
c.lineTo(right, top);
else
c.moveTo(right, top);
if (drawRight)
c.lineTo(right, bottom);
else
c.moveTo(right, bottom);
if (drawBottom)
c.lineTo(left, bottom);
else
c.moveTo(left, bottom);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft;
switch (series.bars.align) {
case "left":
barLeft = 0;
break;
case "right":
barLeft = -series.bars.barWidth;
break;
default:
barLeft = -series.bars.barWidth / 2;
}
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
if (options.legend.container != null) {
$(options.legend.container).html("");
} else {
placeholder.find(".legend").remove();
}
if (!options.legend.show) {
return;
}
var fragments = [], entries = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
// Build a list of legend entries, with each having a label and a color
for (var i = 0; i < series.length; ++i) {
s = series[i];
if (s.label) {
label = lf ? lf(s.label, s) : s.label;
if (label) {
entries.push({
label: label,
color: s.color
});
}
}
}
// Sort the legend using either the default or a custom comparator
if (options.legend.sorted) {
if ($.isFunction(options.legend.sorted)) {
entries.sort(options.legend.sorted);
} else if (options.legend.sorted == "reverse") {
entries.reverse();
} else {
var ascending = options.legend.sorted != "descending";
entries.sort(function(a, b) {
return a.label == b.label ? 0 : (
(a.label < b.label) != ascending ? 1 : -1 // Logical XOR
);
});
}
}
// Generate markup for the list of entries, in their final order
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i];
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + entry.label + '</td>'
);
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j, ps;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
ps = s.datapoints.pointsize;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft, barRight;
switch (s.bars.align) {
case "left":
barLeft = 0;
break;
case "right":
barLeft = -s.bars.barWidth;
break;
default:
barLeft = -s.bars.barWidth / 2;
}
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
var t = options.interaction.redrawOverlayInterval;
if (t == -1) { // skip event queue
drawOverlay();
return;
}
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, t);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
overlay.clear();
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
return;
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis,
highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = highlightColor;
var radius = 1.5 * pointRadius;
x = axisx.p2c(x);
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
fillStyle = highlightColor,
barLeft;
switch (series.bars.align) {
case "left":
barLeft = 0;
break;
case "right":
barLeft = -series.bars.barWidth;
break;
default:
barLeft = -series.bars.barWidth / 2;
}
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = highlightColor;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness);
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
// Add the plot function to the top level of the jQuery object
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.8.3";
$.plot.plugins = [];
// Also add the plot function as a chainable property
$.fn.plot = function(data, options) {
return this.each(function() {
$.plot(this, data, options);
});
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery);
|
app.controller("BookDetailCtrl", function ($scope, $http, httpService, $stateParams, $ionicLoading, $ionicPopup, $ionicPlatform, $cordovaClipboard, $cordovaToast, $timeout, $rootScope) {
// loading spinner in the beginning
$scope.isLoading = true;
$scope.isTimeout = false;
$ionicPlatform.ready(function () {
// check user login
if (user_id === '') {
$scope.isLogin = false;
} else {
$scope.isLogin = true;
}
$scope.input = {
comment: ''
};
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
httpService.post_token($scope, $http, url, obj);
});
// if get token success, request for book detail
$scope.$on('httpService:postTokenSuccess', function () {
token = $scope.data.token;
//console.log(token);
var url = "";
//request compressed image or high res images
if(loadCompressedImages==false)
{
url = post_content_url + $stateParams.id;
}
else
{
url = post_compressed_content_url + $stateParams.id;
}
httpService.get($scope, $http, url, 'content', token);
console.log('BookDetailCtrl');
});
var term_content_type_id;
$rootScope.$on('ReloadDefaultLanguage',reloadTermStaticPageLanguage);
// if get detail book success, set detail book
$scope.$on('httpService:getRequestSuccess', function () {
$scope.content_data = {
id: $stateParams.id,
cover: $scope.data.post.featured_image_path,
title: $scope.data.post.title,
writer: getPostMetaValueById($scope.data.post.post_meta, 'writer'),
publisher: getPostMetaValueById($scope.data.post.post_meta, 'publisher'),
summary: $scope.data.post.summary,
content: $scope.data.post.content,
comment_status: $scope.data.post.comment_status,
total_likes: $scope.data.post.like_count,
total_comments: $scope.data.post.comment_count,
comments: $scope.data.post.comment,
likes: $scope.data.post.like,
post_meta: $scope.data.post.post_meta
};
term_content_type_id = $scope.data.post.term_content_type_id;
$scope = reloadTermStaticPageLanguage($scope,term_content_type_id);
$scope.comments = $scope.content_data.comments;
$scope.isLoading = false;
if ($scope.content_data.comment_status != 0) {
if($scope.content_data.likes !== undefined && $scope.content_data.likes !== null) {
if (checkPostLikes($scope.content_data.likes, user_id)) {
$scope.liked = true;
} else {
$scope.liked = false;
}
}
}
if(isPhoneGap())
{
//console.log($stateParams.id + " " + $scope.data.post.term_id + " " + 'ArticleDetailCtrl' + " " + $scope.data);
savePostJSONToDB($stateParams.id, $scope.data.post.term_id, 'BookDetailCtrl', $scope.data);
//console.log('saved');
}
//request compressed image if set to on
if(loadCompressedImages)
{
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
// call angular http service
httpService.post_token($scope, $http, url, obj, 'high-res-data-content');
}
});
// if get token failed, request token again
$scope.$on('httpService:postTokenError', function () {
if($scope.status === 0)
{
if(isPhoneGap())
{
loadPostJSONFromDB($stateParams.id, $scope);
}
}
else
{
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
httpService.post_token($scope, $http, url, obj, 'content');
}
});
//if get data failed, request token again
$scope.$on('httpService:getRequestError', function () {
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
$scope.isTimeout = true;
// httpService.post_token($scope, $http, url, obj, 'content');
});
$scope.$on('httpService:postTokenGetHighResDataSuccess', function (event, args) {
token = $scope.data.token;
//console.log(token);
var url = post_content_url + $stateParams.id;
httpService.get($scope, $http, url, 'high-res-data-content', token);
//console.log($scope.data);
});
$scope.$on('httpService:postTokenGetHighResDataError', function (event, args) {
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
// call angular http service
httpService.post_token($scope, $http, url, obj, 'high-res-data-content');
});
$scope.$on('httpService:getHighResDataSuccess', function (event, args) {
var updated_data = args.data;
$scope.content_data = {
id: $stateParams.id,
cover: updated_data.post.featured_image_path,
title: updated_data.post.title,
writer: getPostMetaValueById(updated_data.post.post_meta, 'writer'),
publisher: getPostMetaValueById(updated_data.post.post_meta, 'publisher'),
summary: updated_data.post.summary,
content: updated_data.post.content,
comment_status: updated_data.post.comment_status,
total_likes: updated_data.post.like_count,
total_comments: updated_data.post.comment_count,
comments: updated_data.post.comment,
likes: updated_data.post.like,
post_meta: updated_data.post.post_meta
};
$scope = reloadTermStaticPageLanguage($scope,term_content_type_id);
//display true resolution image
console.log('true resolution loaded');
// save to db first page
if(isPhoneGap())
{
//console.log($stateParams.id + " " + $scope.data.post.term_id + " " + 'ArticleDetailCtrl' + " " + $scope.data);
savePostJSONToDB($stateParams.id, updated_data.post.term_id, 'BookDetailCtrl', updated_data);
//console.log('saved');
}
});
// if get data list article error, set timeout, then tap reload again.
$scope.$on('httpService:getHighResDataError', function (event, args) {
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
// call angular http service
httpService.post_token($scope, $http, url, obj, 'high-res-data-content');
});
// function submit comment
$scope.postComment = function () {
if ($scope.input.comment !== '') {
$scope.show();
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
// get token for posting comment
httpService.post_token($scope, $http, url, obj, 'post_comment');
}
};
// if token for post comment success
$scope.$on('httpService:postTokenCommentSuccess', function () {
token = $scope.data.token;
//console.log('token post comment = ' + token);
var obj = serializeData({_method: 'POST', content: $scope.input.comment, post_id: $stateParams.id, user_id: user_id, company_id: company_id, author: username_login});
// post comment
httpService.post($scope, $http, comments_url + '?token=' + token, obj, 'post_comment');
});
// if token for post comment error
$scope.$on('httpService:postTokenCommentError', function () {
$scope.hide();
$scope.showFailedAlert();
});
// if post comment success
$scope.$on('httpService:postCommentSuccess', function () {
if ($scope.data.success === true) {
$scope.hide();
$scope.showSuccessAlert();
$scope.content_data.comments.push($scope.data.comment);
$scope.content_data.total_comments++;
$scope.input = {
comment: ''
};
//console.log($scope.comments);
} else {
$scope.hide();
$scope.showFailedAlert();
}
});
$scope.$on('httpService:postCommentError', function () {
console.log('failed post comment');
$scope.hide();
$scope.showFailedAlert();
});
$scope.likeFunction = function () {
$scope.show();
//console.log('masuk like');
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
httpService.post_token($scope, $http, url, obj, 'post_like');
};
$scope.$on('httpService:postTokenLikeSuccess', function () {
var new_token = $scope.data.token;
//console.log('token post Likes = ' + new_token);
var obj = serializeData({_method: 'POST', content: '', post_id: $stateParams.id, user_id: user_id, company_id: company_id, author: username_login});
// post comment
httpService.post($scope, $http, likes_url + '?token=' + new_token, obj, 'post_like');
});
$scope.$on('httpService:postLikeSuccess', function () {
if ($scope.data.success === true) {
$scope.hide();
$scope.liked = true;
$scope.content_data.total_likes++;
} else {
$scope.hide();
$scope.liked = false;
}
});
$scope.$on('httpService:postLikeError', function () {
$scope.hide();
});
$scope.$on('httpService:postTokenLikeError', function () {
$scope.hide();
});
$scope.show = function () {
$ionicLoading.show({
template: ionicLoadingTemplate
});
};
$scope.hide = function () {
$ionicLoading.hide();
};
// alert fragment
$scope.showSuccessAlert = function () {
var alertPopup = $ionicPopup.alert({
title: $scope.text_comment_title,
css: 'cp-button',
okType:'cp-button',
okText:$scope.alert_button_ok,
template: '<div style="width:100%;text-align:center">' + $scope.text_comment_alert_success + '</div>'
});
};
$scope.showFailedAlert = function () {
var alertPopup = $ionicPopup.alert({
title: $scope.text_comment_title,
css: 'cp-button',
okType:'cp-button',
okText:$scope.alert_button_ok,
template: '<div style="width:100%;text-align:center">' + $scope.text_comment_alert_error + '</div>'
});
};
$scope.socialShare = function () {
if (isPhoneGap()) {
if (isAndroid()) {
socialShare($cordovaClipboard, $cordovaToast, $timeout, $scope.content_data.summary, $scope.content_data.title, null, playstore_link, 'Read more at');
}
else if (isIOS()) {
socialShare($cordovaClipboard, $cordovaToast, $timeout, $scope.content_data.summary, $scope.content_data.title, null, appstore_link, 'Read more at');
}
} else {
console.log('Social Share: Not a Mobile Device');
console.log($scope.content_data.summary);
console.log($scope.content_data.title);
console.log(playstore_link);
console.log(appstore_link);
}
};
$scope.isPhoneGap = function()
{
return isPhoneGap();
};
$scope.$on('SQLite:getOfflineDataSuccess', function () {
$scope.content_data = {
id: $stateParams.id,
cover: $scope.data.post.featured_image_path,
title: $scope.data.post.title,
writer: getPostMetaValueById($scope.data.post.post_meta, 'writer'),
publisher: getPostMetaValueById($scope.data.post.post_meta, 'publisher'),
summary: $scope.data.post.summary,
content: $scope.data.post.content,
comment_status: $scope.data.post.comment_status,
total_likes: $scope.data.post.like_count,
total_comments: $scope.data.post.comment_count,
comments: $scope.data.post.comment,
likes: $scope.data.post.like
};
$scope.comments = $scope.content_data.comments;
$scope.isLoading = false;
if ($scope.content_data.comment_status != 0) {
if($scope.content_data.likes !== undefined && $scope.content_data.likes !== null) {
if (checkPostLikes($scope.content_data.likes, user_id)) {
$scope.liked = true;
} else {
$scope.liked = false;
}
}
}
});
$scope.retryLoadContent = function(){
var url = token_url;
var obj = serializeData({email: username, password: password, company_id: company_id});
$scope.isTimeout = false;
httpService.post_token($scope, $http, url, obj, 'content');
};
});
|
deepmacDetailCallback("cccc81000000/24",[{"d":"2012-05-18","t":"add","a":"D1,Huawei Industrial Base,Bantian,Longgang,Shenzhen\nShenZhen GuangDong 518129\n\n","c":"CHINA","o":"HUAWEI TECHNOLOGIES CO.,LTD"},{"d":"2013-03-27","t":"change","a":"D1-4,Huawei Industrial Base,Bantian,Longgang\nShenZhen GuangDong 518129\n\n","c":"CHINA","o":"HUAWEI TECHNOLOGIES CO.,LTD"},{"d":"2015-08-27","t":"change","a":"D1-4,Huawei Industrial Base,Bantian,Longgang ShenZhen GuangDong CN 518129","c":"CN","o":"HUAWEI TECHNOLOGIES CO.,LTD"}]);
|
/**
* To do: dedupe with nlz-build
*/
var program = require('commander')
program._name = 'nlz manifest'
program
.usage('[options] [entrypoints...]')
.option('-M, --no-min', 'do not calculate minified file sizes')
program.parse(process.argv)
var Options = require('normalize-rc')
var co = require('co')
var options = Options()
options.minifiedLength = program.min
var builder = require('../lib/builder')(program, options)
co(function* () {
yield* builder.build()
yield builder.await('manifest')
options.agent.close()
})()
|
const fs = require('fs')
const prettier = require('prettier')
const pkg = require('../package.json')
function read(filename) {
return fs.readFileSync(`${__dirname}/${filename}`, { encoding: 'utf8' })
}
function write(filename, data) {
return fs.writeFileSync(`${__dirname}/${filename}`, data)
}
// Start with the README
const header = '\n---\n\n## Documentation'
let data = read('../README.md').replace(new RegExp(header + '[\\w\\W]+'), '') + header
function redoLinks(data) {
return (
data
// Remove links that aren't links to source
.replace(/\[([^:]+)\]\(.*?\)/g, '$1')
.replace(/PanzoomOptions/g, '[PanzoomOptions](#PanzoomOptions)')
.replace(/PanOptions/g, '[PanOptions](#PanOptions)')
.replace(/ZoomOptions/g, '[ZoomOptions](#ZoomOptions)')
.replace(/PanzoomObject/g, '[PanzoomObject](#PanzoomObject)')
.replace(/CurrentValues/g, '[CurrentValues](#CurrentValues)')
)
}
const [constructor, defaultOptions] = redoLinks(read('../docs/modules/_panzoom_.md'))
// Remove unwanted text
.replace(/[\w\W]+###\s*Panzoom/, '')
.replace('## Object literals\n\n', '')
.replace('### ▪ **defaultOptions**: *object*\n\n', '')
.split('### `Const` defaultOptions')
data += constructor
const parsedDefaults = {}
defaultOptions.replace(/\*\*(\w+)\*\*: \*\w+\* = (["\w-\.]+)/g, function(all, key, value) {
parsedDefaults[key] = value
return all
})
const rProperties = /[\w\W]+##\s*Properties/
const rOptional = /`Optional` /g
const panzoomOptions =
'\n\n## `PanzoomOptions`\n\nIncludes `MiscOptions`, `PanOptions`, and `ZoomOptions`\n\n' +
redoLinks(read('../docs/interfaces/_types_.miscoptions.md'))
// Remove unwanted text
.replace(rOptional, '')
.replace(rProperties, '\n\n---\n\n## `MiscOptions`\n') +
redoLinks(read('../docs/interfaces/_types_.panspecificoptions.md'))
// Remove unwanted text
.replace(rOptional, '')
.replace(rProperties, '\n\n---\n\n## `PanOptions`\n\nIncludes `MiscOptions`\n\n') +
redoLinks(read('../docs/interfaces/_types_.zoomspecificoptions.md'))
// Remove unwanted text
.replace(rOptional, '')
.replace(rProperties, '\n\n---\n\n## `ZoomOptions`\n\nIncludes `MiscOptions`\n\n')
data += panzoomOptions
// Add in default values to option descriptions
.replace(/\*\*(\w+)\*\*\??\s*: \*\w+\*/g, function(all, key) {
return parsedDefaults[key] ? `${all} (Default: **${parsedDefaults[key]}**)` : all
})
const panzoomObject =
'\n\n---\n\n## `PanzoomObject`\n\nThese methods are available after initializing Panzoom\n\n' +
redoLinks(read('../docs/interfaces/_types_.panzoomobject.md'))
// Remove unwanted text
.replace(rProperties, '')
// Type declaration refers to the signature
.replace(/Type declaration:/g, 'Signature with return type:')
data += panzoomObject
// Add parens to method names
.replace(/([^#])\#\#\#\s*(\w+)/g, '$1### $2()')
const currentValues = read('../docs/interfaces/_types_.currentvalues.md')
// Remove unwanted text
.replace(rProperties, '\n\n---\n\n## `CurrentValues`\n')
data += currentValues + '\n'
const events = read('./EVENTS.md')
data += events
// Write a pretty version
write('../README.md', prettier.format(data, { ...pkg.prettier, parser: 'markdown' }))
|
import React, { PropTypes } from 'react';
class TitleSeparatorVert extends React.Component {
constructor(props) {
super(props)
this.state = props;
}
render() {
return (
<div className="titleSeparatorVert">
<div >
{this.state.text}
</div>
<div className="title">
{this.state.title}
</div>
</div>
);
}
}
TitleSeparatorVert.propTypes = {
text: PropTypes.string,
title: PropTypes.string,
};
export default TitleSeparatorVert;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SMALL_IMAGE = exports.copyCSSStyles = exports.distance = exports.contains = void 0;
var contains = function contains(bit, value) {
return (bit & value) !== 0;
};
exports.contains = contains;
var distance = function distance(a, b) {
return Math.sqrt(a * a + b * b);
};
exports.distance = distance;
var copyCSSStyles = function copyCSSStyles(style, target) {
// Edge does not provide value for cssText
for (var i = style.length - 1; i >= 0; i--) {
var property = style.item(i); // Safari shows pseudoelements if content is set
if (property !== 'content') {
target.style.setProperty(property, style.getPropertyValue(property));
}
}
return target;
};
exports.copyCSSStyles = copyCSSStyles;
var SMALL_IMAGE = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
exports.SMALL_IMAGE = SMALL_IMAGE;
|
var userInput;
var userName;
userInput = 5;
userInput = 'hello';
userName = 'liminjun';
if (typeof userInput === 'string') {
userName = userInput;
}
function generateError(message, code) {
throw { messsage: message, errorCode: code };
}
generateError('An error occurred!', 500);
|
const log4js = require('log4js');
const logger = log4js.getLogger('api');
logger.level = 'DEBUG';
module.exports = logger;
|
var searchData=
[
['simpleopregentry',['SimpleOpRegEntry',['../classmxnet_1_1op_1_1SimpleOpRegEntry.html',1,'mxnet::op']]],
['simpleopregistry',['SimpleOpRegistry',['../classmxnet_1_1op_1_1SimpleOpRegistry.html',1,'mxnet::op']]],
['storage',['Storage',['../classmxnet_1_1Storage.html',1,'mxnet']]]
];
|
Ext.define('KitchenSink.view.drag.FileController', {
extend: 'Ext.app.ViewController',
alias: 'controller.drag-file',
requires: ['Ext.drag.Target'],
afterRender: function(view) {
var body = view.body;
if (window.File && window.FileList && window.FileReader) {
this.target = new Ext.drag.Target({
element: body,
listeners: {
scope: this,
dragenter: this.onDragEnter,
dragleave: this.onDragLeave,
drop: this.onDrop
}
});
} else {
body.down('.drag-file-label').setHtml(
'File dragging is not supported by your browser'
);
body.el.addCls('nosupport');
}
},
onDragEnter: function() {
this.getView().body.addCls('active');
},
onDragLeave: function() {
this.getView().body.removeCls('active');
},
onDrop: function(target, info) {
var view = this.getView(),
body = view.body,
icon = body.down('.drag-file-icon');
body.removeCls('active').addCls('dropped');
icon.addCls('fa-spin');
var me = this,
files = info.files,
len = files.length,
s;
if (len > 1) {
s = 'Dropped ' + len + ' files.';
} else {
s = 'Dropped ' + files[0].name;
}
Ext.toast({
html: s,
closable: false,
align: 't',
slideInDuration: 400,
minWidth: 400
});
me.timer = setTimeout(function() {
if (!view.destroyed) {
icon.removeCls('fa-spin');
icon.fadeOut({
callback: function() {
body.removeCls('dropped');
icon.setOpacity(1);
icon.show();
}
});
}
me.timer = null;
}, 2000);
},
destroy: function() {
clearInterval(this.timer);
this.target = Ext.destroy(this.target);
this.callParent();
}
});
|
/*
Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'horizontalrule', 'ca', {
toolbar: 'Insereix línia horitzontal'
} );
|
module.exports = {
presets: [
[
'@babel/preset-env',
{
modules: false
}
],
'@babel/preset-typescript'
],
env: {
test: {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current'
}
}
],
'@babel/preset-typescript'
],
plugins: ['@babel/plugin-transform-modules-commonjs']
}
}
}
|
// .po file like language pack
plupload.addI18n({
'Select files' : 'Seleziona i files',
'Add files to the upload queue and click the start button.' : 'Aggiungi i file alla coda di caricamento e clicca il pulsante di avvio.',
'Filename' : 'Nome file',
'Status' : 'Stato',
'Size' : 'Dimensione',
'Add files' : 'Aggiungi file',
'Stop current upload' : 'Interrompi il caricamento',
'Start uploading queue' : 'Avvia il caricamento',
'Uploaded %d/%d files': 'Caricati %d/%d file',
'N/A' : 'N/D',
'Drag files here.' : 'Trascina i file qui.',
'File extension error.': 'Errore estensione file.',
'File size error.': 'Errore dimensione file.',
'Init error.': 'Errore inizializzazione.',
'HTTP Error.': 'Errore HTTP.',
'Security error.': 'Errore sicurezza.',
'Generic error.': 'Errore generico.',
'IO error.': 'Errore IO.'
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.