code
stringlengths 2
1.05M
|
|---|
import styled from 'styled-components'
const RulesContainer = styled.div`
text-align: justify;
h3 {
margin-bottom: 10px;
margin-left: 0;
}
.summary {
margin-left: 10px;
font-size: 10pt;
line-height: 13pt;
font-style: italic;
}
`
export default RulesContainer
|
/* eslint-disable */ 'use strict';
const chai = require('chai');
global.chaiAsPromised = require('chai-as-promised');
chai.should();
chai.use(chaiAsPromised);
global.expect = chai.expect;
global.AssertionError = chai.AssertionError;
global.Assertion = chai.Assertion;
global.assert = chai.assert;
|
/*!
* better-scroll / better-scroll
* (c) 2016-2020 ustbhuangyi
* Released under the MIT License.
*/
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function warn(msg) {
console.error("[BScroll warn]: " + msg);
}
// ssr support
var inBrowser = typeof window !== 'undefined';
var ua = inBrowser && navigator.userAgent.toLowerCase();
var isWeChatDevTools = ua && /wechatdevtools/.test(ua);
var isAndroid = ua && ua.indexOf('android') > 0;
function getNow() {
return window.performance && window.performance.now && window.performance.timing
? window.performance.now() + window.performance.timing.navigationStart
: +new Date();
}
function extend(target) {
var rest = [];
for (var _i = 1; _i < arguments.length; _i++) {
rest[_i - 1] = arguments[_i];
}
for (var i = 0; i < rest.length; i++) {
var source = rest[i];
for (var key in source) {
target[key] = source[key];
}
}
return target;
}
function isUndef(v) {
return v === undefined || v === null;
}
function isPlainObject(v) {
return typeof v === 'object' && v !== null;
}
function getDistance(x, y) {
return Math.sqrt(x * x + y * y);
}
function fixInboundValue(x, min, max) {
if (x < min) {
return min;
}
if (x > max) {
return max;
}
return x;
}
var elementStyle = (inBrowser &&
document.createElement('div').style);
var vendor = (function () {
if (!inBrowser) {
return false;
}
var transformNames = {
webkit: 'webkitTransform',
Moz: 'MozTransform',
O: 'OTransform',
ms: 'msTransform',
standard: 'transform'
};
for (var key in transformNames) {
if (elementStyle[transformNames[key]] !== undefined) {
return key;
}
}
return false;
})();
function prefixStyle(style) {
if (vendor === false) {
return style;
}
if (vendor === 'standard') {
if (style === 'transitionEnd') {
return 'transitionend';
}
return style;
}
return vendor + style.charAt(0).toUpperCase() + style.substr(1);
}
function getElement(el) {
return (typeof el === 'string'
? document.querySelector(el)
: el);
}
function addEvent(el, type, fn, capture) {
el.addEventListener(type, fn, {
passive: false,
capture: !!capture
});
}
function removeEvent(el, type, fn, capture) {
el.removeEventListener(type, fn, {
capture: !!capture
});
}
function offset(el) {
var left = 0;
var top = 0;
while (el) {
left -= el.offsetLeft;
top -= el.offsetTop;
el = el.offsetParent;
}
return {
left: left,
top: top
};
}
function offsetToBody(el) {
var rect = el.getBoundingClientRect();
return {
left: -(rect.left + window.pageXOffset),
top: -(rect.top + window.pageYOffset)
};
}
var cssVendor = vendor && vendor !== 'standard' ? '-' + vendor.toLowerCase() + '-' : '';
var transform = prefixStyle('transform');
var transition = prefixStyle('transition');
var hasPerspective = inBrowser && prefixStyle('perspective') in elementStyle;
// fix issue #361
var hasTouch = inBrowser && ('ontouchstart' in window || isWeChatDevTools);
var hasTransition = inBrowser && transition in elementStyle;
var style = {
transform: transform,
transition: transition,
transitionTimingFunction: prefixStyle('transitionTimingFunction'),
transitionDuration: prefixStyle('transitionDuration'),
transitionDelay: prefixStyle('transitionDelay'),
transformOrigin: prefixStyle('transformOrigin'),
transitionEnd: prefixStyle('transitionEnd')
};
var eventTypeMap = {
touchstart: 1,
touchmove: 1,
touchend: 1,
mousedown: 2,
mousemove: 2,
mouseup: 2
};
function getRect(el) {
if (el instanceof window.SVGElement) {
var rect = el.getBoundingClientRect();
return {
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height
};
}
else {
return {
top: el.offsetTop,
left: el.offsetLeft,
width: el.offsetWidth,
height: el.offsetHeight
};
}
}
function preventDefaultExceptionFn(el, exceptions) {
for (var i in exceptions) {
if (exceptions[i].test(el[i])) {
return true;
}
}
return false;
}
var tagExceptionFn = preventDefaultExceptionFn;
function tap(e, eventName) {
var ev = document.createEvent('Event');
ev.initEvent(eventName, true, true);
ev.pageX = e.pageX;
ev.pageY = e.pageY;
e.target.dispatchEvent(ev);
}
function click(e, event) {
if (event === void 0) { event = 'click'; }
var eventSource;
if (e.type === 'mouseup') {
eventSource = e;
}
else if (e.type === 'touchend' || e.type === 'touchcancel') {
eventSource = e.changedTouches[0];
}
var posSrc = {};
if (eventSource) {
posSrc.screenX = eventSource.screenX || 0;
posSrc.screenY = eventSource.screenY || 0;
posSrc.clientX = eventSource.clientX || 0;
posSrc.clientY = eventSource.clientY || 0;
}
var ev;
var bubbles = true;
var cancelable = true;
if (typeof MouseEvent !== 'undefined') {
try {
ev = new MouseEvent(event, extend({
bubbles: bubbles,
cancelable: cancelable
}, posSrc));
}
catch (e) {
createEvent();
}
}
else {
createEvent();
}
function createEvent() {
ev = document.createEvent('Event');
ev.initEvent(event, bubbles, cancelable);
extend(ev, posSrc);
}
// forwardedTouchEvent set to true in case of the conflict with fastclick
ev.forwardedTouchEvent = true;
ev._constructed = true;
e.target.dispatchEvent(ev);
}
function dblclick(e) {
click(e, 'dblclick');
}
function prepend(el, target) {
var firstChild = target.firstChild;
if (firstChild) {
before(el, firstChild);
}
else {
target.appendChild(el);
}
}
function before(el, target) {
target.parentNode.insertBefore(el, target);
}
function removeChild(el, child) {
el.removeChild(child);
}
function hasClass(el, className) {
var reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
return reg.test(el.className);
}
var ease = {
// easeOutQuint
swipe: {
style: 'cubic-bezier(0.23, 1, 0.32, 1)',
fn: function (t) {
return 1 + --t * t * t * t * t;
}
},
// easeOutQuard
swipeBounce: {
style: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
fn: function (t) {
return t * (2 - t);
}
},
// easeOutQuart
bounce: {
style: 'cubic-bezier(0.165, 0.84, 0.44, 1)',
fn: function (t) {
return 1 - --t * t * t * t;
}
}
};
var DEFAULT_INTERVAL = 100 / 60;
var windowCompat = inBrowser && window;
function noop() { }
var requestAnimationFrame = (function () {
if (!inBrowser) {
/* istanbul ignore if */
return noop;
}
return (windowCompat.requestAnimationFrame ||
windowCompat.webkitRequestAnimationFrame ||
windowCompat.mozRequestAnimationFrame ||
windowCompat.oRequestAnimationFrame ||
// if all else fails, use setTimeout
function (callback) {
return window.setTimeout(callback, (callback.interval || DEFAULT_INTERVAL) / 2); // make interval as precise as possible.
});
})();
var cancelAnimationFrame = (function () {
if (!inBrowser) {
/* istanbul ignore if */
return noop;
}
return (windowCompat.cancelAnimationFrame ||
windowCompat.webkitCancelAnimationFrame ||
windowCompat.mozCancelAnimationFrame ||
windowCompat.oCancelAnimationFrame ||
function (id) {
window.clearTimeout(id);
});
})();
var noop$1 = function (val) { };
var sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop$1,
set: noop$1
};
var getProperty = function (obj, key) {
var keys = key.split('.');
for (var i = 0; i < keys.length - 1; i++) {
obj = obj[keys[i]];
if (typeof obj !== 'object' || !obj)
return;
}
var lastKey = keys.pop();
if (typeof obj[lastKey] === 'function') {
return function () {
return obj[lastKey].apply(obj, arguments);
};
}
else {
return obj[lastKey];
}
};
var setProperty = function (obj, key, value) {
var keys = key.split('.');
var temp;
for (var i = 0; i < keys.length - 1; i++) {
temp = keys[i];
if (!obj[temp])
obj[temp] = {};
obj = obj[temp];
}
obj[keys.pop()] = value;
};
function propertiesProxy(target, sourceKey, key) {
sharedPropertyDefinition.get = function proxyGetter() {
return getProperty(this, sourceKey);
};
sharedPropertyDefinition.set = function proxySetter(val) {
setProperty(this, sourceKey, val);
};
Object.defineProperty(target, key, sharedPropertyDefinition);
}
var EventEmitter = /** @class */ (function () {
function EventEmitter(names) {
this.events = {};
this.eventTypes = {};
this.registerType(names);
}
EventEmitter.prototype.on = function (type, fn, context) {
if (context === void 0) { context = this; }
this.hasType(type);
if (!this.events[type]) {
this.events[type] = [];
}
this.events[type].push([fn, context]);
return this;
};
EventEmitter.prototype.once = function (type, fn, context) {
var _this = this;
if (context === void 0) { context = this; }
this.hasType(type);
var magic = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
_this.off(type, magic);
fn.apply(context, args);
};
magic.fn = fn;
this.on(type, magic);
return this;
};
EventEmitter.prototype.off = function (type, fn) {
if (!type && !fn) {
this.events = {};
return this;
}
if (type) {
this.hasType(type);
if (!fn) {
this.events[type] = [];
return this;
}
var events = this.events[type];
if (!events) {
return this;
}
var count = events.length;
while (count--) {
if (events[count][0] === fn ||
(events[count][0] && events[count][0].fn === fn)) {
events.splice(count, 1);
}
}
return this;
}
};
EventEmitter.prototype.trigger = function (type) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
this.hasType(type);
var events = this.events[type];
if (!events) {
return;
}
var len = events.length;
var eventsCopy = events.slice();
var ret;
for (var i = 0; i < len; i++) {
var event_1 = eventsCopy[i];
var fn = event_1[0], context = event_1[1];
if (fn) {
ret = fn.apply(context, args);
if (ret === true) {
return ret;
}
}
}
};
EventEmitter.prototype.registerType = function (names) {
var _this = this;
names.forEach(function (type) {
_this.eventTypes[type] = type;
});
};
EventEmitter.prototype.destroy = function () {
this.events = {};
this.eventTypes = {};
};
EventEmitter.prototype.hasType = function (type) {
var types = this.eventTypes;
var isType = types[type] === type;
if (!isType) {
warn("EventEmitter has used unknown event type: \"" + type + "\", should be oneof [" +
("" + Object.keys(types).map(function (_) { return JSON.stringify(_); })) +
"]");
}
};
return EventEmitter;
}());
var EventRegister = /** @class */ (function () {
function EventRegister(wrapper, events) {
this.wrapper = wrapper;
this.events = events;
this.addDOMEvents();
}
EventRegister.prototype.destroy = function () {
this.removeDOMEvents();
this.events = [];
};
EventRegister.prototype.addDOMEvents = function () {
this.handleDOMEvents(addEvent);
};
EventRegister.prototype.removeDOMEvents = function () {
this.handleDOMEvents(removeEvent);
};
EventRegister.prototype.handleDOMEvents = function (eventOperation) {
var _this = this;
var wrapper = this.wrapper;
this.events.forEach(function (event) {
eventOperation(wrapper, event.name, _this, !!event.capture);
});
};
EventRegister.prototype.handleEvent = function (e) {
var eventType = e.type;
this.events.some(function (event) {
if (event.name === eventType) {
event.handler(e);
return true;
}
return false;
});
};
return EventRegister;
}());
var Options = /** @class */ (function () {
function Options() {
this.startX = 0;
this.startY = 0;
this.scrollX = false;
this.scrollY = true;
this.freeScroll = false;
this.directionLockThreshold = 5;
this.eventPassthrough = "" /* None */;
this.click = false;
this.dblclick = false;
this.tap = '';
this.bounce = {
top: true,
bottom: true,
left: true,
right: true
};
this.bounceTime = 800;
this.momentum = true;
this.momentumLimitTime = 300;
this.momentumLimitDistance = 15;
this.swipeTime = 2500;
this.swipeBounceTime = 500;
this.deceleration = 0.0015;
this.flickLimitTime = 200;
this.flickLimitDistance = 100;
this.resizePolling = 60;
this.probeType = 0 /* Default */;
this.stopPropagation = false;
this.preventDefault = true;
this.preventDefaultException = {
tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|AUDIO)$/
};
this.tagException = {
tagName: /^TEXTAREA$/
};
this.HWCompositing = true;
this.useTransition = true;
this.bindToWrapper = false;
this.disableMouse = hasTouch;
this.disableTouch = !hasTouch;
this.autoBlur = true;
}
Options.prototype.merge = function (options) {
if (!options)
return this;
for (var key in options) {
this[key] = options[key];
}
return this;
};
Options.prototype.process = function () {
this.translateZ =
this.HWCompositing && hasPerspective ? ' translateZ(0)' : '';
this.useTransition = this.useTransition && hasTransition;
this.preventDefault = !this.eventPassthrough && this.preventDefault;
this.resolveBounce();
// If you want eventPassthrough I have to lock one of the axes
this.scrollX =
this.eventPassthrough === "horizontal" /* Horizontal */
? false
: this.scrollX;
this.scrollY =
this.eventPassthrough === "vertical" /* Vertical */ ? false : this.scrollY;
// With eventPassthrough we also need lockDirection mechanism
this.freeScroll = this.freeScroll && !this.eventPassthrough;
// force true when freeScroll is true
this.scrollX = this.freeScroll ? true : this.scrollX;
this.scrollY = this.freeScroll ? true : this.scrollY;
this.directionLockThreshold = this.eventPassthrough
? 0
: this.directionLockThreshold;
return this;
};
Options.prototype.resolveBounce = function () {
var directions = ['top', 'right', 'bottom', 'left'];
var bounce = this.bounce;
if (bounce === false || bounce === true) {
this.bounce = makeMap(directions, bounce);
}
};
return Options;
}());
function makeMap(keys, val) {
if (val === void 0) { val = true; }
var ret = {};
keys.forEach(function (key) {
ret[key] = val;
});
return ret;
}
var ActionsHandler = /** @class */ (function () {
function ActionsHandler(wrapper, options) {
this.wrapper = wrapper;
this.options = options;
this.hooks = new EventEmitter([
'beforeStart',
'start',
'move',
'end',
'click'
]);
this.handleDOMEvents();
}
ActionsHandler.prototype.handleDOMEvents = function () {
var _a = this.options, bindToWrapper = _a.bindToWrapper, disableMouse = _a.disableMouse, disableTouch = _a.disableTouch, click = _a.click;
var wrapper = this.wrapper;
var target = bindToWrapper ? wrapper : window;
var wrapperEvents = [];
var targetEvents = [];
var shouldRegisterTouch = hasTouch && !disableTouch;
var shouldRegisterMouse = !disableMouse;
if (click) {
wrapperEvents.push({
name: 'click',
handler: this.click.bind(this),
capture: true
});
}
if (shouldRegisterTouch) {
wrapperEvents.push({
name: 'touchstart',
handler: this.start.bind(this)
});
targetEvents.push({
name: 'touchmove',
handler: this.move.bind(this)
}, {
name: 'touchend',
handler: this.end.bind(this)
}, {
name: 'touchcancel',
handler: this.end.bind(this)
});
}
if (shouldRegisterMouse) {
wrapperEvents.push({
name: 'mousedown',
handler: this.start.bind(this)
});
targetEvents.push({
name: 'mousemove',
handler: this.move.bind(this)
}, {
name: 'mouseup',
handler: this.end.bind(this)
});
}
this.wrapperEventRegister = new EventRegister(wrapper, wrapperEvents);
this.targetEventRegister = new EventRegister(target, targetEvents);
};
ActionsHandler.prototype.beforeHandler = function (e, type) {
var _a = this.options, preventDefault = _a.preventDefault, stopPropagation = _a.stopPropagation, preventDefaultException = _a.preventDefaultException;
var preventDefaultConditions = {
start: function () {
return (preventDefault &&
!preventDefaultExceptionFn(e.target, preventDefaultException));
},
end: function () {
return (preventDefault &&
!preventDefaultExceptionFn(e.target, preventDefaultException));
},
move: function () {
return preventDefault;
}
};
if (preventDefaultConditions[type]()) {
e.preventDefault();
}
if (stopPropagation) {
e.stopPropagation();
}
};
ActionsHandler.prototype.setInitiated = function (type) {
if (type === void 0) { type = 0; }
this.initiated = type;
};
ActionsHandler.prototype.start = function (e) {
var _eventType = eventTypeMap[e.type];
if (this.initiated && this.initiated !== _eventType) {
return;
}
this.setInitiated(_eventType);
// if textarea or other html tags in options.tagException is manipulated
// do not make bs scroll
if (tagExceptionFn(e.target, this.options.tagException)) {
this.setInitiated();
return;
}
// no mouse left button
if (_eventType === 2 /* Mouse */ && e.button !== 0 /* Left */)
return;
if (this.hooks.trigger(this.hooks.eventTypes.beforeStart, e)) {
return;
}
this.beforeHandler(e, 'start');
var point = (e.touches ? e.touches[0] : e);
this.pointX = point.pageX;
this.pointY = point.pageY;
this.hooks.trigger(this.hooks.eventTypes.start, e);
};
ActionsHandler.prototype.move = function (e) {
if (eventTypeMap[e.type] !== this.initiated) {
return;
}
this.beforeHandler(e, 'move');
var point = (e.touches ? e.touches[0] : e);
var deltaX = point.pageX - this.pointX;
var deltaY = point.pageY - this.pointY;
this.pointX = point.pageX;
this.pointY = point.pageY;
if (this.hooks.trigger(this.hooks.eventTypes.move, {
deltaX: deltaX,
deltaY: deltaY,
e: e
})) {
return;
}
// auto end when out of wrapper
var scrollLeft = document.documentElement.scrollLeft ||
window.pageXOffset ||
document.body.scrollLeft;
var scrollTop = document.documentElement.scrollTop ||
window.pageYOffset ||
document.body.scrollTop;
var pX = this.pointX - scrollLeft;
var pY = this.pointY - scrollTop;
if (pX >
document.documentElement.clientWidth -
this.options.momentumLimitDistance ||
pX < this.options.momentumLimitDistance ||
pY < this.options.momentumLimitDistance ||
pY >
document.documentElement.clientHeight -
this.options.momentumLimitDistance) {
this.end(e);
}
};
ActionsHandler.prototype.end = function (e) {
if (eventTypeMap[e.type] !== this.initiated) {
return;
}
this.setInitiated();
this.beforeHandler(e, 'end');
this.hooks.trigger(this.hooks.eventTypes.end, e);
};
ActionsHandler.prototype.click = function (e) {
this.hooks.trigger(this.hooks.eventTypes.click, e);
};
ActionsHandler.prototype.destroy = function () {
this.wrapperEventRegister.destroy();
this.targetEventRegister.destroy();
this.hooks.destroy();
};
return ActionsHandler;
}());
var translaterMetaData = {
x: ['translateX', 'px'],
y: ['translateY', 'px']
};
var Translater = /** @class */ (function () {
function Translater(content) {
this.content = content;
this.style = content.style;
this.hooks = new EventEmitter(['beforeTranslate', 'translate']);
}
Translater.prototype.getComputedPosition = function () {
var cssStyle = window.getComputedStyle(this.content, null);
var matrix = cssStyle[style.transform].split(')')[0].split(', ');
var x = +(matrix[12] || matrix[4]);
var y = +(matrix[13] || matrix[5]);
return {
x: x,
y: y
};
};
Translater.prototype.translate = function (point) {
var transformStyle = [];
Object.keys(point).forEach(function (key) {
if (!translaterMetaData[key]) {
return;
}
var transformFnName = translaterMetaData[key][0];
if (transformFnName) {
var transformFnArgUnit = translaterMetaData[key][1];
var transformFnArg = point[key];
transformStyle.push(transformFnName + "(" + transformFnArg + transformFnArgUnit + ")");
}
});
this.hooks.trigger(this.hooks.eventTypes.beforeTranslate, transformStyle, point);
this.style[style.transform] = transformStyle.join(' ');
this.hooks.trigger(this.hooks.eventTypes.translate, point);
};
Translater.prototype.destroy = function () {
this.hooks.destroy();
};
return Translater;
}());
var Base = /** @class */ (function () {
function Base(content, translater, options) {
this.content = content;
this.translater = translater;
this.options = options;
this.hooks = new EventEmitter([
'move',
'end',
'beforeForceStop',
'forceStop',
'time',
'timeFunction'
]);
this.style = content.style;
}
Base.prototype.translate = function (endPoint) {
this.translater.translate(endPoint);
};
Base.prototype.setPending = function (pending) {
this.pending = pending;
};
Base.prototype.setForceStopped = function (forceStopped) {
this.forceStopped = forceStopped;
};
Base.prototype.destroy = function () {
this.hooks.destroy();
cancelAnimationFrame(this.timer);
};
return Base;
}());
var Transition = /** @class */ (function (_super) {
__extends(Transition, _super);
function Transition() {
return _super !== null && _super.apply(this, arguments) || this;
}
Transition.prototype.startProbe = function () {
var _this = this;
var probe = function () {
var pos = _this.translater.getComputedPosition();
_this.hooks.trigger(_this.hooks.eventTypes.move, pos);
// excute when transition ends
if (!_this.pending) {
_this.hooks.trigger(_this.hooks.eventTypes.end, pos);
return;
}
_this.timer = requestAnimationFrame(probe);
};
cancelAnimationFrame(this.timer);
this.timer = requestAnimationFrame(probe);
};
Transition.prototype.transitionTime = function (time) {
if (time === void 0) { time = 0; }
this.style[style.transitionDuration] = time + 'ms';
this.hooks.trigger(this.hooks.eventTypes.time, time);
};
Transition.prototype.transitionTimingFunction = function (easing) {
this.style[style.transitionTimingFunction] = easing;
this.hooks.trigger(this.hooks.eventTypes.timeFunction, easing);
};
Transition.prototype.move = function (startPoint, endPoint, time, easingFn, isSlient) {
this.setPending(time > 0 && (startPoint.x !== endPoint.x || startPoint.y !== endPoint.y));
this.transitionTimingFunction(easingFn);
this.transitionTime(time);
this.translate(endPoint);
if (time && this.options.probeType === 3 /* Realtime */) {
this.startProbe();
}
// if we change content's transformY in a tick
// such as: 0 -> 50px -> 0
// transitionend will not be triggered
// so we forceupdate by reflow
if (!time) {
this._reflow = this.content.offsetHeight;
}
// no need to dispatch move and end when slient
if (!time && !isSlient) {
this.hooks.trigger(this.hooks.eventTypes.move, endPoint);
this.hooks.trigger(this.hooks.eventTypes.end, endPoint);
}
};
Transition.prototype.stop = function () {
// still in transition
if (this.pending) {
this.setPending(false);
cancelAnimationFrame(this.timer);
var _a = this.translater.getComputedPosition(), x = _a.x, y = _a.y;
this.transitionTime();
this.translate({ x: x, y: y });
this.setForceStopped(true);
if (this.hooks.trigger(this.hooks.eventTypes.beforeForceStop, { x: x, y: y })) {
return;
}
this.hooks.trigger(this.hooks.eventTypes.forceStop, { x: x, y: y });
}
};
return Transition;
}(Base));
var Animation = /** @class */ (function (_super) {
__extends(Animation, _super);
function Animation() {
return _super !== null && _super.apply(this, arguments) || this;
}
Animation.prototype.move = function (startPoint, endPoint, time, easingFn, isSlient) {
// time is 0
if (!time) {
this.translate(endPoint);
// if we change content's transformY in a tick
// such as: 0 -> 50px -> 0
// transitionend will not be triggered
// so we forceupdate by reflow
this._reflow = this.content.offsetHeight;
// no need to dispatch move and end when slient
if (isSlient)
return;
this.hooks.trigger(this.hooks.eventTypes.move, endPoint);
this.hooks.trigger(this.hooks.eventTypes.end, endPoint);
return;
}
this.animate(startPoint, endPoint, time, easingFn);
};
Animation.prototype.animate = function (startPoint, endPoint, duration, easingFn) {
var _this = this;
var startTime = getNow();
var destTime = startTime + duration;
var step = function () {
var now = getNow();
// js animation end
if (now >= destTime) {
_this.translate(endPoint);
_this.hooks.trigger(_this.hooks.eventTypes.move, endPoint);
_this.hooks.trigger(_this.hooks.eventTypes.end, endPoint);
return;
}
now = (now - startTime) / duration;
var easing = easingFn(now);
var newPoint = {};
Object.keys(endPoint).forEach(function (key) {
var startValue = startPoint[key];
var endValue = endPoint[key];
newPoint[key] = (endValue - startValue) * easing + startValue;
});
_this.translate(newPoint);
if (_this.pending) {
_this.timer = requestAnimationFrame(step);
}
if (_this.options.probeType === 3 /* Realtime */) {
_this.hooks.trigger(_this.hooks.eventTypes.move, newPoint);
}
};
this.setPending(true);
cancelAnimationFrame(this.timer);
step();
};
Animation.prototype.stop = function () {
// still in requestFrameAnimation
if (this.pending) {
this.setPending(false);
cancelAnimationFrame(this.timer);
var pos = this.translater.getComputedPosition();
this.setForceStopped(true);
if (this.hooks.trigger(this.hooks.eventTypes.beforeForceStop, pos)) {
return;
}
this.hooks.trigger(this.hooks.eventTypes.forceStop, pos);
}
};
return Animation;
}(Base));
function createAnimater(element, translater, options) {
var useTransition = options.useTransition;
var animaterOptions = {};
Object.defineProperty(animaterOptions, 'probeType', {
enumerable: true,
configurable: false,
get: function () {
return options.probeType;
}
});
if (useTransition) {
return new Transition(element, translater, animaterOptions);
}
else {
return new Animation(element, translater, animaterOptions);
}
}
var Behavior = /** @class */ (function () {
function Behavior(wrapper, options) {
this.wrapper = wrapper;
this.options = options;
this.hooks = new EventEmitter(['momentum', 'end']);
this.content = this.wrapper.children[0];
this.currentPos = 0;
this.startPos = 0;
}
Behavior.prototype.start = function () {
this.direction = 0 /* Default */;
this.movingDirection = 0 /* Default */;
this.dist = 0;
};
Behavior.prototype.move = function (delta) {
delta = this.hasScroll ? delta : 0;
this.movingDirection =
delta > 0
? -1 /* Negative */
: delta < 0
? 1 /* Positive */
: 0 /* Default */;
var newPos = this.currentPos + delta;
// Slow down or stop if outside of the boundaries
if (newPos > this.minScrollPos || newPos < this.maxScrollPos) {
if ((newPos > this.minScrollPos && this.options.bounces[0]) ||
(newPos < this.maxScrollPos && this.options.bounces[1])) {
newPos = this.currentPos + delta / 3;
}
else {
newPos =
newPos > this.minScrollPos ? this.minScrollPos : this.maxScrollPos;
}
}
return newPos;
};
Behavior.prototype.end = function (duration) {
var momentumInfo = {
duration: 0
};
var absDist = Math.abs(this.currentPos - this.startPos);
// start momentum animation if needed
if (this.options.momentum &&
duration < this.options.momentumLimitTime &&
absDist > this.options.momentumLimitDistance) {
var wrapperSize = (this.direction === -1 /* Negative */ && this.options.bounces[0]) ||
(this.direction === 1 /* Positive */ && this.options.bounces[1])
? this.wrapperSize
: 0;
momentumInfo = this.hasScroll
? this.momentum(this.currentPos, this.startPos, duration, this.maxScrollPos, this.minScrollPos, wrapperSize, this.options)
: { destination: this.currentPos, duration: 0 };
}
else {
this.hooks.trigger(this.hooks.eventTypes.end, momentumInfo);
}
return momentumInfo;
};
Behavior.prototype.momentum = function (current, start, time, lowerMargin, upperMargin, wrapperSize, options) {
if (options === void 0) { options = this.options; }
var distance = current - start;
var speed = Math.abs(distance) / time;
var deceleration = options.deceleration, swipeBounceTime = options.swipeBounceTime, swipeTime = options.swipeTime;
var momentumData = {
destination: current + (speed / deceleration) * (distance < 0 ? -1 : 1),
duration: swipeTime,
rate: 15
};
this.hooks.trigger(this.hooks.eventTypes.momentum, momentumData, distance);
if (momentumData.destination < lowerMargin) {
momentumData.destination = wrapperSize
? Math.max(lowerMargin - wrapperSize / 4, lowerMargin - (wrapperSize / momentumData.rate) * speed)
: lowerMargin;
momentumData.duration = swipeBounceTime;
}
else if (momentumData.destination > upperMargin) {
momentumData.destination = wrapperSize
? Math.min(upperMargin + wrapperSize / 4, upperMargin + (wrapperSize / momentumData.rate) * speed)
: upperMargin;
momentumData.duration = swipeBounceTime;
}
momentumData.destination = Math.round(momentumData.destination);
return momentumData;
};
Behavior.prototype.updateDirection = function () {
var absDist = Math.round(this.currentPos) - this.absStartPos;
this.direction =
absDist > 0
? -1 /* Negative */
: absDist < 0
? 1 /* Positive */
: 0 /* Default */;
};
Behavior.prototype.refresh = function () {
var _a = this.options.rect, size = _a.size, position = _a.position;
var isWrapperStatic = window.getComputedStyle(this.wrapper, null).position === 'static';
var wrapperRect = getRect(this.wrapper);
this.wrapperSize = wrapperRect[size];
var contentRect = getRect(this.content);
this.contentSize = contentRect[size];
this.relativeOffset = contentRect[position];
if (isWrapperStatic) {
this.relativeOffset -= wrapperRect[position];
}
this.minScrollPos = 0;
this.maxScrollPos = this.wrapperSize - this.contentSize;
if (this.maxScrollPos < 0) {
this.maxScrollPos -= this.relativeOffset;
this.minScrollPos = -this.relativeOffset;
}
this.hasScroll =
this.options.scrollable && this.maxScrollPos < this.minScrollPos;
if (!this.hasScroll) {
this.maxScrollPos = this.minScrollPos;
this.contentSize = this.wrapperSize;
}
this.direction = 0;
};
Behavior.prototype.updatePosition = function (pos) {
this.currentPos = pos;
};
Behavior.prototype.getCurrentPos = function () {
return Math.round(this.currentPos);
};
Behavior.prototype.checkInBoundary = function () {
var position = this.adjustPosition(this.currentPos);
var inBoundary = position === this.getCurrentPos();
return {
position: position,
inBoundary: inBoundary
};
};
// adjust position when out of boundary
Behavior.prototype.adjustPosition = function (pos) {
var roundPos = Math.round(pos);
if (!this.hasScroll || roundPos > this.minScrollPos) {
roundPos = this.minScrollPos;
}
else if (roundPos < this.maxScrollPos) {
roundPos = this.maxScrollPos;
}
return roundPos;
};
Behavior.prototype.updateStartPos = function () {
this.startPos = this.currentPos;
};
Behavior.prototype.updateAbsStartPos = function () {
this.absStartPos = this.currentPos;
};
Behavior.prototype.resetStartPos = function () {
this.updateStartPos();
this.updateAbsStartPos();
};
Behavior.prototype.getAbsDist = function (delta) {
this.dist += delta;
return Math.abs(this.dist);
};
Behavior.prototype.destroy = function () {
this.hooks.destroy();
};
return Behavior;
}());
var _a, _b, _c, _d;
var PassthroughHandlers = (_a = {},
_a["yes" /* Yes */] = function (e) {
return true;
},
_a["no" /* No */] = function (e) {
e.preventDefault();
return false;
},
_a);
var DirectionMap = (_b = {},
_b["horizontal" /* Horizontal */] = (_c = {},
_c["yes" /* Yes */] = "horizontal" /* Horizontal */,
_c["no" /* No */] = "vertical" /* Vertical */,
_c),
_b["vertical" /* Vertical */] = (_d = {},
_d["yes" /* Yes */] = "vertical" /* Vertical */,
_d["no" /* No */] = "horizontal" /* Horizontal */,
_d),
_b);
var DirectionLockAction = /** @class */ (function () {
function DirectionLockAction(directionLockThreshold, freeScroll, eventPassthrough) {
this.directionLockThreshold = directionLockThreshold;
this.freeScroll = freeScroll;
this.eventPassthrough = eventPassthrough;
this.reset();
}
DirectionLockAction.prototype.reset = function () {
this.directionLocked = "" /* Default */;
};
DirectionLockAction.prototype.checkMovingDirection = function (absDistX, absDistY, e) {
this.computeDirectionLock(absDistX, absDistY);
return this.handleEventPassthrough(e);
};
DirectionLockAction.prototype.adjustDelta = function (deltaX, deltaY) {
if (this.directionLocked === "horizontal" /* Horizontal */) {
deltaY = 0;
}
else if (this.directionLocked === "vertical" /* Vertical */) {
deltaX = 0;
}
return {
deltaX: deltaX,
deltaY: deltaY
};
};
DirectionLockAction.prototype.computeDirectionLock = function (absDistX, absDistY) {
// If you are scrolling in one direction, lock it
if (this.directionLocked === "" /* Default */ && !this.freeScroll) {
if (absDistX > absDistY + this.directionLockThreshold) {
this.directionLocked = "horizontal" /* Horizontal */; // lock horizontally
}
else if (absDistY >= absDistX + this.directionLockThreshold) {
this.directionLocked = "vertical" /* Vertical */; // lock vertically
}
else {
this.directionLocked = "none" /* None */; // no lock
}
}
};
DirectionLockAction.prototype.handleEventPassthrough = function (e) {
var handleMap = DirectionMap[this.directionLocked];
if (handleMap) {
if (this.eventPassthrough === handleMap["yes" /* Yes */]) {
return PassthroughHandlers["yes" /* Yes */](e);
}
else if (this.eventPassthrough === handleMap["no" /* No */]) {
return PassthroughHandlers["no" /* No */](e);
}
}
return false;
};
return DirectionLockAction;
}());
var ScrollerActions = /** @class */ (function () {
function ScrollerActions(scrollBehaviorX, scrollBehaviorY, actionsHandler, animater, options) {
this.hooks = new EventEmitter([
'start',
'beforeMove',
'scrollStart',
'scroll',
'beforeEnd',
'end',
'scrollEnd'
]);
this.scrollBehaviorX = scrollBehaviorX;
this.scrollBehaviorY = scrollBehaviorY;
this.actionsHandler = actionsHandler;
this.animater = animater;
this.options = options;
this.directionLockAction = new DirectionLockAction(options.directionLockThreshold, options.freeScroll, options.eventPassthrough);
this.enabled = true;
this.bindActionsHandler();
}
ScrollerActions.prototype.bindActionsHandler = function () {
var _this = this;
// [mouse|touch]start event
this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.start, function (e) {
if (!_this.enabled)
return true;
return _this.handleStart(e);
});
// [mouse|touch]move event
this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.move, function (_a) {
var deltaX = _a.deltaX, deltaY = _a.deltaY, e = _a.e;
if (!_this.enabled)
return true;
return _this.handleMove(deltaX, deltaY, e);
});
// [mouse|touch]end event
this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.end, function (e) {
if (!_this.enabled)
return true;
return _this.handleEnd(e);
});
// click
this.actionsHandler.hooks.on(this.actionsHandler.hooks.eventTypes.click, function (e) {
// handle native click event
if (_this.enabled && !e._constructed) {
_this.handleClick(e);
}
});
};
ScrollerActions.prototype.handleStart = function (e) {
var timestamp = getNow();
this.moved = false;
this.startTime = timestamp;
this.directionLockAction.reset();
this.scrollBehaviorX.start();
this.scrollBehaviorY.start();
// force stopping last transition or animation
this.animater.stop();
this.scrollBehaviorX.resetStartPos();
this.scrollBehaviorY.resetStartPos();
this.hooks.trigger(this.hooks.eventTypes.start, e);
};
ScrollerActions.prototype.handleMove = function (deltaX, deltaY, e) {
if (this.hooks.trigger(this.hooks.eventTypes.beforeMove, e)) {
return;
}
var absDistX = this.scrollBehaviorX.getAbsDist(deltaX);
var absDistY = this.scrollBehaviorY.getAbsDist(deltaY);
var timestamp = getNow();
// We need to move at least momentumLimitDistance pixels
// for the scrolling to initiate
if (this.checkMomentum(absDistX, absDistY, timestamp)) {
return true;
}
if (this.directionLockAction.checkMovingDirection(absDistX, absDistY, e)) {
this.actionsHandler.setInitiated();
return true;
}
var delta = this.directionLockAction.adjustDelta(deltaX, deltaY);
var newX = this.scrollBehaviorX.move(delta.deltaX);
var newY = this.scrollBehaviorY.move(delta.deltaY);
if (!this.moved) {
this.moved = true;
this.hooks.trigger(this.hooks.eventTypes.scrollStart);
}
this.animater.translate({
x: newX,
y: newY
});
this.dispatchScroll(timestamp);
};
ScrollerActions.prototype.dispatchScroll = function (timestamp) {
// dispatch scroll in interval time
if (timestamp - this.startTime > this.options.momentumLimitTime) {
// refresh time and starting position to initiate a momentum
this.startTime = timestamp;
this.scrollBehaviorX.updateStartPos();
this.scrollBehaviorY.updateStartPos();
if (this.options.probeType === 1 /* Throttle */) {
this.hooks.trigger(this.hooks.eventTypes.scroll, this.getCurrentPos());
}
}
// dispatch scroll all the time
if (this.options.probeType > 1 /* Throttle */) {
this.hooks.trigger(this.hooks.eventTypes.scroll, this.getCurrentPos());
}
};
ScrollerActions.prototype.checkMomentum = function (absDistX, absDistY, timestamp) {
return (timestamp - this.endTime > this.options.momentumLimitTime &&
absDistY < this.options.momentumLimitDistance &&
absDistX < this.options.momentumLimitDistance);
};
ScrollerActions.prototype.handleEnd = function (e) {
if (this.hooks.trigger(this.hooks.eventTypes.beforeEnd, e)) {
return;
}
var currentPos = this.getCurrentPos();
this.scrollBehaviorX.updateDirection();
this.scrollBehaviorY.updateDirection();
if (this.hooks.trigger(this.hooks.eventTypes.end, e, currentPos)) {
return true;
}
this.animater.translate(currentPos);
this.endTime = getNow();
var duration = this.endTime - this.startTime;
this.hooks.trigger(this.hooks.eventTypes.scrollEnd, currentPos, duration);
};
ScrollerActions.prototype.handleClick = function (e) {
if (!preventDefaultExceptionFn(e.target, this.options.preventDefaultException)) {
e.preventDefault();
e.stopPropagation();
}
};
ScrollerActions.prototype.getCurrentPos = function () {
return {
x: this.scrollBehaviorX.getCurrentPos(),
y: this.scrollBehaviorY.getCurrentPos()
};
};
ScrollerActions.prototype.refresh = function () {
this.endTime = 0;
};
ScrollerActions.prototype.destroy = function () {
this.hooks.destroy();
};
return ScrollerActions;
}());
function createActionsHandlerOptions(bsOptions) {
var options = [
'click',
'bindToWrapper',
'disableMouse',
'disableTouch',
'preventDefault',
'stopPropagation',
'tagException',
'preventDefaultException'
].reduce(function (prev, cur) {
prev[cur] = bsOptions[cur];
return prev;
}, {});
return options;
}
function createBehaviorOptions(bsOptions, extraProp, bounces, rect) {
var options = [
'momentum',
'momentumLimitTime',
'momentumLimitDistance',
'deceleration',
'swipeBounceTime',
'swipeTime'
].reduce(function (prev, cur) {
prev[cur] = bsOptions[cur];
return prev;
}, {});
// add extra property
options.scrollable = bsOptions[extraProp];
options.bounces = bounces;
options.rect = rect;
return options;
}
function bubbling(source, target, events) {
events.forEach(function (event) {
var sourceEvent;
var targetEvent;
if (typeof event === 'string') {
sourceEvent = targetEvent = event;
}
else {
sourceEvent = event.source;
targetEvent = event.target;
}
source.on(sourceEvent, function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return target.trigger.apply(target, [targetEvent].concat(args));
});
});
}
var Scroller = /** @class */ (function () {
function Scroller(wrapper, options) {
this.hooks = new EventEmitter([
'beforeStart',
'beforeMove',
'beforeScrollStart',
'scrollStart',
'scroll',
'beforeEnd',
'scrollEnd',
'refresh',
'touchEnd',
'end',
'flick',
'scrollCancel',
'momentum',
'scrollTo',
'ignoreDisMoveForSamePos',
'scrollToElement',
'resize'
]);
this.wrapper = wrapper;
this.content = wrapper.children[0];
this.options = options;
var _a = this
.options.bounce, _b = _a.left, left = _b === void 0 ? true : _b, _c = _a.right, right = _c === void 0 ? true : _c, _d = _a.top, top = _d === void 0 ? true : _d, _e = _a.bottom, bottom = _e === void 0 ? true : _e;
// direction X
this.scrollBehaviorX = new Behavior(wrapper, createBehaviorOptions(options, 'scrollX', [left, right], {
size: 'width',
position: 'left'
}));
// direction Y
this.scrollBehaviorY = new Behavior(wrapper, createBehaviorOptions(options, 'scrollY', [top, bottom], {
size: 'height',
position: 'top'
}));
this.translater = new Translater(this.content);
this.animater = createAnimater(this.content, this.translater, this.options);
this.actionsHandler = new ActionsHandler(wrapper, createActionsHandlerOptions(this.options));
this.actions = new ScrollerActions(this.scrollBehaviorX, this.scrollBehaviorY, this.actionsHandler, this.animater, this.options);
var resizeHandler = this.resize.bind(this);
this.resizeRegister = new EventRegister(window, [
{
name: 'orientationchange',
handler: resizeHandler
},
{
name: 'resize',
handler: resizeHandler
}
]);
this.transitionEndRegister = new EventRegister(this.content, [
{
name: style.transitionEnd,
handler: this.transitionEnd.bind(this)
}
]);
this.init();
}
Scroller.prototype.init = function () {
var _this = this;
this.bindTranslater();
this.bindAnimater();
this.bindActions();
// enable pointer events when scrolling ends
this.hooks.on(this.hooks.eventTypes.scrollEnd, function () {
_this.togglePointerEvents(true);
});
};
Scroller.prototype.bindTranslater = function () {
var _this = this;
var hooks = this.translater.hooks;
hooks.on(hooks.eventTypes.beforeTranslate, function (transformStyle) {
if (_this.options.translateZ) {
transformStyle.push(_this.options.translateZ);
}
});
// disable pointer events when scrolling
hooks.on(hooks.eventTypes.translate, function (pos) {
_this.updatePositions(pos);
_this.togglePointerEvents(false);
});
};
Scroller.prototype.bindAnimater = function () {
var _this = this;
// reset position
this.animater.hooks.on(this.animater.hooks.eventTypes.end, function (pos) {
if (!_this.resetPosition(_this.options.bounceTime)) {
_this.animater.setPending(false);
_this.hooks.trigger(_this.hooks.eventTypes.scrollEnd, pos);
}
});
bubbling(this.animater.hooks, this.hooks, [
{
source: this.animater.hooks.eventTypes.move,
target: this.hooks.eventTypes.scroll
},
{
source: this.animater.hooks.eventTypes.forceStop,
target: this.hooks.eventTypes.scrollEnd
}
]);
};
Scroller.prototype.bindActions = function () {
var _this = this;
var actions = this.actions;
bubbling(actions.hooks, this.hooks, [
{
source: actions.hooks.eventTypes.start,
target: this.hooks.eventTypes.beforeStart
},
{
source: actions.hooks.eventTypes.start,
target: this.hooks.eventTypes.beforeScrollStart // just for event api
},
{
source: actions.hooks.eventTypes.beforeMove,
target: this.hooks.eventTypes.beforeMove
},
{
source: actions.hooks.eventTypes.scrollStart,
target: this.hooks.eventTypes.scrollStart
},
{
source: actions.hooks.eventTypes.scroll,
target: this.hooks.eventTypes.scroll
},
{
source: actions.hooks.eventTypes.beforeEnd,
target: this.hooks.eventTypes.beforeEnd
}
]);
actions.hooks.on(actions.hooks.eventTypes.end, function (e, pos) {
_this.hooks.trigger(_this.hooks.eventTypes.touchEnd, pos);
if (_this.hooks.trigger(_this.hooks.eventTypes.end, pos)) {
return true;
}
// check if it is a click operation
if (!actions.moved && _this.checkClick(e)) {
_this.animater.setForceStopped(false);
_this.hooks.trigger(_this.hooks.eventTypes.scrollCancel);
return true;
}
_this.animater.setForceStopped(false);
// reset if we are outside of the boundaries
if (_this.resetPosition(_this.options.bounceTime, ease.bounce)) {
return true;
}
});
actions.hooks.on(actions.hooks.eventTypes.scrollEnd, function (pos, duration) {
var deltaX = Math.abs(pos.x - _this.scrollBehaviorX.startPos);
var deltaY = Math.abs(pos.y - _this.scrollBehaviorY.startPos);
if (_this.checkFlick(duration, deltaX, deltaY)) {
_this.hooks.trigger(_this.hooks.eventTypes.flick);
return;
}
if (_this.momentum(pos, duration)) {
return;
}
_this.hooks.trigger(_this.hooks.eventTypes.scrollEnd, pos);
});
};
Scroller.prototype.checkFlick = function (duration, deltaX, deltaY) {
// flick
if (this.hooks.events.flick.length > 1 &&
duration < this.options.flickLimitTime &&
deltaX < this.options.flickLimitDistance &&
deltaY < this.options.flickLimitDistance) {
return true;
}
};
Scroller.prototype.momentum = function (pos, duration) {
var meta = {
time: 0,
easing: ease.swiper,
newX: pos.x,
newY: pos.y
};
// start momentum animation if needed
var momentumX = this.scrollBehaviorX.end(duration);
var momentumY = this.scrollBehaviorY.end(duration);
meta.newX = isUndef(momentumX.destination)
? meta.newX
: momentumX.destination;
meta.newY = isUndef(momentumY.destination)
? meta.newY
: momentumY.destination;
meta.time = Math.max(momentumX.duration, momentumY.duration);
this.hooks.trigger(this.hooks.eventTypes.momentum, meta, this);
// when x or y changed, do momentum animation now!
if (meta.newX !== pos.x || meta.newY !== pos.y) {
// change easing function when scroller goes out of the boundaries
if (meta.newX > this.scrollBehaviorX.minScrollPos ||
meta.newX < this.scrollBehaviorX.maxScrollPos ||
meta.newY > this.scrollBehaviorY.minScrollPos ||
meta.newY < this.scrollBehaviorY.maxScrollPos) {
meta.easing = ease.swipeBounce;
}
this.scrollTo(meta.newX, meta.newY, meta.time, meta.easing);
return true;
}
};
Scroller.prototype.checkClick = function (e) {
// when in the process of pulling down, it should not prevent click
var cancelable = {
preventClick: this.animater.forceStopped
};
// we scrolled less than momentumLimitDistance pixels
if (this.hooks.trigger(this.hooks.eventTypes.checkClick))
return true;
if (!cancelable.preventClick) {
var _dblclick = this.options.dblclick;
var dblclickTrigged = false;
if (_dblclick && this.lastClickTime) {
var _a = _dblclick.delay, delay = _a === void 0 ? 300 : _a;
if (getNow() - this.lastClickTime < delay) {
dblclickTrigged = true;
dblclick(e);
}
}
if (this.options.tap) {
tap(e, this.options.tap);
}
if (this.options.click &&
!preventDefaultExceptionFn(e.target, this.options.preventDefaultException)) {
click(e);
}
this.lastClickTime = dblclickTrigged ? null : getNow();
return true;
}
return false;
};
Scroller.prototype.resize = function () {
var _this = this;
if (!this.actions.enabled) {
return;
}
// fix a scroll problem under Android condition
if (isAndroid) {
this.wrapper.scrollTop = 0;
}
if (!this.hooks.trigger(this.hooks.eventTypes.resize)) {
clearTimeout(this.resizeTimeout);
this.resizeTimeout = window.setTimeout(function () {
_this.refresh();
}, this.options.resizePolling);
}
};
Scroller.prototype.transitionEnd = function (e) {
if (e.target !== this.content || !this.animater.pending) {
return;
}
var animater = this.animater;
animater.transitionTime();
if (!this.resetPosition(this.options.bounceTime, ease.bounce)) {
this.animater.setPending(false);
if (this.options.probeType !== 3 /* Realtime */) {
this.hooks.trigger(this.hooks.eventTypes.scrollEnd, this.getCurrentPos());
}
}
};
Scroller.prototype.togglePointerEvents = function (enabled) {
if (enabled === void 0) { enabled = true; }
var el = this.content.children.length
? this.content.children
: [this.content];
var pointerEvents = enabled ? 'auto' : 'none';
for (var i = 0; i < el.length; i++) {
var node = el[i];
// ignore BetterScroll instance's wrapper DOM
if (node.isBScrollContainer) {
continue;
}
node.style.pointerEvents = pointerEvents;
}
};
Scroller.prototype.refresh = function () {
this.scrollBehaviorX.refresh();
this.scrollBehaviorY.refresh();
this.actions.refresh();
this.wrapperOffset = offset(this.wrapper);
};
Scroller.prototype.scrollBy = function (deltaX, deltaY, time, easing) {
if (time === void 0) { time = 0; }
var _a = this.getCurrentPos(), x = _a.x, y = _a.y;
easing = !easing ? ease.bounce : easing;
deltaX += x;
deltaY += y;
this.scrollTo(deltaX, deltaY, time, easing);
};
Scroller.prototype.scrollTo = function (x, y, time, easing, extraTransform, isSilent) {
if (time === void 0) { time = 0; }
if (extraTransform === void 0) { extraTransform = {
start: {},
end: {}
}; }
easing = !easing ? ease.bounce : easing;
var easingFn = this.options.useTransition ? easing.style : easing.fn;
var currentPos = this.getCurrentPos();
var startPoint = __assign({ x: currentPos.x, y: currentPos.y }, extraTransform.start);
var endPoint = __assign({ x: x,
y: y }, extraTransform.end);
this.hooks.trigger(this.hooks.eventTypes.scrollTo, endPoint);
if (!this.hooks.trigger(this.hooks.eventTypes.ignoreDisMoveForSamePos)) {
// it is an useless move
if (startPoint.x === endPoint.x && startPoint.y === endPoint.y) {
return;
}
}
this.animater.move(startPoint, endPoint, time, easingFn, isSilent);
};
Scroller.prototype.scrollToElement = function (el, time, offsetX, offsetY, easing) {
var targetEle = getElement(el);
var pos = offset(targetEle);
var getOffset = function (offset, size, wrapperSize) {
if (typeof offset === 'number') {
return offset;
}
// if offsetX/Y are true we center the element to the screen
return offset ? Math.round(size / 2 - wrapperSize / 2) : 0;
};
offsetX = getOffset(offsetX, targetEle.offsetWidth, this.wrapper.offsetWidth);
offsetY = getOffset(offsetY, targetEle.offsetHeight, this.wrapper.offsetHeight);
var getPos = function (pos, wrapperPos, offset, scrollBehavior) {
pos -= wrapperPos;
pos = scrollBehavior.adjustPosition(pos - offset);
return pos;
};
pos.left = getPos(pos.left, this.wrapperOffset.left, offsetX, this.scrollBehaviorX);
pos.top = getPos(pos.top, this.wrapperOffset.top, offsetY, this.scrollBehaviorY);
if (this.hooks.trigger(this.hooks.eventTypes.scrollToElement, targetEle, pos)) {
return;
}
this.scrollTo(pos.left, pos.top, time, easing);
};
Scroller.prototype.resetPosition = function (time, easing) {
if (time === void 0) { time = 0; }
easing = !easing ? ease.bounce : easing;
var _a = this.scrollBehaviorX.checkInBoundary(), x = _a.position, xInBoundary = _a.inBoundary;
var _b = this.scrollBehaviorY.checkInBoundary(), y = _b.position, yInBoundary = _b.inBoundary;
if (xInBoundary && yInBoundary) {
return false;
}
// out of boundary
this.scrollTo(x, y, time, easing);
return true;
};
Scroller.prototype.updatePositions = function (pos) {
this.scrollBehaviorX.updatePosition(pos.x);
this.scrollBehaviorY.updatePosition(pos.y);
};
Scroller.prototype.getCurrentPos = function () {
return this.actions.getCurrentPos();
};
Scroller.prototype.enable = function () {
this.actions.enabled = true;
};
Scroller.prototype.disable = function () {
cancelAnimationFrame(this.animater.timer);
this.actions.enabled = false;
};
Scroller.prototype.destroy = function () {
var _this = this;
var keys = [
'resizeRegister',
'transitionEndRegister',
'actionsHandler',
'actions',
'hooks',
'animater',
'translater',
'scrollBehaviorX',
'scrollBehaviorY'
];
keys.forEach(function (key) { return _this[key].destroy(); });
};
return Scroller;
}());
var propertiesConfig = [
{
sourceKey: 'scroller.scrollBehaviorX.currentPos',
key: 'x'
},
{
sourceKey: 'scroller.scrollBehaviorY.currentPos',
key: 'y'
},
{
sourceKey: 'scroller.scrollBehaviorX.hasScroll',
key: 'hasHorizontalScroll'
},
{
sourceKey: 'scroller.scrollBehaviorY.hasScroll',
key: 'hasVerticalScroll'
},
{
sourceKey: 'scroller.scrollBehaviorX.contentSize',
key: 'scrollerWidth'
},
{
sourceKey: 'scroller.scrollBehaviorY.contentSize',
key: 'scrollerHeight'
},
{
sourceKey: 'scroller.scrollBehaviorX.maxScrollPos',
key: 'maxScrollX'
},
{
sourceKey: 'scroller.scrollBehaviorY.maxScrollPos',
key: 'maxScrollY'
},
{
sourceKey: 'scroller.scrollBehaviorX.minScrollPos',
key: 'minScrollX'
},
{
sourceKey: 'scroller.scrollBehaviorY.minScrollPos',
key: 'minScrollY'
},
{
sourceKey: 'scroller.scrollBehaviorX.movingDirection',
key: 'movingDirectionX'
},
{
sourceKey: 'scroller.scrollBehaviorY.movingDirection',
key: 'movingDirectionY'
},
{
sourceKey: 'scroller.scrollBehaviorX.direction',
key: 'directionX'
},
{
sourceKey: 'scroller.scrollBehaviorY.direction',
key: 'directionY'
},
{
sourceKey: 'scroller.actions.enabled',
key: 'enabled'
},
{
sourceKey: 'scroller.animater.pending',
key: 'pending'
},
{
sourceKey: 'scroller.animater.stop',
key: 'stop'
},
{
sourceKey: 'scroller.scrollTo',
key: 'scrollTo'
},
{
sourceKey: 'scroller.scrollBy',
key: 'scrollBy'
},
{
sourceKey: 'scroller.scrollToElement',
key: 'scrollToElement'
},
{
sourceKey: 'scroller.resetPosition',
key: 'resetPosition'
}
];
var BScroll = /** @class */ (function (_super) {
__extends(BScroll, _super);
function BScroll(el, options) {
var _this = _super.call(this, [
'refresh',
'enable',
'disable',
'beforeScrollStart',
'scrollStart',
'scroll',
'scrollEnd',
'scrollCancel',
'touchEnd',
'flick',
'destroy'
]) || this;
var wrapper = getElement(el);
if (!wrapper) {
warn('Can not resolve the wrapper DOM.');
return _this;
}
var content = wrapper.children[0];
if (!content) {
warn('The wrapper need at least one child element to be scroller.');
return _this;
}
_this.plugins = {};
_this.options = new Options().merge(options).process();
_this.hooks = new EventEmitter([
'init',
'refresh',
'enable',
'disable',
'destroy'
]);
_this.init(wrapper);
return _this;
}
BScroll.use = function (ctor) {
var name = ctor.pluginName;
var installed = this.plugins.some(function (plugin) { return ctor === plugin.ctor; });
if (installed)
return this;
if (isUndef(name)) {
warn("Plugin Class must specify plugin's name in static property by 'pluginName' field.");
return this;
}
if (this.pluginsMap[name]) {
warn("This plugin has been registered, maybe you need change plugin's name");
return this;
}
this.pluginsMap[name] = true;
this.plugins.push({
name: name,
applyOrder: ctor.applyOrder,
ctor: ctor
});
return this;
};
BScroll.prototype.init = function (wrapper) {
this.wrapper = wrapper;
wrapper.isBScrollContainer = true;
this.scroller = new Scroller(wrapper, this.options);
this.eventBubbling();
this.handleAutoBlur();
this.innerRefresh();
this.scroller.scrollTo(this.options.startX, this.options.startY);
this.enable();
this.proxy(propertiesConfig);
this.applyPlugins();
};
BScroll.prototype.applyPlugins = function () {
var _this = this;
var options = this.options;
this.constructor.plugins
.sort(function (a, b) {
var _a;
var applyOrderMap = (_a = {},
_a["pre" /* Pre */] = -1,
_a["post" /* Post */] = 1,
_a);
var aOrder = a.applyOrder ? applyOrderMap[a.applyOrder] : 0;
var bOrder = b.applyOrder ? applyOrderMap[b.applyOrder] : 0;
return aOrder - bOrder;
})
.forEach(function (item) {
var ctor = item.ctor;
if (options[item.name] && typeof ctor === 'function') {
_this.plugins[item.name] = new ctor(_this);
}
});
};
BScroll.prototype.handleAutoBlur = function () {
if (this.options.autoBlur) {
this.on(this.eventTypes.beforeScrollStart, function () {
var activeElement = document.activeElement;
if (activeElement &&
(activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA')) {
activeElement.blur();
}
});
}
};
BScroll.prototype.eventBubbling = function () {
bubbling(this.scroller.hooks, this, [
'beforeScrollStart',
'scrollStart',
'scroll',
'scrollEnd',
'scrollCancel',
'touchEnd',
'flick'
]);
};
BScroll.prototype.innerRefresh = function () {
this.scroller.refresh();
this.hooks.trigger(this.hooks.eventTypes.refresh);
this.trigger(this.eventTypes.refresh);
};
BScroll.prototype.proxy = function (propertiesConfig) {
var _this = this;
propertiesConfig.forEach(function (_a) {
var key = _a.key, sourceKey = _a.sourceKey;
propertiesProxy(_this, sourceKey, key);
});
};
BScroll.prototype.refresh = function () {
this.innerRefresh();
this.scroller.resetPosition();
};
BScroll.prototype.enable = function () {
this.scroller.enable();
this.hooks.trigger(this.hooks.eventTypes.enable);
this.trigger(this.eventTypes.enable);
};
BScroll.prototype.disable = function () {
this.scroller.disable();
this.hooks.trigger(this.hooks.eventTypes.disable);
this.trigger(this.eventTypes.disable);
};
BScroll.prototype.destroy = function () {
this.hooks.trigger(this.hooks.eventTypes.destroy);
this.trigger(this.eventTypes.destroy);
this.scroller.destroy();
};
BScroll.prototype.eventRegister = function (names) {
this.registerType(names);
};
BScroll.plugins = [];
BScroll.pluginsMap = {};
return BScroll;
}(EventEmitter));
var MouseWheel = /** @class */ (function () {
function MouseWheel(scroll) {
this.scroll = scroll;
this.wheelStart = false;
scroll.registerType(['mousewheelMove', 'mousewheelStart', 'mousewheelEnd']);
this.mouseWheelOpt = scroll.options.mouseWheel;
this.deltaCache = [];
this.registorEvent();
this.hooksFn = [];
this.registorHooks(scroll.hooks, 'destroy', this.destroy);
}
MouseWheel.prototype.destroy = function () {
this.eventRegistor.destroy();
window.clearTimeout(this.wheelEndTimer);
window.clearTimeout(this.wheelMoveTimer);
this.hooksFn.forEach(function (item) {
var hooks = item[0];
var hooksName = item[1];
var handlerFn = item[2];
hooks.off(hooksName, handlerFn);
});
};
MouseWheel.prototype.registorEvent = function () {
this.eventRegistor = new EventRegister(this.scroll.scroller.wrapper, [
{
name: 'wheel',
handler: this.wheelHandler.bind(this)
},
{
name: 'mousewheel',
handler: this.wheelHandler.bind(this)
},
{
name: 'DOMMouseScroll',
handler: this.wheelHandler.bind(this)
}
]);
};
MouseWheel.prototype.wheelHandler = function (e) {
this.beforeHandler(e);
// start
if (!this.wheelStart) {
this.wheelStartHandler(e);
this.wheelStart = true;
}
// move
var delta = this.getWheelDelta(e);
this.wheelMove(delta);
// end
this.wheelStopDetactor(e, delta);
};
MouseWheel.prototype.wheelStartHandler = function (e) {
this.deltaCache = [];
this.scroll.trigger(this.scroll.eventTypes.mousewheelStart);
};
MouseWheel.prototype.wheelStopDetactor = function (e, delta) {
var _this = this;
window.clearTimeout(this.wheelEndTimer);
var delayTime = this.mouseWheelOpt.throttle || 400;
this.wheelEndTimer = window.setTimeout(function () {
_this.wheelStart = false;
window.clearTimeout(_this.wheelMoveTimer);
_this.wheelMoveTimer = 0;
_this.scroll.trigger(_this.scroll.eventTypes.mousewheelEnd, delta);
}, delayTime);
};
MouseWheel.prototype.getWheelDelta = function (e) {
var _a = this.mouseWheelOpt, _b = _a.speed, speed = _b === void 0 ? 20 : _b, _c = _a.invert, invert = _c === void 0 ? false : _c;
var wheelDeltaX = 0;
var wheelDeltaY = 0;
var direction = invert ? -1 /* Negative */ : 1 /* Positive */;
switch (true) {
case 'deltaX' in e:
if (e.deltaMode === 1) {
wheelDeltaX = -e.deltaX * speed;
wheelDeltaY = -e.deltaY * speed;
}
else {
wheelDeltaX = -e.deltaX;
wheelDeltaY = -e.deltaY;
}
break;
case 'wheelDeltaX' in e:
wheelDeltaX = (e.wheelDeltaX / 120) * speed;
wheelDeltaY = (e.wheelDeltaY / 120) * speed;
break;
case 'wheelDelta' in e:
wheelDeltaX = wheelDeltaY = (e.wheelDelta / 120) * speed;
break;
case 'detail' in e:
wheelDeltaX = wheelDeltaY = (-e.detail / 3) * speed;
break;
}
wheelDeltaX *= direction;
wheelDeltaY *= direction;
if (!this.scroll.scroller.scrollBehaviorY.hasScroll) {
wheelDeltaX = wheelDeltaY;
wheelDeltaY = 0;
}
if (!this.scroll.scroller.scrollBehaviorX.hasScroll) {
wheelDeltaX = 0;
}
var directionX = wheelDeltaX > 0
? -1 /* Negative */
: wheelDeltaX < 0
? 1 /* Positive */
: 0;
var directionY = wheelDeltaY > 0
? -1 /* Negative */
: wheelDeltaY < 0
? 1 /* Positive */
: 0;
return {
x: wheelDeltaX,
y: wheelDeltaY,
directionX: directionX,
directionY: directionY
};
};
MouseWheel.prototype.beforeHandler = function (e) {
var _a = this.scroll.options, preventDefault = _a.preventDefault, stopPropagation = _a.stopPropagation, preventDefaultException = _a.preventDefaultException;
if (preventDefault &&
!preventDefaultExceptionFn(e.target, preventDefaultException)) {
e.preventDefault();
}
if (stopPropagation) {
e.stopPropagation();
}
};
MouseWheel.prototype.wheelMove = function (delta) {
var _this = this;
if (this.mouseWheelOpt.debounce && this.wheelMoveTimer) {
this.deltaCache.push(delta);
}
else {
var cachedDelta = this.deltaCache.reduce(function (prev, current) {
return {
x: prev.x + current.x,
y: prev.y + current.y
};
}, { x: 0, y: 0 });
this.deltaCache = [];
var newX = this.scroll.x + Math.round(delta.x) + cachedDelta.x;
var newY = this.scroll.y + Math.round(delta.y) + cachedDelta.y;
var scrollBehaviorX = this.scroll.scroller.scrollBehaviorX;
var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY;
newX = fixInboundValue(newX, scrollBehaviorX.maxScrollPos, scrollBehaviorX.minScrollPos);
newY = fixInboundValue(newY, scrollBehaviorY.maxScrollPos, scrollBehaviorY.minScrollPos);
if (!this.scroll.trigger(this.scroll.eventTypes.mousewheelMove, {
x: newX,
y: newY
})) {
var easeTime = this.getEaseTime();
if (newX !== this.scroll.x || newY !== this.scroll.y) {
this.scroll.scrollTo(newX, newY, easeTime);
}
}
if (this.mouseWheelOpt.debounce) {
this.wheelMoveTimer = window.setTimeout(function () {
_this.wheelMoveTimer = 0;
}, this.mouseWheelOpt.debounce);
}
}
};
MouseWheel.prototype.registorHooks = function (hooks, name, handler) {
hooks.on(name, handler, this);
this.hooksFn.push([hooks, name, handler]);
};
MouseWheel.prototype.getEaseTime = function () {
var DEFAULT_EASETIME = 300;
var SAFE_EASETIME = 100;
var easeTime = this.mouseWheelOpt.easeTime || DEFAULT_EASETIME;
// scrollEnd event will be triggered in every calling of scrollTo when easeTime is too small
// easeTime needs to be greater than 100
if (easeTime < SAFE_EASETIME) {
warn("easeTime should be greater than 100.\n If mouseWheel easeTime is too small, scrollEnd will be triggered many times.");
}
return easeTime;
};
MouseWheel.pluginName = 'mouseWheel';
MouseWheel.applyOrder = "pre" /* Pre */;
return MouseWheel;
}());
var ObserveDOM = /** @class */ (function () {
function ObserveDOM(scroll) {
var _this = this;
this.scroll = scroll;
this.stopObserver = false;
this.hooksFn = [];
this.init();
this.registorHooks(this.scroll.hooks, 'enable', function () {
if (_this.stopObserver) {
_this.init();
}
});
this.registorHooks(this.scroll.hooks, 'disable', function () {
_this.stopObserve();
});
this.registorHooks(this.scroll.hooks, 'destroy', function () {
_this.destroy();
});
}
ObserveDOM.prototype.init = function () {
var _this = this;
if (typeof MutationObserver !== 'undefined') {
var timer_1 = 0;
this.observer = new MutationObserver(function (mutations) {
_this.mutationObserverHandler(mutations, timer_1);
});
this.startObserve(this.observer);
}
else {
this.checkDOMUpdate();
}
};
ObserveDOM.prototype.destroy = function () {
this.stopObserve();
this.hooksFn.forEach(function (item) {
var hooks = item[0];
var hooksName = item[1];
var handlerFn = item[2];
hooks.off(hooksName, handlerFn);
});
this.hooksFn.length = 0;
};
ObserveDOM.prototype.mutationObserverHandler = function (mutations, timer) {
var _this = this;
if (this.shouldNotRefresh()) {
return;
}
var immediateRefresh = false;
var deferredRefresh = false;
for (var i = 0; i < mutations.length; i++) {
var mutation = mutations[i];
if (mutation.type !== 'attributes') {
immediateRefresh = true;
break;
}
else {
if (mutation.target !== this.scroll.scroller.content) {
deferredRefresh = true;
break;
}
}
}
if (immediateRefresh) {
this.scroll.refresh();
}
else if (deferredRefresh) {
// attributes changes too often
clearTimeout(timer);
timer = window.setTimeout(function () {
if (!_this.shouldNotRefresh()) {
_this.scroll.refresh();
}
}, 60);
}
};
ObserveDOM.prototype.startObserve = function (observer) {
var config = {
attributes: true,
childList: true,
subtree: true
};
observer.observe(this.scroll.scroller.content, config);
};
ObserveDOM.prototype.shouldNotRefresh = function () {
var scroller = this.scroll.scroller;
var scrollBehaviorX = scroller.scrollBehaviorX;
var scrollBehaviorY = scroller.scrollBehaviorY;
var outsideBoundaries = scrollBehaviorX.currentPos > scrollBehaviorX.minScrollPos ||
scrollBehaviorX.currentPos < scrollBehaviorX.maxScrollPos ||
scrollBehaviorY.currentPos > scrollBehaviorY.minScrollPos ||
scrollBehaviorY.currentPos < scrollBehaviorY.maxScrollPos;
return scroller.animater.pending || outsideBoundaries;
};
ObserveDOM.prototype.checkDOMUpdate = function () {
var me = this;
var scrollIns = this.scroll;
var scrollerEl = scrollIns.scroller.content;
var scrollerRect = getRect(scrollerEl);
var oldWidth = scrollerRect.width;
var oldHeight = scrollerRect.height;
function check() {
if (me.stopObserver) {
return;
}
scrollerRect = getRect(scrollerEl);
var newWidth = scrollerRect.width;
var newHeight = scrollerRect.height;
if (oldWidth !== newWidth || oldHeight !== newHeight) {
scrollIns.refresh();
}
oldWidth = newWidth;
oldHeight = newHeight;
next();
}
function next() {
setTimeout(function () {
check();
}, 1000);
}
next();
};
ObserveDOM.prototype.registorHooks = function (hooks, name, handler) {
hooks.on(name, handler, this);
this.hooksFn.push([hooks, name, handler]);
};
ObserveDOM.prototype.stopObserve = function () {
this.stopObserver = true;
if (this.observer) {
this.observer.disconnect();
}
};
ObserveDOM.pluginName = 'observeDOM';
return ObserveDOM;
}());
var sourcePrefix = 'plugins.pullDownRefresh';
var propertiesMap = [
{
key: 'finishPullDown',
name: 'finish'
},
{
key: 'openPullDown',
name: 'open'
},
{
key: 'closePullDown',
name: 'close'
},
{
key: 'autoPullDownRefresh',
name: 'autoPull'
}
];
var propertiesProxyConfig = propertiesMap.map(function (item) {
return {
key: item.key,
sourceKey: sourcePrefix + "." + item.name
};
});
var PullDown = /** @class */ (function () {
function PullDown(scroll) {
this.scroll = scroll;
this.pulling = false;
if (scroll.options.pullDownRefresh) {
this._watch();
}
this.scroll.registerType(['pullingDown']);
this.scroll.proxy(propertiesProxyConfig);
}
PullDown.prototype._watch = function () {
// 需要设置 probe = 3 吗?
// must watch scroll in real time
this.scroll.options.probeType = 3 /* Realtime */;
this.scroll.scroller.hooks.on('end', this._checkPullDown, this);
};
PullDown.prototype._checkPullDown = function () {
if (!this.scroll.options.pullDownRefresh) {
return;
}
var _a = this.scroll.options
.pullDownRefresh, _b = _a.threshold, threshold = _b === void 0 ? 90 : _b, _c = _a.stop, stop = _c === void 0 ? 40 : _c;
// check if a real pull down action
if (this.scroll.directionY !== -1 /* Negative */ ||
this.scroll.y < threshold) {
return false;
}
if (!this.pulling) {
this.pulling = true;
this.scroll.trigger('pullingDown');
this.originalMinScrollY = this.scroll.minScrollY;
this.scroll.minScrollY = stop;
}
this.scroll.scrollTo(this.scroll.x, stop, this.scroll.options.bounceTime, ease.bounce);
return this.pulling;
};
PullDown.prototype.finish = function () {
this.pulling = false;
this.scroll.minScrollY = this.originalMinScrollY;
this.scroll.resetPosition(this.scroll.options.bounceTime, ease.bounce);
};
PullDown.prototype.open = function (config) {
if (config === void 0) { config = true; }
this.scroll.options.pullDownRefresh = config;
this._watch();
};
PullDown.prototype.close = function () {
this.scroll.options.pullDownRefresh = false;
};
PullDown.prototype.autoPull = function () {
var _a = this.scroll.options
.pullDownRefresh, _b = _a.threshold, threshold = _b === void 0 ? 90 : _b, _c = _a.stop, stop = _c === void 0 ? 40 : _c;
if (this.pulling) {
return;
}
this.pulling = true;
this.originalMinScrollY = this.scroll.minScrollY;
this.scroll.minScrollY = threshold;
this.scroll.scrollTo(this.scroll.x, threshold);
this.scroll.trigger('pullingDown');
this.scroll.scrollTo(this.scroll.x, stop, this.scroll.options.bounceTime, ease.bounce);
};
PullDown.pluginName = 'pullDownRefresh';
return PullDown;
}());
var sourcePrefix$1 = 'plugins.pullUpLoad';
var propertiesMap$1 = [
{
key: 'finishPullUp',
name: 'finish'
},
{
key: 'openPullUp',
name: 'open'
},
{
key: 'closePullUp',
name: 'close'
}
];
var propertiesProxyConfig$1 = propertiesMap$1.map(function (item) {
return {
key: item.key,
sourceKey: sourcePrefix$1 + "." + item.name
};
});
var PullUp = /** @class */ (function () {
function PullUp(bscroll) {
this.bscroll = bscroll;
this.watching = false;
if (bscroll.options.pullUpLoad) {
this._watch();
}
this.bscroll.registerType(['pullingUp']);
this.bscroll.proxy(propertiesProxyConfig$1);
}
PullUp.prototype._watch = function () {
if (this.watching) {
return;
}
// must watch scroll in real time
this.bscroll.options.probeType = 3 /* Realtime */;
this.watching = true;
this.bscroll.on('scroll', this._checkToEnd, this);
};
PullUp.prototype._checkToEnd = function (pos) {
var _this = this;
if (!this.bscroll.options.pullUpLoad) {
return;
}
var _a = this.bscroll.options
.pullUpLoad.threshold, threshold = _a === void 0 ? 0 : _a;
if (this.bscroll.movingDirectionY === 1 /* Positive */ &&
pos.y <= this.bscroll.maxScrollY + threshold) {
// reset pullupWatching status after scroll end to promise that trigger 'pullingUp' only once when pulling up
this.bscroll.once('scrollEnd', function () {
_this.watching = false;
});
this.bscroll.trigger('pullingUp');
this.bscroll.off('scroll', this._checkToEnd);
}
};
PullUp.prototype.finish = function () {
if (this.watching) {
this.bscroll.once('scrollEnd', this._watch, this);
}
else {
this._watch();
}
};
PullUp.prototype.open = function (config) {
if (config === void 0) { config = true; }
this.bscroll.options.pullUpLoad = config;
this._watch();
};
PullUp.prototype.close = function () {
this.bscroll.options.pullUpLoad = false;
if (!this.watching) {
return;
}
this.watching = false;
this.bscroll.off('scroll', this._checkToEnd);
};
PullUp.pluginName = 'pullUpLoad';
return PullUp;
}());
var EventHandler = /** @class */ (function () {
function EventHandler(indicator, options) {
this.indicator = indicator;
this.options = options;
this.bscroll = indicator.bscroll;
this.startEventRegister = new EventRegister(this.indicator.el, [
{
name: options.disableMouse ? 'touchstart' : 'mousedown',
handler: this._start.bind(this)
}
]);
this.endEventRegister = new EventRegister(window, [
{
name: options.disableMouse ? 'touchend' : 'mouseup',
handler: this._end.bind(this)
}
]);
this.hooks = new EventEmitter(['touchStart', 'touchMove', 'touchEnd']);
}
EventHandler.prototype._start = function (e) {
var point = (e.touches ? e.touches[0] : e);
e.preventDefault();
e.stopPropagation();
this.initiated = true;
this.moved = false;
this.lastPoint = point[this.indicator.keysMap.pointPos];
var disableMouse = this.bscroll.options.disableMouse;
this.moveEventRegister = new EventRegister(window, [
{
name: disableMouse ? 'touchmove' : 'mousemove',
handler: this._move.bind(this)
}
]);
this.hooks.trigger('touchStart');
};
EventHandler.prototype._move = function (e) {
var point = (e.touches ? e.touches[0] : e);
var pointPos = point[this.indicator.keysMap.pointPos];
e.preventDefault();
e.stopPropagation();
var delta = pointPos - this.lastPoint;
this.lastPoint = pointPos;
if (!this.moved) {
this.hooks.trigger('touchMove', this.moved, delta);
this.moved = true;
return;
}
this.hooks.trigger('touchMove', this.moved, delta);
};
EventHandler.prototype._end = function (e) {
if (!this.initiated) {
return;
}
this.initiated = false;
e.preventDefault();
e.stopPropagation();
this.moveEventRegister.destroy();
this.hooks.trigger('touchEnd', this.moved);
};
EventHandler.prototype.destroy = function () {
this.startEventRegister.destroy();
this.moveEventRegister && this.moveEventRegister.destroy();
this.endEventRegister.destroy();
};
return EventHandler;
}());
var INDICATOR_MIN_LEN = 8;
var Indicator = /** @class */ (function () {
function Indicator(bscroll, options) {
this.bscroll = bscroll;
this.options = options;
this.keyVals = {
sizeRatio: 1,
maxPos: 0,
initialSize: 0
};
this.curPos = 0;
this.hooksHandlers = [];
this.wrapper = options.wrapper;
this.wrapperStyle = this.wrapper.style;
this.el = this.wrapper.children[0];
this.elStyle = this.el.style;
this.bscroll = bscroll;
this.direction = options.direction;
this.keysMap = this._getKeysMap();
if (options.fade) {
this.visible = 0;
this.wrapperStyle.opacity = '0';
}
else {
this.visible = 1;
}
this._listenHooks(options.fade, options.interactive);
this.refresh();
}
Indicator.prototype._listenHooks = function (fade, interactive) {
var _this = this;
var bscroll = this.bscroll;
var bscrollHooks = bscroll;
var translaterHooks = bscroll.scroller.translater.hooks;
var animaterHooks = bscroll.scroller.animater.hooks;
this._listen(bscrollHooks, 'refresh', this.refresh);
this._listen(translaterHooks, 'translate', this.updatePosAndSize);
this._listen(animaterHooks, 'time', function (time) {
_this.setTransitionTime(time);
});
this._listen(animaterHooks, 'timeFunction', function (ease) {
_this.setTransitionTimingFunction(ease);
});
if (fade) {
this._listen(bscrollHooks, 'scrollEnd', function () {
_this.fade();
});
this._listen(bscrollHooks, 'scrollStart', function () {
_this.fade(true);
});
// for mousewheel event
if (bscroll.eventTypes.mousewheelStart &&
bscroll.eventTypes.mousewheelEnd) {
this._listen(bscrollHooks, 'mousewheelStart', function () {
_this.fade(true);
});
this._listen(bscrollHooks, 'mousewheelEnd', function () {
_this.fade();
});
}
}
if (interactive) {
var disableMouse = this.bscroll.options.disableMouse;
this.eventHandler = new EventHandler(this, { disableMouse: disableMouse });
var eventHandlerHooks = this.eventHandler.hooks;
this._listen(eventHandlerHooks, 'touchStart', this.startHandler);
this._listen(eventHandlerHooks, 'touchMove', this.moveHandler);
this._listen(eventHandlerHooks, 'touchEnd', this.endHandler);
}
};
Indicator.prototype._getKeysMap = function () {
if (this.direction === "vertical" /* Vertical */) {
return {
hasScroll: 'hasVerticalScroll',
size: 'height',
wrapperSize: 'clientHeight',
scrollerSize: 'scrollerHeight',
maxScroll: 'maxScrollY',
pos: 'y',
pointPos: 'pageY',
translate: 'translateY'
};
}
return {
hasScroll: 'hasHorizontalScroll',
size: 'width',
wrapperSize: 'clientWidth',
scrollerSize: 'scrollerWidth',
maxScroll: 'maxScrollX',
pos: 'x',
pointPos: 'pageX',
translate: 'translateX'
};
};
Indicator.prototype.fade = function (visible) {
var time = visible ? 250 : 500;
this.wrapperStyle[style.transitionDuration] = time + 'ms';
this.wrapperStyle.opacity = visible ? '1' : '0';
this.visible = visible ? 1 : 0;
};
Indicator.prototype.refresh = function () {
var hasScroll = this.keysMap.hasScroll;
if (this._setShowBy(this.bscroll[hasScroll])) {
var _a = this.keysMap, wrapperSize = _a.wrapperSize, scrollerSize = _a.scrollerSize, maxScroll = _a.maxScroll;
this.keyVals = this._refreshKeyValues(this.wrapper[wrapperSize], this.bscroll[scrollerSize], this.bscroll[maxScroll]);
this.updatePosAndSize({
x: this.bscroll.x,
y: this.bscroll.y
});
}
};
Indicator.prototype._setShowBy = function (hasScroll) {
if (hasScroll) {
this.wrapper.style.display = '';
return true;
}
this.wrapper.style.display = 'none';
return false;
};
Indicator.prototype._refreshKeyValues = function (wrapperSize, scrollerSize, maxScroll) {
var initialSize = Math.max(Math.round((wrapperSize * wrapperSize) / (scrollerSize || wrapperSize || 1)), INDICATOR_MIN_LEN);
var maxPos = wrapperSize - initialSize;
// sizeRatio is negative
var sizeRatio = maxPos / maxScroll;
return {
initialSize: initialSize,
maxPos: maxPos,
sizeRatio: sizeRatio
};
};
Indicator.prototype.updatePosAndSize = function (endPoint) {
var _a = this._refreshPosAndSizeValue(endPoint, this.keyVals), pos = _a.pos, size = _a.size;
this.curPos = pos;
this._refreshPosAndSizeStyle(size, pos);
};
Indicator.prototype._refreshPosAndSizeValue = function (endPoint, keyVals) {
var posKey = this.keysMap.pos;
var sizeRatio = keyVals.sizeRatio, initialSize = keyVals.initialSize, maxPos = keyVals.maxPos;
var pos = Math.round(sizeRatio * endPoint[posKey]);
var size;
if (pos < 0) {
size = Math.max(initialSize + pos * 3, INDICATOR_MIN_LEN);
pos = 0;
}
else if (pos > maxPos) {
size = Math.max(initialSize - (pos - maxPos) * 3, INDICATOR_MIN_LEN);
pos = maxPos + initialSize - size;
}
else {
size = initialSize;
}
return {
pos: pos,
size: size
};
};
Indicator.prototype._refreshPosAndSizeStyle = function (size, pos) {
var _a = this.keysMap, translate = _a.translate, sizeKey = _a.size;
this.elStyle[sizeKey] = size + "px";
this.elStyle[style.transform] = translate + "(" + pos + "px)" + this.bscroll.options.translateZ;
};
Indicator.prototype.setTransitionTime = function (time) {
if (time === void 0) { time = 0; }
this.elStyle[style.transitionDuration] = time + 'ms';
};
Indicator.prototype.setTransitionTimingFunction = function (easing) {
this.elStyle[style.transitionTimingFunction] = easing;
};
Indicator.prototype.startHandler = function () {
this.setTransitionTime();
this.bscroll.trigger('beforeScrollStart');
};
Indicator.prototype.moveHandler = function (moved, delta) {
if (!moved) {
this.bscroll.trigger('scrollStart');
}
var newScrollPos = this._calScrollDesPos(this.curPos, delta, this.keyVals);
// TODO freeScroll ?
if (this.direction === "vertical" /* Vertical */) {
this.bscroll.scrollTo(this.bscroll.x, newScrollPos);
}
else {
this.bscroll.scrollTo(newScrollPos, this.bscroll.y);
}
this.bscroll.trigger('scroll', {
x: this.bscroll.x,
y: this.bscroll.y
});
};
Indicator.prototype._calScrollDesPos = function (curPos, delta, keyVals) {
var maxPos = keyVals.maxPos, sizeRatio = keyVals.sizeRatio;
var newPos = curPos + delta;
if (newPos < 0) {
newPos = 0;
}
else if (newPos > maxPos) {
newPos = maxPos;
}
return Math.round(newPos / sizeRatio);
};
Indicator.prototype.endHandler = function (moved) {
if (moved) {
this.bscroll.trigger('scrollEnd', {
x: this.bscroll.x,
y: this.bscroll.y
});
}
};
Indicator.prototype.destroy = function () {
if (this.options.interactive) {
this.eventHandler.destroy();
}
this.wrapper.parentNode.removeChild(this.wrapper);
this.hooksHandlers.forEach(function (item) {
var hooks = item[0];
var hooksName = item[1];
var handlerFn = item[2];
hooks.off(hooksName, handlerFn);
});
this.hooksHandlers.length = 0;
};
Indicator.prototype._listen = function (hooks, name, handler) {
hooks.on(name, handler, this);
this.hooksHandlers.push([hooks, name, handler]);
};
return Indicator;
}());
var ScrollBar = /** @class */ (function () {
function ScrollBar(bscroll) {
this.indicators = [];
if (bscroll.options.scrollbar) {
this.indicators = this._initIndicators(bscroll);
bscroll.on('destroy', this.destroy, this);
}
}
ScrollBar.prototype._initIndicators = function (bscroll) {
var _this = this;
var _a = bscroll.options
.scrollbar, _b = _a.fade, fade = _b === void 0 ? true : _b, _c = _a.interactive, interactive = _c === void 0 ? false : _c;
var indicatorOption;
var scrolls = {
scrollX: "horizontal" /* Horizontal */,
scrollY: "vertical" /* Vertical */
};
var indicators = [];
Object.keys(scrolls).forEach(function (key) {
var direction = scrolls[key];
if (bscroll.options[key]) {
indicatorOption = {
wrapper: _this._createIndicatorElement(direction),
direction: direction,
fade: fade,
interactive: interactive
};
bscroll.wrapper.appendChild(indicatorOption.wrapper);
indicators.push(new Indicator(bscroll, indicatorOption));
}
});
return indicators;
};
ScrollBar.prototype._createIndicatorElement = function (direction) {
var scrollbarEl = document.createElement('div');
var indicatorEl = document.createElement('div');
scrollbarEl.style.cssText =
'position:absolute;z-index:9999;pointerEvents:none';
indicatorEl.style.cssText =
'box-sizing:border-box;position:absolute;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);border-radius:3px;';
indicatorEl.className = 'bscroll-indicator';
if (direction === 'horizontal') {
scrollbarEl.style.cssText += ';height:7px;left:2px;right:2px;bottom:0';
indicatorEl.style.height = '100%';
scrollbarEl.className = 'bscroll-horizontal-scrollbar';
}
else {
scrollbarEl.style.cssText += ';width:7px;bottom:2px;top:2px;right:1px';
indicatorEl.style.width = '100%';
scrollbarEl.className = 'bscroll-vertical-scrollbar';
}
scrollbarEl.style.cssText += ';overflow:hidden';
scrollbarEl.appendChild(indicatorEl);
return scrollbarEl;
};
ScrollBar.prototype.destroy = function () {
for (var _i = 0, _a = this.indicators; _i < _a.length; _i++) {
var indicator = _a[_i];
indicator.destroy();
}
};
ScrollBar.pluginName = 'scrollbar';
return ScrollBar;
}());
var PagesPos = /** @class */ (function () {
function PagesPos(scroll, slideOpt) {
this.scroll = scroll;
this.slideOpt = slideOpt;
this.slideEl = null;
this.init();
}
PagesPos.prototype.init = function () {
var scrollerIns = this.scroll.scroller;
var scrollBehaviorX = scrollerIns.scrollBehaviorX;
var scrollBehaviorY = scrollerIns.scrollBehaviorY;
var wrapper = getRect(scrollerIns.wrapper);
var scroller = getRect(scrollerIns.content);
this.wrapperWidth = wrapper.width;
this.wrapperHeight = wrapper.height;
this.scrollerHeight = scrollBehaviorY.hasScroll
? scroller.height
: wrapper.height;
this.scrollerWidth = scrollBehaviorX.hasScroll
? scroller.width
: wrapper.width;
var stepX = this.slideOpt.stepX || this.wrapperWidth;
var stepY = this.slideOpt.stepY || this.wrapperHeight;
var slideEls = scrollerIns.content;
var el = this.slideOpt.el;
if (typeof el === 'string') {
this.slideEl = slideEls.querySelectorAll(el);
}
this.pages = this.slideEl
? this.computePagePosInfoByEl(this.slideEl)
: this.computePagePosInfo(stepX, stepY);
this.xLen = this.pages ? this.pages.length : 0;
this.yLen = this.pages && this.pages[0] ? this.pages[0].length : 0;
};
PagesPos.prototype.hasInfo = function () {
if (!this.pages || !this.pages.length) {
return false;
}
return true;
};
PagesPos.prototype.getPos = function (x, y) {
return this.pages[x][y];
};
PagesPos.prototype.getNearestPage = function (x, y) {
if (!this.hasInfo()) {
return;
}
var pageX = 0;
var pageY = 0;
var l = this.pages.length;
for (; pageX < l - 1; pageX++) {
if (x >= this.pages[pageX][0].cx) {
break;
}
}
l = this.pages[pageX].length;
for (; pageY < l - 1; pageY++) {
if (y >= this.pages[0][pageY].cy) {
break;
}
}
return {
pageX: pageX,
pageY: pageY
};
};
PagesPos.prototype.computePagePosInfo = function (stepX, stepY) {
var pages = [];
var x = 0;
var y;
var cx;
var cy;
var i = 0;
var l;
var maxScrollPosX = this.scroll.scroller.scrollBehaviorX.maxScrollPos;
var maxScrollPosY = this.scroll.scroller.scrollBehaviorY.maxScrollPos;
cx = Math.round(stepX / 2);
cy = Math.round(stepY / 2);
while (x > -this.scrollerWidth) {
pages[i] = [];
l = 0;
y = 0;
while (y > -this.scrollerHeight) {
pages[i][l] = {
x: Math.max(x, maxScrollPosX),
y: Math.max(y, maxScrollPosY),
width: stepX,
height: stepY,
cx: x - cx,
cy: y - cy
};
y -= stepY;
l++;
}
x -= stepX;
i++;
}
return pages;
};
PagesPos.prototype.computePagePosInfoByEl = function (el) {
var pages = [];
var x = 0;
var y = 0;
var cx;
var cy;
var i = 0;
var l = el.length;
var m = 0;
var n = -1;
var rect;
var maxScrollX = this.scroll.scroller.scrollBehaviorX.maxScrollPos;
var maxScrollY = this.scroll.scroller.scrollBehaviorY.maxScrollPos;
for (; i < l; i++) {
rect = getRect(el[i]);
if (i === 0 || rect.left <= getRect(el[i - 1]).left) {
m = 0;
n++;
}
if (!pages[m]) {
pages[m] = [];
}
x = Math.max(-rect.left, maxScrollX);
y = Math.max(-rect.top, maxScrollY);
cx = x - Math.round(rect.width / 2);
cy = y - Math.round(rect.height / 2);
pages[m][n] = {
x: x,
y: y,
width: rect.width,
height: rect.height,
cx: cx,
cy: cy
};
if (x > maxScrollX) {
m++;
}
}
return pages;
};
return PagesPos;
}());
var PageInfo = /** @class */ (function () {
function PageInfo(scroll, slideOpt) {
this.scroll = scroll;
this.slideOpt = slideOpt;
}
PageInfo.prototype.init = function () {
this.currentPage = {
x: 0,
y: 0,
pageX: 0,
pageY: 0
};
this.pagesPos = new PagesPos(this.scroll, this.slideOpt);
this.checkSlideLoop();
};
PageInfo.prototype.changeCurrentPage = function (newPage) {
this.currentPage = newPage;
};
PageInfo.prototype.change2safePage = function (pageX, pageY) {
if (!this.pagesPos.hasInfo()) {
return;
}
if (pageX >= this.pagesPos.xLen) {
pageX = this.pagesPos.xLen - 1;
}
else if (pageX < 0) {
pageX = 0;
}
if (pageY >= this.pagesPos.yLen) {
pageY = this.pagesPos.yLen - 1;
}
else if (pageY < 0) {
pageY = 0;
}
var _a = this.pagesPos.getPos(pageX, pageY), x = _a.x, y = _a.y;
return {
pageX: pageX,
pageY: pageY,
x: x,
y: y
};
};
PageInfo.prototype.getInitPage = function () {
var initPageX = this.loopX ? 1 : 0;
var initPageY = this.loopY ? 1 : 0;
return {
pageX: initPageX,
pageY: initPageY
};
};
PageInfo.prototype.getRealPage = function (page) {
var fixedPage = function (page, realPageLen) {
var pageIndex = [];
for (var i = 0; i < realPageLen; i++) {
pageIndex.push(i);
}
pageIndex.unshift(realPageLen - 1);
pageIndex.push(0);
return pageIndex[page];
};
var currentPage = page
? extend({}, page)
: extend({}, this.currentPage);
if (this.loopX) {
currentPage.pageX = fixedPage(currentPage.pageX, this.pagesPos.xLen - 2);
}
if (this.loopY) {
currentPage.pageY = fixedPage(currentPage.pageY, this.pagesPos.yLen - 2);
}
return {
pageX: currentPage.pageX,
pageY: currentPage.pageY
};
};
PageInfo.prototype.getPageSize = function () {
return this.pagesPos.getPos(this.currentPage.pageX, this.currentPage.pageY);
};
PageInfo.prototype.realPage2Page = function (x, y) {
if (!this.pagesPos.hasInfo()) {
return;
}
var lastX = this.pagesPos.xLen - 1;
var lastY = this.pagesPos.yLen - 1;
var firstX = 0;
var firstY = 0;
if (this.loopX) {
x += 1;
firstX = firstX + 1;
lastX = lastX - 1;
}
if (this.loopY) {
y += 1;
firstY = firstY + 1;
lastY = lastY - 1;
}
x = fixInboundValue(x, firstX, lastX);
y = fixInboundValue(y, firstY, lastY);
return {
realX: x,
realY: y
};
};
PageInfo.prototype.nextPage = function () {
return this.changedPageNum("positive" /* Positive */);
};
PageInfo.prototype.prevPage = function () {
return this.changedPageNum("negative" /* Negative */);
};
PageInfo.prototype.nearestPage = function (x, y, directionX, directionY) {
var pageInfo = this.pagesPos.getNearestPage(x, y);
if (!pageInfo) {
return {
x: 0,
y: 0,
pageX: 0,
pageY: 0
};
}
var pageX = pageInfo.pageX;
var pageY = pageInfo.pageY;
var newX;
var newY;
if (pageX === this.currentPage.pageX) {
pageX += directionX;
pageX = fixInboundValue(pageX, 0, this.pagesPos.xLen - 1);
}
if (pageY === this.currentPage.pageY) {
pageY += directionY;
pageY = fixInboundValue(pageInfo.pageY, 0, this.pagesPos.yLen - 1);
}
newX = this.pagesPos.getPos(pageX, 0).x;
newY = this.pagesPos.getPos(0, pageY).y;
return {
x: newX,
y: newY,
pageX: pageX,
pageY: pageY
};
};
PageInfo.prototype.getLoopStage = function () {
if (!this.needLoop) {
return "middle" /* Middle */;
}
if (this.loopX) {
if (this.currentPage.pageX === 0) {
return "head" /* Head */;
}
if (this.currentPage.pageX === this.pagesPos.xLen - 1) {
return "tail" /* Tail */;
}
}
if (this.loopY) {
if (this.currentPage.pageY === 0) {
return "head" /* Head */;
}
if (this.currentPage.pageY === this.pagesPos.yLen - 1) {
return "tail" /* Tail */;
}
}
return "middle" /* Middle */;
};
PageInfo.prototype.resetLoopPage = function () {
if (this.loopX) {
if (this.currentPage.pageX === 0) {
return {
pageX: this.pagesPos.xLen - 2,
pageY: this.currentPage.pageY
};
}
if (this.currentPage.pageX === this.pagesPos.xLen - 1) {
return {
pageX: 1,
pageY: this.currentPage.pageY
};
}
}
if (this.loopY) {
if (this.currentPage.pageY === 0) {
return {
pageX: this.currentPage.pageX,
pageY: this.pagesPos.yLen - 2
};
}
if (this.currentPage.pageY === this.pagesPos.yLen - 1) {
return {
pageX: this.currentPage.pageX,
pageY: 1
};
}
}
};
PageInfo.prototype.isSameWithCurrent = function (page) {
if (page.pageX !== this.currentPage.pageX ||
page.pageY !== this.currentPage.pageY) {
return false;
}
return true;
};
PageInfo.prototype.changedPageNum = function (direction) {
var x = this.currentPage.pageX;
var y = this.currentPage.pageY;
if (this.slideX) {
x = direction === "negative" /* Negative */ ? x - 1 : x + 1;
}
if (this.slideY) {
y = direction === "negative" /* Negative */ ? y - 1 : y + 1;
}
return {
pageX: x,
pageY: y
};
};
PageInfo.prototype.checkSlideLoop = function () {
this.needLoop = this.slideOpt.loop;
if (this.pagesPos.xLen > 1) {
this.slideX = true;
}
if (this.pagesPos.pages[0] && this.pagesPos.yLen > 1) {
this.slideY = true;
}
this.loopX = this.needLoop && this.slideX;
this.loopY = this.needLoop && this.slideY;
if (this.slideX && this.slideY) {
warn('slide does not support two direction at the same time.');
}
};
return PageInfo;
}());
var sourcePrefix$2 = 'plugins.slide';
var propertiesMap$2 = [
{
key: 'next',
name: 'next'
},
{
key: 'prev',
name: 'prev'
},
{
key: 'goToPage',
name: 'goToPage'
},
{
key: 'getCurrentPage',
name: 'getCurrentPage'
}
];
var propertiesConfig$1 = propertiesMap$2.map(function (item) {
return {
key: item.key,
sourceKey: sourcePrefix$2 + "." + item.name
};
});
var Slide = /** @class */ (function () {
function Slide(scroll) {
this.scroll = scroll;
this.resetLooping = false;
this.isTouching = false;
this.scroll.proxy(propertiesConfig$1);
this.scroll.registerType(['slideWillChange']);
this.slideOpt = this.scroll.options.slide;
this.page = new PageInfo(scroll, this.slideOpt);
this.hooksFn = [];
this.willChangeToPage = {
pageX: 0,
pageY: 0
};
this.init();
}
Slide.prototype.init = function () {
var _this = this;
var slide = this.slideOpt;
var slideEls = this.scroll.scroller.content;
var lazyInitByRefresh = false;
if (slide.loop) {
var children = slideEls.children;
if (children.length > 1) {
this.cloneSlideEleForLoop(slideEls);
lazyInitByRefresh = true;
}
else {
// Loop does not make any sense if there is only one child.
slide.loop = false;
}
}
var shouldRefreshByWidth = this.setSlideWidth(slideEls);
var shouldRefreshByHeight = this.setSlideHeight(this.scroll.scroller.wrapper, slideEls);
var shouldRefresh = shouldRefreshByWidth || shouldRefreshByHeight;
var scrollHooks = this.scroll.hooks;
var scrollerHooks = this.scroll.scroller.hooks;
this.registorHooks(scrollHooks, 'refresh', this.initSlideState);
this.registorHooks(scrollHooks, 'destroy', this.destroy);
this.registorHooks(scrollerHooks, 'momentum', this.modifyScrollMetaHandler);
// scrollEnd handler should be called before customized handlers
this.registorHooks(this.scroll, 'scrollEnd', this.amendCurrentPage);
this.registorHooks(scrollerHooks, 'beforeStart', this.setTouchFlag);
this.registorHooks(scrollerHooks, 'scroll', this.scrollMoving);
this.registorHooks(scrollerHooks, 'resize', this.resize);
// for mousewheel event
if (this.scroll.eventTypes.mousewheelMove &&
this.scroll.eventTypes.mousewheelEnd) {
this.registorHooks(this.scroll, 'mousewheelMove', function () {
// prevent default action of mousewheelMove
return true;
});
this.registorHooks(this.scroll, 'mousewheelEnd', function (delta) {
if (delta.directionX === 1 /* Positive */ ||
delta.directionY === 1 /* Positive */) {
_this.next();
}
if (delta.directionX === -1 /* Negative */ ||
delta.directionY === -1 /* Negative */) {
_this.prev();
}
});
}
if (slide.listenFlick !== false) {
this.registorHooks(scrollerHooks, 'flick', this.flickHandler);
}
if (!lazyInitByRefresh && !shouldRefresh) {
this.initSlideState();
}
else {
this.scroll.refresh();
}
};
Slide.prototype.resize = function () {
var _this = this;
var slideEls = this.scroll.scroller.content;
var slideWrapper = this.scroll.scroller.wrapper;
clearTimeout(this.resizeTimeout);
this.resizeTimeout = window.setTimeout(function () {
_this.clearSlideWidth(slideEls);
_this.clearSlideHeight(slideEls);
_this.setSlideWidth(slideEls);
_this.setSlideHeight(slideWrapper, slideEls);
_this.scroll.refresh();
}, this.scroll.options.resizePolling);
return true;
};
Slide.prototype.next = function (time, easing) {
var _a = this.page.nextPage(), pageX = _a.pageX, pageY = _a.pageY;
this.goTo(pageX, pageY, time, easing);
};
Slide.prototype.prev = function (time, easing) {
var _a = this.page.prevPage(), pageX = _a.pageX, pageY = _a.pageY;
this.goTo(pageX, pageY, time, easing);
};
Slide.prototype.goToPage = function (x, y, time, easing) {
var pageInfo = this.page.realPage2Page(x, y);
if (!pageInfo) {
return;
}
this.goTo(pageInfo.realX, pageInfo.realY, time, easing);
};
Slide.prototype.getCurrentPage = function () {
return this.page.getRealPage();
};
Slide.prototype.nearestPage = function (x, y) {
var scrollBehaviorX = this.scroll.scroller.scrollBehaviorX;
var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY;
var triggerThreshold = true;
if (Math.abs(x - scrollBehaviorX.absStartPos) <= this.thresholdX &&
Math.abs(y - scrollBehaviorY.absStartPos) <= this.thresholdY) {
triggerThreshold = false;
}
if (!triggerThreshold) {
return this.page.currentPage;
}
return this.page.nearestPage(fixInboundValue(x, scrollBehaviorX.maxScrollPos, scrollBehaviorX.minScrollPos), fixInboundValue(y, scrollBehaviorY.maxScrollPos, scrollBehaviorY.minScrollPos), scrollBehaviorX.direction, scrollBehaviorY.direction);
};
Slide.prototype.destroy = function () {
var slideEls = this.scroll.scroller.content;
if (this.slideOpt.loop) {
var children = slideEls.children;
if (children.length > 2) {
removeChild(slideEls, children[children.length - 1]);
removeChild(slideEls, children[0]);
}
}
this.hooksFn.forEach(function (item) {
var hooks = item[0];
var hooksName = item[1];
var handlerFn = item[2];
if (hooks.eventTypes[hooksName]) {
hooks.off(hooksName, handlerFn);
}
});
this.hooksFn.length = 0;
};
Slide.prototype.initSlideState = function () {
this.page.init();
this.initThreshold();
var initPage = this.page.getInitPage();
this.goTo(initPage.pageX, initPage.pageY, 0);
};
Slide.prototype.initThreshold = function () {
var slideThreshold = this.slideOpt.threshold || 0.1;
if (slideThreshold % 1 === 0) {
this.thresholdX = slideThreshold;
this.thresholdY = slideThreshold;
}
else {
var pageSize = this.page.getPageSize();
this.thresholdX = Math.round(pageSize.width * slideThreshold);
this.thresholdY = Math.round(pageSize.height * slideThreshold);
}
};
Slide.prototype.cloneSlideEleForLoop = function (slideEls) {
var children = slideEls.children;
prepend(children[children.length - 1].cloneNode(true), slideEls);
slideEls.appendChild(children[1].cloneNode(true));
};
Slide.prototype.amendCurrentPage = function () {
this.isTouching = false;
if (!this.slideOpt.loop) {
return;
}
// triggered by resetLoop
if (this.resetLooping) {
this.resetLooping = false;
return;
}
// fix bug: scroll two page or even more page at once and fetch the boundary.
// In this case, momentum won't be trigger, so the pageIndex will be wrong and won't be trigger reset.
var isScrollToBoundary = false;
if (this.page.loopX &&
(this.scroll.x === this.scroll.scroller.scrollBehaviorX.minScrollPos ||
this.scroll.x === this.scroll.scroller.scrollBehaviorX.maxScrollPos)) {
isScrollToBoundary = true;
}
if (this.page.loopY &&
(this.scroll.y === this.scroll.scroller.scrollBehaviorY.minScrollPos ||
this.scroll.y === this.scroll.scroller.scrollBehaviorY.maxScrollPos)) {
isScrollToBoundary = true;
}
if (isScrollToBoundary) {
var scrollBehaviorX = this.scroll.scroller.scrollBehaviorX;
var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY;
var newPos = this.page.nearestPage(fixInboundValue(this.scroll.x, scrollBehaviorX.maxScrollPos, scrollBehaviorX.minScrollPos), fixInboundValue(this.scroll.y, scrollBehaviorY.maxScrollPos, scrollBehaviorY.minScrollPos), 0, 0);
var newPage = {
x: newPos.x,
y: newPos.y,
pageX: newPos.pageX,
pageY: newPos.pageY
};
if (!this.page.isSameWithCurrent(newPage)) {
this.page.changeCurrentPage(newPage);
}
}
var changePage = this.page.resetLoopPage();
if (changePage) {
this.resetLooping = true;
this.goTo(changePage.pageX, changePage.pageY, 0);
return true; // stop trigger chain
}
// amend willChangeToPage, because willChangeToPage maybe wrong when sliding quickly
this.pageWillChangeTo(this.page.currentPage);
};
Slide.prototype.shouldSetWidthHeight = function (checkType) {
var checkMap = {
width: ['scrollX', 'disableSetWidth'],
height: ['scrollY', 'disableSetHeight']
};
var checkOption = checkMap[checkType];
if (!this.scroll.options[checkOption[0]]) {
return false;
}
if (this.slideOpt[checkOption[1]]) {
return false;
}
return true;
};
Slide.prototype.clearSlideWidth = function (slideEls) {
if (!this.shouldSetWidthHeight('width')) {
return;
}
var children = slideEls.children;
for (var i = 0; i < children.length; i++) {
var slideItemDom = children[i];
slideItemDom.removeAttribute('style');
}
slideEls.removeAttribute('style');
};
Slide.prototype.setSlideWidth = function (slideEls) {
if (!this.shouldSetWidthHeight('width')) {
return false;
}
var children = slideEls.children;
var slideItemWidth = children[0].clientWidth;
for (var i = 0; i < children.length; i++) {
var slideItemDom = children[i];
slideItemDom.style.width = slideItemWidth + 'px';
}
slideEls.style.width = slideItemWidth * children.length + 'px';
return true;
};
Slide.prototype.clearSlideHeight = function (slideEls) {
if (!this.shouldSetWidthHeight('height')) {
return;
}
var children = slideEls.children;
for (var i = 0; i < children.length; i++) {
var slideItemDom = children[i];
slideItemDom.removeAttribute('style');
}
slideEls.removeAttribute('style');
};
// height change will not effect minScrollY & maxScrollY
Slide.prototype.setSlideHeight = function (slideWrapper, slideEls) {
if (!this.shouldSetWidthHeight('height')) {
return false;
}
var wrapperHeight = slideWrapper.clientHeight;
var children = slideEls.children;
for (var i = 0; i < children.length; i++) {
var slideItemDom = children[i];
slideItemDom.style.height = wrapperHeight + 'px';
}
slideEls.style.height = wrapperHeight * children.length + 'px';
return true;
};
Slide.prototype.goTo = function (pageX, pageY, time, easing) {
if (pageY === void 0) { pageY = 0; }
var newPageInfo = this.page.change2safePage(pageX, pageY);
if (!newPageInfo) {
return;
}
var scrollEasing = easing || this.slideOpt.easing || ease.bounce;
var posX = newPageInfo.x;
var posY = newPageInfo.y;
var deltaX = posX - this.scroll.scroller.scrollBehaviorX.currentPos;
var deltaY = posY - this.scroll.scroller.scrollBehaviorY.currentPos;
if (!deltaX && !deltaY) {
return;
}
time = time === undefined ? this.getAnimateTime(deltaX, deltaY) : time;
this.page.changeCurrentPage({
x: posX,
y: posY,
pageX: newPageInfo.pageX,
pageY: newPageInfo.pageY
});
this.pageWillChangeTo(this.page.currentPage);
this.scroll.scroller.scrollTo(posX, posY, time, scrollEasing);
};
Slide.prototype.flickHandler = function () {
var scrollBehaviorX = this.scroll.scroller.scrollBehaviorX;
var scrollBehaviorY = this.scroll.scroller.scrollBehaviorY;
var deltaX = scrollBehaviorX.currentPos - scrollBehaviorX.startPos;
var deltaY = scrollBehaviorY.currentPos - scrollBehaviorY.startPos;
var time = this.getAnimateTime(deltaX, deltaY);
this.goTo(this.page.currentPage.pageX + scrollBehaviorX.direction, this.page.currentPage.pageY + scrollBehaviorY.direction, time);
};
Slide.prototype.getAnimateTime = function (deltaX, deltaY) {
if (this.slideOpt.speed) {
return this.slideOpt.speed;
}
return Math.max(Math.max(Math.min(Math.abs(deltaX), 1000), Math.min(Math.abs(deltaY), 1000)), 300);
};
Slide.prototype.modifyScrollMetaHandler = function (scrollMeta) {
var newPos = this.nearestPage(scrollMeta.newX, scrollMeta.newY);
scrollMeta.time = this.getAnimateTime(scrollMeta.newX - newPos.x, scrollMeta.newY - newPos.y);
scrollMeta.newX = newPos.x;
scrollMeta.newY = newPos.y;
scrollMeta.easing = this.slideOpt.easing || ease.bounce;
this.page.changeCurrentPage({
x: scrollMeta.newX,
y: scrollMeta.newY,
pageX: newPos.pageX,
pageY: newPos.pageY
});
this.pageWillChangeTo(this.page.currentPage);
};
Slide.prototype.scrollMoving = function (point) {
if (this.isTouching) {
var newPos = this.nearestPage(point.x, point.y);
this.pageWillChangeTo(newPos);
}
};
Slide.prototype.pageWillChangeTo = function (newPage) {
var changeToPage = this.page.getRealPage(newPage);
if (changeToPage.pageX === this.willChangeToPage.pageX &&
changeToPage.pageY === this.willChangeToPage.pageY) {
return;
}
this.willChangeToPage = changeToPage;
this.scroll.trigger('slideWillChange', this.willChangeToPage);
};
Slide.prototype.setTouchFlag = function () {
this.isTouching = true;
};
Slide.prototype.registorHooks = function (hooks, name, handler) {
hooks.on(name, handler, this);
this.hooksFn.push([hooks, name, handler]);
};
Slide.pluginName = 'slide';
return Slide;
}());
var sourcePrefix$3 = 'plugins.wheel';
var propertiesMap$3 = [
{
key: 'wheelTo',
name: 'wheelTo'
},
{
key: 'getSelectedIndex',
name: 'getSelectedIndex'
}
];
var propertiesConfig$2 = propertiesMap$3.map(function (item) {
return {
key: item.key,
sourceKey: sourcePrefix$3 + "." + item.name
};
});
var CONSTANTS = {
rate: 4
};
var Wheel = /** @class */ (function () {
function Wheel(scroll) {
this.scroll = scroll;
this.options = this.scroll.options.wheel;
this.init();
}
Wheel.prototype.init = function () {
if (this.options) {
this.normalizeOptions();
this.refresh();
this.tapIntoHooks();
this.wheelTo(this.selectedIndex);
this.scroll.proxy(propertiesConfig$2);
}
};
Wheel.prototype.tapIntoHooks = function () {
var _this = this;
var scroller = this.scroll.scroller;
var actionsHandler = scroller.actionsHandler;
var scrollBehaviorY = scroller.scrollBehaviorY;
var animater = scroller.animater;
// BScroll
this.scroll.on(this.scroll.hooks.eventTypes.refresh, function () {
_this.refresh();
});
// Scroller
scroller.hooks.on(scroller.hooks.eventTypes.checkClick, function () {
var index = Array.from(_this.items).indexOf(_this.target);
if (index === -1)
return true;
_this.wheelTo(index, _this.options.adjustTime, ease.swipe);
return true;
});
scroller.hooks.on(scroller.hooks.eventTypes.scrollTo, function (endPoint) {
endPoint.y = _this.findNearestValidWheel(endPoint.y).y;
});
scroller.hooks.on(scroller.hooks.eventTypes.scrollToElement, function (el, pos) {
if (!hasClass(el, _this.options.wheelItemClass)) {
return true;
}
else {
pos.top = _this.findNearestValidWheel(pos.top).y;
}
});
scroller.hooks.on(scroller.hooks.eventTypes.ignoreDisMoveForSamePos, function () {
return true;
});
// ActionsHandler
actionsHandler.hooks.on(actionsHandler.hooks.eventTypes.beforeStart, function (e) {
_this.target = e.target;
});
// ScrollBehaviorY
scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.momentum, function (momentumInfo, distance) {
momentumInfo.rate = CONSTANTS.rate;
momentumInfo.destination = _this.findNearestValidWheel(momentumInfo.destination).y;
var maxDistance = 1000;
var minDuration = 800;
if (distance < maxDistance) {
momentumInfo.duration = Math.max(minDuration, (distance / maxDistance) * _this.scroll.options.swipeTime);
}
});
scrollBehaviorY.hooks.on(scrollBehaviorY.hooks.eventTypes.end, function (momentumInfo) {
var validWheel = _this.findNearestValidWheel(scrollBehaviorY.currentPos);
momentumInfo.destination = validWheel.y;
momentumInfo.duration = _this.options.adjustTime;
_this.selectedIndex = validWheel.index;
});
// Animater
animater.hooks.on(animater.hooks.eventTypes.time, function (time) {
_this.transitionDuration(time);
});
animater.hooks.on(animater.hooks.eventTypes.timeFunction, function (easing) {
_this.timeFunction(easing);
});
animater.hooks.on(animater.hooks.eventTypes.beforeForceStop, function (_a) {
var y = _a.y;
_this.target = _this.items[_this.findNearestValidWheel(y).index];
// don't dispatch scrollEnd when it is a click operation
return true;
});
// Translater
animater.translater.hooks.on(animater.translater.hooks.eventTypes.translate, function (endPoint) {
_this.rotateX(endPoint.y);
_this.selectedIndex = _this.findNearestValidWheel(endPoint.y).index;
});
};
Wheel.prototype.refresh = function () {
var scroller = this.scroll.scroller;
var scrollBehaviorY = scroller.scrollBehaviorY;
// adjust contentSize
var contentRect = getRect(scroller.content);
scrollBehaviorY.contentSize = contentRect.height;
this.items = scroller.content.children;
this.checkWheelAllDisabled();
this.itemHeight = this.items.length
? scrollBehaviorY.contentSize / this.items.length
: 0;
if (this.selectedIndex === undefined) {
this.selectedIndex = this.options.selectedIndex || 0;
}
this.scroll.maxScrollX = 0;
this.scroll.maxScrollY = -this.itemHeight * (this.items.length - 1);
this.scroll.minScrollX = 0;
this.scroll.minScrollY = 0;
scrollBehaviorY.hasScroll =
scrollBehaviorY.options && this.scroll.maxScrollY < this.scroll.minScrollY;
};
Wheel.prototype.getSelectedIndex = function () {
return this.selectedIndex;
};
Wheel.prototype.wheelTo = function (index, time, ease, isSlient) {
if (index === void 0) { index = 0; }
if (time === void 0) { time = 0; }
var y = -index * this.itemHeight;
this.scroll.scrollTo(0, y, time, ease, isSlient);
};
Wheel.prototype.transitionDuration = function (time) {
for (var i = 0; i < this.items.length; i++) {
this.items[i].style[style.transitionDuration] =
time + 'ms';
}
};
Wheel.prototype.timeFunction = function (easing) {
for (var i = 0; i < this.items.length; i++) {
this.items[i].style[style.transitionTimingFunction] = easing;
}
};
Wheel.prototype.rotateX = function (y) {
var _a = this.options.rotate, rotate = _a === void 0 ? 25 : _a;
for (var i = 0; i < this.items.length; i++) {
var deg = rotate * (y / this.itemHeight + i);
this.items[i].style[style.transform] = "rotateX(" + deg + "deg)";
}
};
Wheel.prototype.findNearestValidWheel = function (y) {
y = y > 0 ? 0 : y < this.scroll.maxScrollY ? this.scroll.maxScrollY : y;
var currentIndex = Math.abs(Math.round(-y / this.itemHeight));
var cacheIndex = currentIndex;
var items = this.items;
var wheelDisabledItemClassName = this.options
.wheelDisabledItemClass;
// Impersonation web native select
// first, check whether there is a enable item whose index is smaller than currentIndex
// then, check whether there is a enable item whose index is bigger than currentIndex
// otherwise, there are all disabled items, just keep currentIndex unchange
while (currentIndex >= 0) {
if (!hasClass(items[currentIndex], wheelDisabledItemClassName)) {
break;
}
currentIndex--;
}
if (currentIndex < 0) {
currentIndex = cacheIndex;
while (currentIndex <= items.length - 1) {
if (!hasClass(items[currentIndex], wheelDisabledItemClassName)) {
break;
}
currentIndex++;
}
}
// keep it unchange when all the items are disabled
if (currentIndex === items.length) {
currentIndex = cacheIndex;
}
// when all the items are disabled, this.selectedIndex should always be -1
return {
index: this.wheelItemsAllDisabled ? -1 : currentIndex,
y: -currentIndex * this.itemHeight
};
};
Wheel.prototype.normalizeOptions = function () {
var options = (this.options = isPlainObject(this.options)
? this.options
: {});
if (!options.wheelWrapperClass) {
options.wheelWrapperClass = 'wheel-scroll';
}
if (!options.wheelItemClass) {
options.wheelItemClass = 'wheel-item';
}
if (!options.rotate) {
options.rotate = 25;
}
if (!options.adjustTime) {
options.adjustTime = 400;
}
if (!options.wheelDisabledItemClass) {
options.wheelDisabledItemClass = 'wheel-disabled-item';
}
};
Wheel.prototype.checkWheelAllDisabled = function () {
var wheelDisabledItemClassName = this.options
.wheelDisabledItemClass;
var items = this.items;
this.wheelItemsAllDisabled = true;
for (var i = 0; i < items.length; i++) {
if (!hasClass(items[i], wheelDisabledItemClassName)) {
this.wheelItemsAllDisabled = false;
break;
}
}
};
Wheel.pluginName = 'wheel';
return Wheel;
}());
var sourcePrefix$4 = 'plugins.zoom';
var propertiesMap$4 = [
{
key: 'zoomTo',
name: 'zoomTo'
}
];
var propertiesConfig$3 = propertiesMap$4.map(function (item) {
return {
key: item.key,
sourceKey: sourcePrefix$4 + "." + item.name
};
});
var Zoom = /** @class */ (function () {
function Zoom(scroll) {
this.scroll = scroll;
this.scale = 1;
this.scroll.proxy(propertiesConfig$3);
this.scroll.registerType(['zoomStart', 'zoomEnd']);
this.zoomOpt = this.scroll.options.zoom;
this.lastTransformScale = this.scale;
this.hooksFn = [];
this.init();
}
Zoom.prototype.init = function () {
var _this = this;
var scrollerIns = this.scroll.scroller;
this.wrapper = this.scroll.scroller.wrapper;
this.scaleElement = this.scroll.scroller.content;
this.scaleElement.style[style.transformOrigin] = '0 0';
this.scaleElementInitSize = getRect(this.scaleElement);
var scrollBehaviorX = scrollerIns.scrollBehaviorX;
var scrollBehaviorY = scrollerIns.scrollBehaviorY;
this.initScrollBoundary = {
x: [scrollBehaviorX.minScrollPos, scrollBehaviorX.maxScrollPos],
y: [scrollBehaviorY.minScrollPos, scrollBehaviorY.maxScrollPos]
};
this.registorHooks(scrollerIns.actions.hooks, 'start', function (e) {
if (e.touches && e.touches.length > 1) {
_this.zoomStart(e);
}
});
this.registorHooks(scrollerIns.actions.hooks, 'beforeMove', function (e) {
if (!e.touches || e.touches.length < 2) {
return false;
}
_this.zoom(e);
return true;
});
this.registorHooks(scrollerIns.actions.hooks, 'beforeEnd', function (e) {
if (!_this.zooming) {
return false;
}
_this.zoomEnd();
return true;
});
this.registorHooks(scrollerIns.translater.hooks, 'beforeTranslate', function (transformStyle, point) {
var scale = point.scale ? point.scale : _this.lastTransformScale;
_this.lastTransformScale = scale;
transformStyle.push("scale(" + scale + ")");
});
this.registorHooks(scrollerIns.hooks, 'ignoreDisMoveForSamePos', function () {
return true;
});
this.registorHooks(this.scroll.hooks, 'destroy', this.destroy);
};
Zoom.prototype.zoomTo = function (scale, x, y) {
var _a = offsetToBody(this.wrapper), left = _a.left, top = _a.top;
var originX = x + left - this.scroll.x;
var originY = y + top - this.scroll.y;
this.zooming = true;
this._zoomTo(scale, { x: originX, y: originY }, this.scale);
this.zooming = false;
};
Zoom.prototype.zoomStart = function (e) {
this.zooming = true;
var firstFinger = e.touches[0];
var secondFinger = e.touches[1];
this.startDistance = this.getFingerDistance(e);
this.startScale = this.scale;
var _a = offsetToBody(this.wrapper), left = _a.left, top = _a.top;
this.origin = {
x: Math.abs(firstFinger.pageX + secondFinger.pageX) / 2 +
left -
this.scroll.x,
y: Math.abs(firstFinger.pageY + secondFinger.pageY) / 2 +
top -
this.scroll.y
};
this.scroll.trigger(this.scroll.eventTypes.zoomStart);
};
Zoom.prototype.zoom = function (e) {
var scrollerIns = this.scroll.scroller;
var currentDistance = this.getFingerDistance(e);
var currentScale = (currentDistance / this.startDistance) * this.startScale;
this.scale = this.scaleCure(currentScale);
var lastScale = this.scale / this.startScale;
var scrollBehaviorX = scrollerIns.scrollBehaviorX;
var scrollBehaviorY = scrollerIns.scrollBehaviorY;
var x = this.getNewPos(this.origin.x, lastScale, scrollBehaviorX);
var y = this.getNewPos(this.origin.y, lastScale, scrollBehaviorY);
this.resetBoundaries(this.scale, scrollBehaviorX, 'x', x);
this.resetBoundaries(this.scale, scrollBehaviorY, 'y', y);
scrollerIns.scrollTo(x, y, 0, undefined, {
start: {
scale: this.lastTransformScale
},
end: {
scale: this.scale
}
});
};
Zoom.prototype.getFingerDistance = function (e) {
var firstFinger = e.touches[0];
var secondFinger = e.touches[1];
var deltaX = Math.abs(firstFinger.pageX - secondFinger.pageX);
var deltaY = Math.abs(firstFinger.pageY - secondFinger.pageY);
return getDistance(deltaX, deltaY);
};
Zoom.prototype.zoomEnd = function () {
this._zoomTo(this.scale, this.origin, this.startScale || this.scale);
this.zooming = false;
this.scroll.trigger(this.scroll.eventTypes.zoomEnd);
};
Zoom.prototype.destroy = function () {
this.hooksFn.forEach(function (item) {
var hooks = item[0];
var hooksName = item[1];
var handlerFn = item[2];
hooks.off(hooksName, handlerFn);
});
this.hooksFn.length = 0;
};
Zoom.prototype._zoomTo = function (scale, origin, startScale) {
this.scale = this.fixInScaleLimit(scale);
var lastScale = this.scale / startScale;
var scrollerIns = this.scroll.scroller;
var scrollBehaviorX = scrollerIns.scrollBehaviorX;
var scrollBehaviorY = scrollerIns.scrollBehaviorY;
this.resetBoundaries(this.scale, scrollBehaviorX, 'x');
this.resetBoundaries(this.scale, scrollBehaviorY, 'y');
// resetPosition
var newX = this.getNewPos(origin.x, lastScale, scrollBehaviorX, true);
var newY = this.getNewPos(origin.y, lastScale, scrollBehaviorY, true);
if (scrollBehaviorX.currentPos !== Math.round(newX) ||
scrollBehaviorY.currentPos !== Math.round(newY) ||
this.scale !== this.lastTransformScale) {
scrollerIns.scrollTo(newX, newY, this.scroll.options.bounceTime, undefined, {
start: {
scale: this.lastTransformScale
},
end: {
scale: this.scale
}
});
}
};
Zoom.prototype.resetBoundaries = function (scale, scrollBehavior, direction, extendValue) {
var min = this.initScrollBoundary[direction][0];
var max = this.initScrollBoundary[direction][1];
var hasScroll = false;
if (scale > 1) {
var sideName = direction === 'x' ? 'width' : 'height';
max =
-this.scaleElementInitSize[sideName] * (scale - 1) -
this.initScrollBoundary[direction][1];
hasScroll = true;
}
if (!isUndef(extendValue)) {
max = Math.min(extendValue, max);
min = Math.max(extendValue, min); // max & min & curValue is negative value
hasScroll = !!(min || max);
}
scrollBehavior.minScrollPos = Math.floor(min);
scrollBehavior.maxScrollPos = Math.floor(max);
scrollBehavior.hasScroll = hasScroll;
};
Zoom.prototype.getNewPos = function (origin, lastScale, scrollBehavior, fixInBound) {
var newPos = origin - origin * lastScale + scrollBehavior.startPos;
if (fixInBound) {
newPos = fixInboundValue(newPos, scrollBehavior.maxScrollPos, 0);
}
return Math.floor(newPos);
};
Zoom.prototype.scaleCure = function (scale) {
var _a = this.zoomOpt, _b = _a.min, min = _b === void 0 ? 1 : _b, _c = _a.max, max = _c === void 0 ? 4 : _c;
if (scale < min) {
scale = 0.5 * min * Math.pow(2.0, scale / min);
}
else if (scale > max) {
scale = 2.0 * max * Math.pow(0.5, max / scale);
}
return scale;
};
Zoom.prototype.fixInScaleLimit = function (scale) {
var _a = this.zoomOpt, _b = _a.min, min = _b === void 0 ? 1 : _b, _c = _a.max, max = _c === void 0 ? 4 : _c;
if (scale > max) {
scale = max;
}
else if (scale < min) {
scale = min;
}
return scale;
};
Zoom.prototype.registorHooks = function (hooks, name, handler) {
hooks.on(name, handler, this);
this.hooksFn.push([hooks, name, handler]);
};
Zoom.pluginName = 'zoom';
return Zoom;
}());
var compatibleFeatures = {
duplicateClick: function (_a) {
var parentScroll = _a[0], childScroll = _a[1];
// no need to make childScroll's click true
if (parentScroll.options.click && childScroll.options.click) {
childScroll.options.click = false;
}
},
nestedScroll: function (scrollsPair) {
var parentScroll = scrollsPair[0], childScroll = scrollsPair[1];
var parentScrollX = parentScroll.options.scrollX;
var parentScrollY = parentScroll.options.scrollY;
var childScrollX = childScroll.options.scrollX;
var childScrollY = childScroll.options.scrollY;
// vertical nested in vertical scroll and horizontal nested in horizontal
// otherwise, no need to handle.
if (parentScrollX === childScrollX || parentScrollY === childScrollY) {
scrollsPair.forEach(function (scroll, index) {
var oppositeScroll = scrollsPair[(index + 1) % 2];
scroll.on('beforeScrollStart', function () {
if (oppositeScroll.pending) {
oppositeScroll.stop();
oppositeScroll.resetPosition();
}
setupData(oppositeScroll);
oppositeScroll.disable();
});
scroll.on('touchEnd', function () {
oppositeScroll.enable();
});
});
childScroll.on('scrollStart', function () {
if (checkBeyondBoundary(childScroll)) {
childScroll.disable();
parentScroll.enable();
}
});
}
}
};
var NestedScroll = /** @class */ (function () {
function NestedScroll(scroll) {
var singleton = NestedScroll.nestedScroll;
if (!(singleton instanceof NestedScroll)) {
singleton = NestedScroll.nestedScroll = this;
singleton.stores = [];
}
singleton.setup(scroll);
singleton.addHooks(scroll);
return singleton;
}
NestedScroll.prototype.setup = function (scroll) {
this.appendBScroll(scroll);
this.handleContainRelationship();
this.handleCompatible();
};
NestedScroll.prototype.addHooks = function (scroll) {
var _this = this;
scroll.on('destroy', function () {
_this.teardown(scroll);
});
};
NestedScroll.prototype.teardown = function (scroll) {
this.removeBScroll(scroll);
this.handleContainRelationship();
this.handleCompatible();
};
NestedScroll.prototype.appendBScroll = function (scroll) {
this.stores.push(scroll);
};
NestedScroll.prototype.removeBScroll = function (scroll) {
var index = this.stores.indexOf(scroll);
if (index === -1)
return;
scroll.wrapper.isBScrollContainer = undefined;
this.stores.splice(index, 1);
};
NestedScroll.prototype.handleContainRelationship = function () {
// bs's length <= 1
var stores = this.stores;
if (stores.length <= 1) {
// there is only a childBScroll left.
if (stores[0] && stores[0].__parentInfo) {
stores[0].__parentInfo = undefined;
}
return;
}
var outerBS;
var outerBSWrapper;
var innerBS;
var innerBSWrapper;
// Need two layers of "For loop" to calculate parent-child relationship
for (var i = 0; i < stores.length; i++) {
outerBS = stores[i];
outerBSWrapper = outerBS.wrapper;
for (var j = 0; j < stores.length; j++) {
innerBS = stores[j];
innerBSWrapper = innerBS.wrapper;
// same bs
if (outerBS === innerBS)
continue;
// now start calculating
if (!innerBSWrapper.contains(outerBSWrapper))
continue;
// now innerBS contains outerBS
// no parentInfo yet
if (!outerBS.__parentInfo) {
outerBS.__parentInfo = {
parent: innerBS,
depth: calculateDepths(outerBSWrapper, innerBSWrapper)
};
}
else {
// has parentInfo already!
// just judge the "true" parent by depth
// we regard the latest node as parent, not the furthest
var currentDepths = calculateDepths(outerBSWrapper, innerBSWrapper);
var prevDepths = outerBS.__parentInfo.depth;
// refresh currentBS as parentScroll
if (prevDepths > currentDepths) {
outerBS.__parentInfo = {
parent: innerBS,
depth: currentDepths
};
}
}
}
}
};
NestedScroll.prototype.handleCompatible = function () {
var pairs = this.availableBScrolls();
var keys = ['duplicateClick', 'nestedScroll'];
pairs.forEach(function (pair) {
keys.forEach(function (key) {
compatibleFeatures[key](pair);
});
});
};
NestedScroll.prototype.availableBScrolls = function () {
var ret = [];
ret = this.stores
.filter(function (bs) { return !!bs.__parentInfo; })
.map(function (bs) { return [bs.__parentInfo.parent, bs]; });
return ret;
};
NestedScroll.pluginName = 'nestedScroll';
return NestedScroll;
}());
function calculateDepths(childNode, parentNode) {
var depth = 0;
var parent = childNode.parentNode;
while (parent && parent !== parentNode) {
depth++;
parent = parent.parentNode;
}
return depth;
}
function checkBeyondBoundary(scroll) {
var _a = hasScroll(scroll), hasHorizontalScroll = _a.hasHorizontalScroll, hasVerticalScroll = _a.hasVerticalScroll;
var _b = scroll.scroller, scrollBehaviorX = _b.scrollBehaviorX, scrollBehaviorY = _b.scrollBehaviorY;
var hasReachLeft = scroll.x >= scroll.minScrollX && scrollBehaviorX.movingDirection === -1;
var hasReachRight = scroll.x <= scroll.maxScrollX && scrollBehaviorX.movingDirection === 1;
var hasReachTop = scroll.y >= scroll.minScrollY && scrollBehaviorY.movingDirection === -1;
var hasReachBottom = scroll.y <= scroll.maxScrollY && scrollBehaviorY.movingDirection === 1;
if (hasVerticalScroll) {
return hasReachTop || hasReachBottom;
}
else if (hasHorizontalScroll) {
return hasReachLeft || hasReachRight;
}
return false;
}
function setupData(scroll) {
var _a = hasScroll(scroll), hasHorizontalScroll = _a.hasHorizontalScroll, hasVerticalScroll = _a.hasVerticalScroll;
var _b = scroll.scroller, actions = _b.actions, scrollBehaviorX = _b.scrollBehaviorX, scrollBehaviorY = _b.scrollBehaviorY;
actions.startTime = +new Date();
if (hasVerticalScroll) {
scrollBehaviorY.startPos = scrollBehaviorY.currentPos;
}
else if (hasHorizontalScroll) {
scrollBehaviorX.startPos = scrollBehaviorX.currentPos;
}
}
function hasScroll(scroll) {
return {
hasHorizontalScroll: scroll.scroller.scrollBehaviorX.hasScroll,
hasVerticalScroll: scroll.scroller.scrollBehaviorY.hasScroll
};
}
var PRE_NUM = 10;
var POST_NUM = 30;
var IndexCalculator = /** @class */ (function () {
function IndexCalculator(wrapperHeight, tombstoneHeight) {
this.wrapperHeight = wrapperHeight;
this.tombstoneHeight = tombstoneHeight;
this.lastDirection = 1 /* DOWN */;
this.lastPos = 0;
}
IndexCalculator.prototype.calculate = function (pos, list) {
var offset = pos - this.lastPos;
this.lastPos = pos;
var direction = this.getDirection(offset);
// important! start index is much more important than end index.
var start = this.calculateIndex(0, pos, list);
var end = this.calculateIndex(start, pos + this.wrapperHeight, list);
if (direction === 1 /* DOWN */) {
start -= PRE_NUM;
end += POST_NUM;
}
else {
start -= POST_NUM;
end += PRE_NUM;
}
if (start < 0) {
start = 0;
}
return {
start: start,
end: end
};
};
IndexCalculator.prototype.getDirection = function (offset) {
var direction;
if (offset > 0) {
direction = 1 /* DOWN */;
}
else if (offset < 0) {
direction = 0 /* UP */;
}
else {
return this.lastDirection;
}
this.lastDirection = direction;
return direction;
};
IndexCalculator.prototype.calculateIndex = function (start, offset, list) {
if (offset <= 0) {
return start;
}
var i = start;
var startPos = list[i] && list[i].pos !== -1 ? list[i].pos : 0;
var lastPos = startPos;
var tombstone = 0;
while (i < list.length && list[i].pos < offset) {
lastPos = list[i].pos;
i++;
}
if (i === list.length) {
tombstone = Math.floor((offset - lastPos) / this.tombstoneHeight);
}
i += tombstone;
return i;
};
return IndexCalculator;
}());
var ListItem = /** @class */ (function () {
function ListItem() {
this.data = null;
this.dom = null;
this.tombstone = null;
this.width = 0;
this.height = 0;
this.pos = 0;
}
return ListItem;
}());
var DataManager = /** @class */ (function () {
function DataManager(list, fetchFn, onFetchFinish) {
this.fetchFn = fetchFn;
this.onFetchFinish = onFetchFinish;
this.loadedNum = 0;
this.fetching = false;
this.hasMore = true;
this.list = list || [];
}
DataManager.prototype.update = function (end) {
return __awaiter(this, void 0, void 0, function () {
var len;
return __generator(this, function (_a) {
if (!this.hasMore) {
end = Math.min(end, this.list.length);
}
// add data placeholder
if (end > this.list.length) {
len = end - this.list.length;
this.addEmptyData(len);
}
// tslint:disable-next-line: no-floating-promises
return [2 /*return*/, this.checkToFetch(end)];
});
});
};
DataManager.prototype.add = function (data) {
for (var i = 0; i < data.length; i++) {
if (!this.list[this.loadedNum]) {
this.list[this.loadedNum] = { data: data[i] };
}
else {
this.list[this.loadedNum] = __assign({}, this.list[this.loadedNum], { data: data[i] });
}
this.loadedNum++;
}
return this.list;
};
DataManager.prototype.addEmptyData = function (len) {
for (var i = 0; i < len; i++) {
this.list.push(new ListItem());
}
return this.list;
};
DataManager.prototype.fetch = function (len) {
return __awaiter(this, void 0, void 0, function () {
var data;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.fetching) {
return [2 /*return*/, []];
}
this.fetching = true;
return [4 /*yield*/, this.fetchFn(len)];
case 1:
data = _a.sent();
this.fetching = false;
return [2 /*return*/, data];
}
});
});
};
DataManager.prototype.checkToFetch = function (end) {
return __awaiter(this, void 0, void 0, function () {
var min, newData, currentEnd;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.hasMore) {
return [2 /*return*/];
}
if (end <= this.loadedNum) {
return [2 /*return*/];
}
min = end - this.loadedNum;
return [4 /*yield*/, this.fetch(min)];
case 1:
newData = _a.sent();
if (newData instanceof Array && newData.length) {
this.add(newData);
currentEnd = this.onFetchFinish(this.list, true);
return [2 /*return*/, this.checkToFetch(currentEnd)];
}
else if (typeof newData === 'boolean' && newData === false) {
this.hasMore = false;
this.list.splice(this.loadedNum);
this.onFetchFinish(this.list, false);
}
return [2 /*return*/];
}
});
});
};
DataManager.prototype.getList = function () {
return this.list;
};
return DataManager;
}());
var Tombstone = /** @class */ (function () {
function Tombstone(create) {
this.create = create;
this.cached = [];
this.width = 0;
this.height = 0;
this.initialed = false;
this.getSize();
}
Tombstone.isTombstone = function (el) {
if (el && el.classList) {
return el.classList.contains('tombstone');
}
return false;
};
Tombstone.prototype.getSize = function () {
if (!this.initialed) {
var tombstone = this.create();
tombstone.style.position = 'absolute';
document.body.appendChild(tombstone);
tombstone.style.display = '';
this.height = tombstone.offsetHeight;
this.width = tombstone.offsetWidth;
document.body.removeChild(tombstone);
this.cached.push(tombstone);
}
};
Tombstone.prototype.getOne = function () {
var tombstone = this.cached.pop();
if (tombstone) {
var tombstoneStyle = tombstone.style;
tombstoneStyle.display = '';
tombstoneStyle.opacity = '1';
tombstoneStyle[style.transform] = '';
tombstoneStyle[style.transition] = '';
return tombstone;
}
return this.create();
};
Tombstone.prototype.recycle = function (tombstones) {
for (var _i = 0, tombstones_1 = tombstones; _i < tombstones_1.length; _i++) {
var tombstone = tombstones_1[_i];
tombstone.style.display = 'none';
this.cached.push(tombstone);
}
return this.cached;
};
Tombstone.prototype.recycleOne = function (tombstone) {
this.cached.push(tombstone);
return this.cached;
};
return Tombstone;
}());
var ANIMATION_DURATION_MS = 200;
var DomManager = /** @class */ (function () {
function DomManager(content, renderFn, tombstone) {
this.content = content;
this.renderFn = renderFn;
this.tombstone = tombstone;
this.unusedDom = [];
this.timers = [];
}
DomManager.prototype.update = function (list, start, end) {
if (start >= list.length) {
start = list.length - 1;
}
if (end > list.length) {
end = list.length;
}
this.collectUnusedDom(list, start, end);
this.createDom(list, start, end);
this.cacheHeight(list, start, end);
var _a = this.positionDom(list, start, end), startPos = _a.startPos, startDelta = _a.startDelta, endPos = _a.endPos;
return {
start: start,
startPos: startPos,
startDelta: startDelta,
end: end,
endPos: endPos
};
};
DomManager.prototype.collectUnusedDom = function (list, start, end) {
// TODO optimise
for (var i = 0; i < list.length; i++) {
if (i === start) {
i = end - 1;
continue;
}
if (list[i].dom) {
var dom = list[i].dom;
if (Tombstone.isTombstone(dom)) {
this.tombstone.recycleOne(dom);
dom.style.display = 'none';
}
else {
this.unusedDom.push(dom);
}
list[i].dom = null;
}
}
return list;
};
DomManager.prototype.createDom = function (list, start, end) {
for (var i = start; i < end; i++) {
var dom = list[i].dom;
var data = list[i].data;
if (dom) {
if (Tombstone.isTombstone(dom) && data) {
list[i].tombstone = dom;
list[i].dom = null;
}
else {
continue;
}
}
dom = data
? this.renderFn(data, this.unusedDom.pop())
: this.tombstone.getOne();
dom.style.position = 'absolute';
list[i].dom = dom;
list[i].pos = -1;
this.content.appendChild(dom);
}
};
DomManager.prototype.cacheHeight = function (list, start, end) {
for (var i = start; i < end; i++) {
if (list[i].data && !list[i].height) {
list[i].height = list[i].dom.offsetHeight;
}
}
};
DomManager.prototype.positionDom = function (list, start, end) {
var _this = this;
var tombstoneEles = [];
var _a = this.getStartPos(list, start, end), startPos = _a.start, startDelta = _a.delta;
var pos = startPos;
// TODO transition
for (var i = start; i < end; i++) {
var tombstone = list[i].tombstone;
if (tombstone) {
var tombstoneStyle = tombstone.style;
tombstoneStyle[style.transition] = cssVendor + "transform " + ANIMATION_DURATION_MS + "ms, opacity " + ANIMATION_DURATION_MS + "ms";
tombstoneStyle[style.transform] = "translateY(" + pos + "px)";
tombstoneStyle.opacity = '0';
list[i].tombstone = null;
tombstoneEles.push(tombstone);
}
if (list[i].dom && list[i].pos !== pos) {
list[i].dom.style[style.transform] = "translateY(" + pos + "px)";
list[i].pos = pos;
}
pos += list[i].height || this.tombstone.height;
}
var timerId = window.setTimeout(function () {
_this.tombstone.recycle(tombstoneEles);
}, ANIMATION_DURATION_MS);
this.timers.push(timerId);
return {
startPos: startPos,
startDelta: startDelta,
endPos: pos
};
};
DomManager.prototype.getStartPos = function (list, start, end) {
if (list[start] && list[start].pos !== -1) {
return {
start: list[start].pos,
delta: 0
};
}
// TODO optimise
var pos = list[0].pos === -1 ? 0 : list[0].pos;
for (var i_1 = 0; i_1 < start; i_1++) {
pos += list[i_1].height || this.tombstone.height;
}
var originPos = pos;
var i;
for (i = start; i < end; i++) {
if (!Tombstone.isTombstone(list[i].dom) && list[i].pos !== -1) {
pos = list[i].pos;
break;
}
}
var x = i;
if (x < end) {
while (x > start) {
pos -= list[x - 1].height;
x--;
}
}
var delta = originPos - pos;
return {
start: pos,
delta: delta
};
};
DomManager.prototype.removeTombstone = function () {
var tombstones = this.content.querySelectorAll('.tombstone');
for (var i = tombstones.length - 1; i >= 0; i--) {
this.content.removeChild(tombstones[i]);
}
};
DomManager.prototype.destroy = function () {
this.removeTombstone();
this.timers.forEach(function (id) {
clearTimeout(id);
});
};
return DomManager;
}());
var EXTRA_SCROLL_Y = -2000;
var InfinityScroll = /** @class */ (function () {
function InfinityScroll(bscroll) {
this.bscroll = bscroll;
this.start = 0;
this.end = 0;
if (bscroll.options.infinity) {
this.bscroll.options.probeType = 3 /* Realtime */;
this.bscroll.scroller.scrollBehaviorY.hasScroll = true;
this.bscroll.scroller.scrollBehaviorY.maxScrollPos = EXTRA_SCROLL_Y;
this.init(bscroll.options.infinity);
}
}
InfinityScroll.prototype.init = function (options) {
var fetchFn = options.fetch, renderFn = options.render, createTombstoneFn = options.createTombstone;
this.tombstone = new Tombstone(createTombstoneFn);
this.indexCalculator = new IndexCalculator(this.bscroll.scroller.scrollBehaviorY.wrapperSize, this.tombstone.height);
this.domManager = new DomManager(this.bscroll.scroller.content, renderFn, this.tombstone);
this.dataManager = new DataManager([], fetchFn, this.onFetchFinish.bind(this));
this.bscroll.on('destroy', this.destroy, this);
this.bscroll.on('scroll', this.update, this);
this.update({ y: 0 });
};
InfinityScroll.prototype.update = function (pos) {
var position = Math.round(-pos.y);
// important! calculate start/end index to render
var _a = this.indexCalculator.calculate(position, this.dataManager.getList()), start = _a.start, end = _a.end;
this.start = start;
this.end = end;
// tslint:disable-next-line: no-floating-promises
this.dataManager.update(end);
this.updateDom(this.dataManager.getList());
};
InfinityScroll.prototype.onFetchFinish = function (list, hasMore) {
var end = this.updateDom(list).end;
if (!hasMore) {
this.domManager.removeTombstone();
this.bscroll.scroller.animater.stop();
this.bscroll.resetPosition();
}
// tslint:disable-next-line: no-floating-promises
return end;
};
InfinityScroll.prototype.updateDom = function (list) {
var _a = this.domManager.update(list, this.start, this.end), end = _a.end, startPos = _a.startPos, endPos = _a.endPos, startDelta = _a.startDelta;
if (startDelta) {
this.bscroll.minScrollY = startDelta;
}
if (endPos > this.bscroll.maxScrollY) {
this.bscroll.maxScrollY = -(endPos - this.bscroll.scroller.scrollBehaviorY.wrapperSize);
}
return {
end: end,
startPos: startPos,
endPos: endPos
};
};
InfinityScroll.prototype.destroy = function () {
var content = this.bscroll.scroller.content;
while (content.firstChild) {
content.removeChild(content.firstChild);
}
this.domManager.destroy();
this.bscroll.off('scroll', this.update);
this.bscroll.off('destroy', this.destroy);
};
InfinityScroll.pluginName = 'infinity';
return InfinityScroll;
}());
BScroll.use(MouseWheel)
.use(ObserveDOM)
.use(PullDown)
.use(PullUp)
.use(ScrollBar)
.use(Slide)
.use(Wheel)
.use(Zoom)
.use(NestedScroll)
.use(InfinityScroll);
export default BScroll;
|
describe('addClassDecorator', function () {
it('should call the decorate method when the Decorator is invoked', function () {
var info = {decorate: jasmine.createSpy('decorate')};
BaseClass.addClassDecorator('decorator', info);
BaseClass('name', function () {
~decorator();
});
expect(info.decorate).toHaveBeenCalled();
});
it('should call the decorate method with the correct parameters', function () {
var info = {decorate: jasmine.createSpy('decorate')};
BaseClass.addClassDecorator('decorator', info);
var aClass = BaseClass('name', function () {
~decorator(1, true);
});
expect(info.decorate).toHaveBeenCalledWith(aClass.$class, 1, true);
});
it('should allow nested Decorators', function () {
var info = {decorate: jasmine.createSpy('decorate')};
BaseClass.addClassDecorator('decorator', info);
BaseClass.addClassDecorator('decorator.A', info);
BaseClass.addClassDecorator('decorator.A.B', info);
BaseClass.addClassDecorator('decorator.A.B.C.D.E', info);
BaseClass.addClassDecorator('decorator.A.B.C.F', info);
BaseClass('name', function () {
+decorator();
+decorator.A();
+decorator.A.B();
+decorator.A.B.C.D.E();
+decorator.A.B.C.F();
});
expect(info.decorate.calls.count()).toBe(5);
});
it('should temporarily add the Decorator to the resulting class', function () {
var info = {decorate: jasmine.createSpy('decorate')};
BaseClass.addClassDecorator('decorator', info);
var aClass = BaseClass('name', function () {
expect(typeof this.decorator).toBe('function');
+this.decorator(1, true);
});
expect(aClass.decorator).toBeUndefined();
expect(info.decorate).toHaveBeenCalledWith(aClass.$class, 1, true);
});
describe('globalize: false', function () {
it('should not globalize the Decorator by default', function () {
var info = {decorate: jasmine.createSpy('decorate')};
BaseClass.addClassDecorator('decorator', info);
expect(typeof decorator).toBe('undefined');
BaseClass('name', function () {
expect(typeof decorator).toBe('function');
+decorator();
});
expect(typeof decorator).toBe('undefined');
expect(info.decorate.calls.count()).toBe(1);
});
it('should apply the Decorator to the Class being currently built', function () {
var info = {decorate: jasmine.createSpy('decorate')};
BaseClass.addClassDecorator('decorator', info);
var aClass, aClass2;
var aClass = BaseClass('name1', function () {
+decorator();
aClass2 = BaseClass('name2', function () {
+decorator();
});
});
expect(info.decorate.calls.argsFor(0)).toEqual([aClass.$class]);
expect(info.decorate.calls.argsFor(1)).toEqual([aClass2.$class]);
});
});
describe('globalize: true', function () {
it('should globalize the Decorator if asked to', function () {
var info = {decorate: jasmine.createSpy('decorate'), globalize: true};
BaseClass.addClassDecorator('decorator', info);
expect(typeof decorator).toBe('function');
BaseClass('name1', function () {
expect(typeof decorator).toBe('function');
});
expect(typeof decorator).toBe('function');
});
it('should apply the Decorator to the next Class', function () {
var info = {decorate: jasmine.createSpy('decorate'), globalize: true};
BaseClass.addClassDecorator('decorator', info);
var aClass, aClass2;
+decorator();
aClass = BaseClass('name1', function () {
+decorator();
aClass2 = BaseClass('name2', ot.noop);
});
expect(info.decorate.calls.argsFor(0)).toEqual([aClass.$class]);
expect(info.decorate.calls.argsFor(1)).toEqual([aClass2.$class]);
});
it('should only apply the Decorator to its ClassDefiner branch', function () {
var infoParent = {decorate: jasmine.createSpy('parentDec'), globalize: true},
infoChild = {decorate: jasmine.createSpy('childDec'), globalize: true},
childClass = BaseClass.child('child'),
diffBranchClass = BaseClass.child('diffBranchClass'),
aClass;
BaseClass.addClassDecorator('parentDec', infoParent);
childClass.addClassDecorator('childDec', infoChild);
// on same branch
+parentDec();
+childDec();
aClass = childClass('name', ot.noop);
expect(infoParent.decorate).toHaveBeenCalledWith(aClass.$class);
expect(infoChild.decorate).toHaveBeenCalledWith(aClass.$class);
infoParent.decorate.calls.reset();
infoChild.decorate.calls.reset();
// on parent's branch
+parentDec();
+childDec();
aClass = BaseClass('name', ot.noop);
expect(infoParent.decorate).toHaveBeenCalledWith(aClass.$class);
expect(infoChild.decorate).not.toHaveBeenCalled();
aClass = childClass('name', ot.noop);
expect(infoChild.decorate).toHaveBeenCalledWith(aClass.$class);
infoParent.decorate.calls.reset();
infoChild.decorate.calls.reset();
// on different branch
+parentDec();
+childDec();
aClass = diffBranchClass('name', ot.noop);
expect(infoParent.decorate).toHaveBeenCalledWith(aClass.$class);
expect(infoChild.decorate).not.toHaveBeenCalled();
aClass = childClass('name', ot.noop);
expect(infoChild.decorate).toHaveBeenCalledWith(aClass.$class);
});
});
describe('on', function () {
it('should register the listeners to the events only once', function () {
var info = {decorate: ot.noop, on: {
event1: jasmine.createSpy('event1'),
event2: jasmine.createSpy('event2')
}};
BaseClass.addClassDecorator('decorator', info);
var aClass = BaseClass('name', function () {
+decorator();
+decorator();
});
aClass.$class.emit('event1', [1]);
aClass.$class.emit('event2', [true]);
expect(info.on.event1.calls.count()).toBe(1);
expect(info.on.event2.calls.count()).toBe(1);
expect(info.on.event1.calls.first()).toEqual({object: info, args: [1]});
expect(info.on.event2.calls.first()).toEqual({object: info, args: [true]});
});
});
});
|
'use strict';
const stateModule = angular.module('hkRouter', ['ui.router']);
stateModule
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
/////////////////////////////
// Redirects and Otherwise //
/////////////////////////////
$urlRouterProvider.otherwise("/attractions");
// state provider
$stateProvider
.state('attractions',
{
url: '/attractions',
templateUrl: 'partials/attraction.html',
resolve: {
locationResult : [ 'Accessible', function(Accessible) {
return Accessible.get('facilities/attractions.json', 'attractions');
}],
translateHeader: ['$translate', function($translate) {
return $translate('ATTRACTION');
}]
},
controller: 'AccessibleCtrl',
controllerAs: 'vm'
})
.state('shopping_dining',
{
url: '/shopping_dining',
templateUrl: 'partials/attraction.html',
resolve: {
locationResult : [ 'Accessible', function(Accessible) {
return Accessible.get('facilities/shoppings.json', 'shopping-dining');
}],
translateHeader: ['$translate', function($translate) {
return $translate('SHOPPING');
}]
},
controller: 'AccessibleCtrl',
controllerAs: 'vm'
})
.state('hotels',
{
url: '/hotels',
templateUrl: 'partials/attraction.html',
resolve: {
locationResult : [ 'Accessible', function(Accessible) {
return Accessible.get('facilities/hotels.json', 'hotels');
}],
translateHeader: ['$translate', function($translate) {
return $translate('HOTEL');
}]
},
controller: 'AccessibleCtrl',
controllerAs: 'vm'
})
.state('other_venues',
{
url: '/other_venues',
templateUrl: 'partials/attraction.html',
resolve: {
locationResult : [ 'Accessible', function(Accessible) {
return Accessible.get('facilities/other_venues.json', 'other-venues');
}],
translateHeader: ['$translate', function($translate) {
return $translate('OTHERVENUE');
}]
},
controller: 'AccessibleCtrl',
controllerAs: 'vm'
})
// .state('geolocation',
// {
// url: '/geolocation',
// templateUrl: 'partials/geolocation.html',
// resolve: {
// locationResult : [ 'Accessible', function(Accessible) {
// return Accessible.get("facilities/shoppings.json","shopping-dining");
// }]
// },
// controller: 'MapCtrl',
// controllerAs: 'vm'
// })
.state('related_links',
{
url : '/links',
templateUrl : 'partials/link.html',
controller : 'LinkCtrl',
controllerAs: 'vm'
});
}]);
|
$(function() {
setInterval( function() {
var seconds = new Date().getSeconds();
var sdegree = seconds * 6;
var srotate = "rotate(" + sdegree + "deg)";
$('.dynamic-time').html(moment(new Date()).format("hh:mm:ss A"));
$("#sec").css({"-moz-transform" : srotate, "-webkit-transform" : srotate});
}, 1000 );
setInterval( function() {
var hours = new Date().getHours();
var mins = new Date().getMinutes();
var hdegree = hours * 30 + (mins / 2);
var hrotate = "rotate(" + hdegree + "deg)";
$("#hour").css({"-moz-transform" : hrotate, "-webkit-transform" : hrotate});
}, 1000 );
setInterval( function() {
var mins = new Date().getMinutes();
var mdegree = mins * 6;
var mrotate = "rotate(" + mdegree + "deg)";
$("#min").css({"-moz-transform" : mrotate, "-webkit-transform" : mrotate});
}, 1000 );
});
|
angular
.module('AngularCommunicator', [])
.provider('angularCommunicatorService', function() {
var registeredListeners = {};
function buildHierarchicalStructure(reg, splitName, callback) {
(!reg[splitName[0]]) && (reg[splitName[0]] = {listeners: []});
if(splitName.length === 1) {
reg[splitName[0]].listeners.push(callback);
return;
}
var registered = reg[splitName[0]];
splitName.splice(0, 1);
buildHierarchicalStructure(registered, splitName, callback);
}
function unRegisterListener(reg, splitName) {
if(splitName.length === 1) {
reg[splitName[0]] = {listeners: []};
return;
}
var registered = reg[splitName[0]];
splitName.splice(0, 1);
unRegisterListener(registered, splitName);
}
function findNodeListenersToExecute(reg, splitName, params, $exceptionHandler) {
if(splitName.length === 1) {
execNodeListeners(reg[splitName[0]], params, $exceptionHandler);
return;
}
var registered = reg[splitName[0]];
splitName.splice(0, 1);
findNodeListenersToExecute(registered, splitName, params);
}
function execNodeListeners(reg, params, $exceptionHandler) {
for(var i = 0; i < reg.listeners.length; i++) {
try {
reg.listeners[i](params);
} catch(e) {
$exceptionHandler(e);
}
}
var children = Object.keys(reg).filter(function(elem) {
return elem !== 'listeners';
});
for(var child = 0; child < children.length; child++) {
execNodeListeners(reg[children[child]], params, $exceptionHandler);
}
}
function isEmptyObject(obj) {
return Object.keys(obj).length === 0 && JSON.stringify(obj) === JSON.stringify({});
}
function isInvalidKey(key) {
return typeof key !== 'string';
}
this.$get = ['$exceptionHandler', function($exceptionHandler) {
var registerHierarchicalListener = function(key, listener) {
if(arguments.length < 2) {
throw 'Invalid number of arguments';
}
if(isInvalidKey(key)) {
throw 'Invalid key';
}
buildHierarchicalStructure(registeredListeners, key.split(':'), listener);
return function() {
unRegisterListener(registeredListeners, key.split(':'));
}
};
var removeRegisteredListener = function(key) {
if(isInvalidKey(key)) {
throw 'Invalid key';
}
if(isEmptyObject(registeredListeners)) {
return;
}
unRegisterListener(registeredListeners, key.split(':'))
};
var execGroupedListeners = function(keys, params) {
if(Array.isArray(keys)) {
if(isEmptyObject(registeredListeners)) {
return;
}
var args = Array.isArray(params) ? params : [params];
for(var i = 0; i < keys.length; i++) {
findNodeListenersToExecute(registeredListeners, keys[i].split(':'), args[i] || args[0], $exceptionHandler);
}
return;
}
if(isInvalidKey(keys)) {
throw 'Invalid key';
}
if(isEmptyObject(registeredListeners)) {
return;
}
findNodeListenersToExecute(registeredListeners, keys.split(':'), params, $exceptionHandler);
};
var clearListeners = function() {
registeredListeners = {};
};
return {
on: registerHierarchicalListener,
remove: removeRegisteredListener,
exec: execGroupedListeners,
clear: clearListeners
};
}];
});
|
import React from 'react';
import SvgImage from 'components/svg-image';
import ChartLabel from 'components/chart-label';
import { getLayout } from 'layouts/flexbox';
import getCenter from 'decorators/get-center';
@getCenter
export default class HorizontalBarDetail extends React.Component {
static propTypes = {
height: React.PropTypes.number.isRequired,
icon: React.PropTypes.string,
iconHeight: React.PropTypes.number,
label: React.PropTypes.string,
width: React.PropTypes.number.isRequired,
}
static defaultProps = {
height: 0,
icon: '',
iconHeight: 0,
label: '',
width: 0,
}
state = {
layout: {},
}
componentDidMount() {
this.setStateFromProps(this.props);
}
componentWillReceiveProps(nextProps) {
this.setStateFromProps(nextProps);
}
getLayout(props) {
return getLayout(React.findDOMNode(this), {
alignItems: 'center',
flexDirection: 'row',
flexWrap: 'nowrap',
height: props.height,
justifyContent: 'flex-end',
width: props.width,
}, [
{style: {marginRight: 10}},
{style: {marginRight: 10}},
]);
}
setStateFromProps(props) {
this.setState({
centerY: this.getCenter(props.height),
layout: this.getLayout(props),
});
}
render() {
return (
<g className={'horizontal-bar-detail'}>
{this.props.label ? (
<ChartLabel
className={'horizontal-bar-detail-label'}
text={this.props.label}
x={this.state.layout.children ? this.state.layout.children[0].left : 0}
y={this.state.centerY} />
) : null}
{this.props.icon ? (
<SvgImage
className={'horizontal-bar-detail-icon'}
height={this.props.iconHeight}
url={this.props.icon}
width={this.props.iconHeight}
x={this.state.layout.children ? this.state.layout.children[1].left : 0}
y={this.state.layout.children ? this.state.layout.children[1].top : 0} />
) : null}
</g>
);
}
}
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['408',"Tlece.Recruitment.Controllers Namespace","topic_000000000000018A.html"],['597',"SiteManagementController Class","topic_000000000000022F.html"],['599',"Methods","topic_000000000000022F_methods--.html"],['605',"PostCreateSubscription Method","topic_0000000000000236.html"]];
|
;(function(jqi, $, undefined) {
function Dive(index, $step, $previous, options) {
var z = $step.attr('data-z'),
x = $previous.attr('data-x'),
y = $previous.attr('data-y');
if (!z) z = -2000;
else z = parseInt(z) - 2000;
$step.attr({'data-z' : z, 'data-x' : x, 'data-y' : y });
return this;
}
jqi.Dive = Dive;
}(jqImpress, jQuery));
|
/*!
* DevExtreme (dx.aspnet.mvc.js)
* Version: 20.1.8 (build 20303-1716)
* Build date: Thu Oct 29 2020
*
* Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
! function(factory) {
if ("function" === typeof define && define.amd) {
define(function(require, exports, module) {
module.exports = factory(require("jquery"), require("./core/templates/template_engine_registry").setTemplateEngine, require("./core/templates/template_base").renderedCallbacks, require("./core/guid"), require("./ui/validation_engine"), require("./core/utils/iterator"), require("./core/utils/dom").extractTemplateMarkup, require("./core/utils/string").encodeHtml, require("./core/utils/ajax"), require("./core/utils/console"))
})
} else {
DevExpress.aspnet = factory(window.jQuery, DevExpress.setTemplateEngine, DevExpress.templateRendered, DevExpress.data.Guid, DevExpress.validationEngine, DevExpress.utils.iterator, DevExpress.utils.dom.extractTemplateMarkup, DevExpress.utils.string.encodeHtml, DevExpress.utils.ajax, DevExpress.utils.console)
}
}(function($, setTemplateEngine, templateRendered, Guid, validationEngine, iteratorUtils, extractTemplateMarkup, encodeHtml, ajax, console) {
var templateCompiler = createTemplateCompiler();
var pendingCreateComponentRoutines = [];
var enableAlternativeTemplateTags = true;
var warnBug17028 = false;
function createTemplateCompiler() {
var OPEN_TAG = "<%",
CLOSE_TAG = "%>",
ENCODE_QUALIFIER = "-",
INTERPOLATE_QUALIFIER = "=";
var EXTENDED_OPEN_TAG = /[<[]%/g,
EXTENDED_CLOSE_TAG = /%[>\]]/g;
function acceptText(bag, text) {
if (text) {
bag.push("_.push(", JSON.stringify(text), ");")
}
}
function acceptCode(bag, code) {
var encode = code.charAt(0) === ENCODE_QUALIFIER,
value = code.substr(1),
interpolate = code.charAt(0) === INTERPOLATE_QUALIFIER;
if (encode || interpolate) {
bag.push("_.push(");
bag.push(encode ? "arguments[1](" + value + ")" : value);
bag.push(");")
} else {
bag.push(code + "\n")
}
}
return function(text) {
var bag = ["var _ = [];", "with(obj||{}) {"],
chunks = text.split(enableAlternativeTemplateTags ? EXTENDED_OPEN_TAG : OPEN_TAG);
if (warnBug17028 && chunks.length > 1) {
if (text.indexOf(OPEN_TAG) > -1) {
console.logger.warn("Please use an alternative template syntax: https://community.devexpress.com/blogs/aspnet/archive/2020/01/29/asp-net-core-new-syntax-to-fix-razor-issue.aspx");
warnBug17028 = false
}
}
acceptText(bag, chunks.shift());
for (var i = 0; i < chunks.length; i++) {
var tmp = chunks[i].split(enableAlternativeTemplateTags ? EXTENDED_CLOSE_TAG : CLOSE_TAG);
if (2 !== tmp.length) {
throw "Template syntax error"
}
acceptCode(bag, tmp[0]);
acceptText(bag, tmp[1])
}
bag.push("}", "return _.join('')");
return new Function("obj", bag.join(""))
}
}
function createTemplateEngine() {
return {
compile: function(element) {
return templateCompiler(extractTemplateMarkup(element))
},
render: function(template, data) {
var html = template(data, encodeHtml);
var dxMvcExtensionsObj = window.MVCx;
if (dxMvcExtensionsObj && !dxMvcExtensionsObj.isDXScriptInitializedOnLoad) {
html = html.replace(/(<script[^>]+)id="dxss_.+?"/g, "$1")
}
return html
}
}
}
function getValidationSummary(validationGroup) {
var result;
$(".dx-validationsummary").each(function(_, element) {
var summary = $(element).data("dxValidationSummary");
if (summary && summary.option("validationGroup") === validationGroup) {
result = summary;
return false
}
});
return result
}
function createValidationSummaryItemsFromValidators(validators, editorNames) {
var items = [];
iteratorUtils.each(validators, function(_, validator) {
var widget = validator.$element().data("dx-validation-target");
if (widget && $.inArray(widget.option("name"), editorNames) > -1) {
items.push({
text: widget.option("validationError.message"),
validator: validator
})
}
});
return items
}
function createComponent(name, options, id, validatorOptions) {
var selector = "#" + String(id).replace(/[^\w-]/g, "\\$&");
pendingCreateComponentRoutines.push(function() {
var $element = $(selector);
if ($element.length) {
var $component = $(selector)[name](options);
if ($.isPlainObject(validatorOptions)) {
$component.dxValidator(validatorOptions)
}
return true
}
return false
})
}
templateRendered.add(function() {
var snapshot = pendingCreateComponentRoutines.slice();
var leftover = [];
pendingCreateComponentRoutines = [];
snapshot.forEach(function(func) {
if (!func()) {
leftover.push(func)
}
});
pendingCreateComponentRoutines = pendingCreateComponentRoutines.concat(leftover)
});
return {
createComponent: createComponent,
renderComponent: function(name, options, id, validatorOptions) {
id = id || "dx-" + new Guid;
createComponent(name, options, id, validatorOptions);
return '<div id="' + id + '"></div>'
},
getEditorValue: function(inputName) {
var $widget = $("input[name='" + inputName + "']").closest(".dx-widget");
if ($widget.length) {
var dxComponents = $widget.data("dxComponents"),
widget = $widget.data(dxComponents[0]);
if (widget) {
return widget.option("value")
}
}
},
setTemplateEngine: function() {
if (setTemplateEngine) {
setTemplateEngine(createTemplateEngine())
}
},
enableAlternativeTemplateTags: function(value) {
enableAlternativeTemplateTags = value
},
warnBug17028: function() {
warnBug17028 = true
},
createValidationSummaryItems: function(validationGroup, editorNames) {
var groupConfig, items, summary = getValidationSummary(validationGroup);
if (summary) {
groupConfig = validationEngine.getGroupConfig(validationGroup);
if (groupConfig) {
items = createValidationSummaryItemsFromValidators(groupConfig.validators, editorNames);
items.length && summary.option("items", items)
}
}
},
sendValidationRequest: function(propertyName, propertyValue, url, method) {
var d = $.Deferred();
var data = {};
data[propertyName] = propertyValue;
ajax.sendRequest({
url: url,
dataType: "json",
method: method || "GET",
data: data
}).then(function(response) {
if ("string" === typeof response) {
d.resolve({
isValid: false,
message: response
})
} else {
d.resolve(response)
}
}, function(xhr) {
d.reject({
isValid: false,
message: xhr.responseText
})
});
return d.promise()
}
}
});
|
/*!
* DevExtreme (dx.messages.en.js)
* Version: 22.1.0 (build 22018-0314)
* Build date: Tue Jan 18 2022
*
* Copyright (c) 2012 - 2022 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define((function(require) {
factory(require("devextreme/localization"))
}))
} else if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}(0, (function(localization) {
localization.loadMessages({
en: {
Yes: "Yes",
No: "No",
Cancel: "Cancel",
Clear: "Clear",
Done: "Done",
Loading: "Loading...",
Select: "Select...",
Search: "Search",
Back: "Back",
OK: "OK",
"dxCollectionWidget-noDataText": "No data to display",
"dxDropDownEditor-selectLabel": "Select",
"validation-required": "Required",
"validation-required-formatted": "{0} is required",
"validation-numeric": "Value must be a number",
"validation-numeric-formatted": "{0} must be a number",
"validation-range": "Value is out of range",
"validation-range-formatted": "{0} is out of range",
"validation-stringLength": "The length of the value is not correct",
"validation-stringLength-formatted": "The length of {0} is not correct",
"validation-custom": "Value is invalid",
"validation-custom-formatted": "{0} is invalid",
"validation-async": "Value is invalid",
"validation-async-formatted": "{0} is invalid",
"validation-compare": "Values do not match",
"validation-compare-formatted": "{0} does not match",
"validation-pattern": "Value does not match pattern",
"validation-pattern-formatted": "{0} does not match pattern",
"validation-email": "Email is invalid",
"validation-email-formatted": "{0} is invalid",
"validation-mask": "Value is invalid",
"dxLookup-searchPlaceholder": "Minimum character number: {0}",
"dxList-pullingDownText": "Pull down to refresh...",
"dxList-pulledDownText": "Release to refresh...",
"dxList-refreshingText": "Refreshing...",
"dxList-pageLoadingText": "Loading...",
"dxList-nextButtonText": "More",
"dxList-selectAll": "Select All",
"dxListEditDecorator-delete": "Delete",
"dxListEditDecorator-more": "More",
"dxScrollView-pullingDownText": "Pull down to refresh...",
"dxScrollView-pulledDownText": "Release to refresh...",
"dxScrollView-refreshingText": "Refreshing...",
"dxScrollView-reachBottomText": "Loading...",
"dxDateBox-simulatedDataPickerTitleTime": "Select time",
"dxDateBox-simulatedDataPickerTitleDate": "Select date",
"dxDateBox-simulatedDataPickerTitleDateTime": "Select date and time",
"dxDateBox-validation-datetime": "Value must be a date or time",
"dxFileUploader-selectFile": "Select file",
"dxFileUploader-dropFile": "or Drop file here",
"dxFileUploader-bytes": "bytes",
"dxFileUploader-kb": "kb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-upload": "Upload",
"dxFileUploader-uploaded": "Uploaded",
"dxFileUploader-readyToUpload": "Ready to upload",
"dxFileUploader-uploadAbortedMessage": "Upload cancelled",
"dxFileUploader-uploadFailedMessage": "Upload failed",
"dxFileUploader-invalidFileExtension": "File type is not allowed",
"dxFileUploader-invalidMaxFileSize": "File is too large",
"dxFileUploader-invalidMinFileSize": "File is too small",
"dxRangeSlider-ariaFrom": "From",
"dxRangeSlider-ariaTill": "Till",
"dxSwitch-switchedOnText": "ON",
"dxSwitch-switchedOffText": "OFF",
"dxForm-optionalMark": "optional",
"dxForm-requiredMessage": "{0} is required",
"dxNumberBox-invalidValueMessage": "Value must be a number",
"dxNumberBox-noDataText": "No data",
"dxDataGrid-columnChooserTitle": "Column Chooser",
"dxDataGrid-columnChooserEmptyText": "Drag a column here to hide it",
"dxDataGrid-groupContinuesMessage": "Continues on the next page",
"dxDataGrid-groupContinuedMessage": "Continued from the previous page",
"dxDataGrid-groupHeaderText": "Group by This Column",
"dxDataGrid-ungroupHeaderText": "Ungroup",
"dxDataGrid-ungroupAllText": "Ungroup All",
"dxDataGrid-editingEditRow": "Edit",
"dxDataGrid-editingSaveRowChanges": "Save",
"dxDataGrid-editingCancelRowChanges": "Cancel",
"dxDataGrid-editingDeleteRow": "Delete",
"dxDataGrid-editingUndeleteRow": "Undelete",
"dxDataGrid-editingConfirmDeleteMessage": "Are you sure you want to delete this record?",
"dxDataGrid-validationCancelChanges": "Cancel changes",
"dxDataGrid-groupPanelEmptyText": "Drag a column header here to group by that column",
"dxDataGrid-noDataText": "No data",
"dxDataGrid-searchPanelPlaceholder": "Search...",
"dxDataGrid-filterRowShowAllText": "(All)",
"dxDataGrid-filterRowResetOperationText": "Reset",
"dxDataGrid-filterRowOperationEquals": "Equals",
"dxDataGrid-filterRowOperationNotEquals": "Does not equal",
"dxDataGrid-filterRowOperationLess": "Less than",
"dxDataGrid-filterRowOperationLessOrEquals": "Less than or equal to",
"dxDataGrid-filterRowOperationGreater": "Greater than",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Greater than or equal to",
"dxDataGrid-filterRowOperationStartsWith": "Starts with",
"dxDataGrid-filterRowOperationContains": "Contains",
"dxDataGrid-filterRowOperationNotContains": "Does not contain",
"dxDataGrid-filterRowOperationEndsWith": "Ends with",
"dxDataGrid-filterRowOperationBetween": "Between",
"dxDataGrid-filterRowOperationBetweenStartText": "Start",
"dxDataGrid-filterRowOperationBetweenEndText": "End",
"dxDataGrid-applyFilterText": "Apply filter",
"dxDataGrid-trueText": "true",
"dxDataGrid-falseText": "false",
"dxDataGrid-sortingAscendingText": "Sort Ascending",
"dxDataGrid-sortingDescendingText": "Sort Descending",
"dxDataGrid-sortingClearText": "Clear Sorting",
"dxDataGrid-editingSaveAllChanges": "Save changes",
"dxDataGrid-editingCancelAllChanges": "Discard changes",
"dxDataGrid-editingAddRow": "Add a row",
"dxDataGrid-summaryMin": "Min: {0}",
"dxDataGrid-summaryMinOtherColumn": "Min of {1} is {0}",
"dxDataGrid-summaryMax": "Max: {0}",
"dxDataGrid-summaryMaxOtherColumn": "Max of {1} is {0}",
"dxDataGrid-summaryAvg": "Avg: {0}",
"dxDataGrid-summaryAvgOtherColumn": "Avg of {1} is {0}",
"dxDataGrid-summarySum": "Sum: {0}",
"dxDataGrid-summarySumOtherColumn": "Sum of {1} is {0}",
"dxDataGrid-summaryCount": "Count: {0}",
"dxDataGrid-columnFixingFix": "Fix",
"dxDataGrid-columnFixingUnfix": "Unfix",
"dxDataGrid-columnFixingLeftPosition": "To the left",
"dxDataGrid-columnFixingRightPosition": "To the right",
"dxDataGrid-exportTo": "Export",
"dxDataGrid-exportToExcel": "Export to Excel file",
"dxDataGrid-exporting": "Exporting...",
"dxDataGrid-excelFormat": "Excel file",
"dxDataGrid-selectedRows": "Selected rows",
"dxDataGrid-exportSelectedRows": "Export selected rows",
"dxDataGrid-exportAll": "Export all data",
"dxDataGrid-headerFilterEmptyValue": "(Blanks)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "Cancel",
"dxDataGrid-ariaAdaptiveCollapse": "Hide additional data",
"dxDataGrid-ariaAdaptiveExpand": "Display additional data",
"dxDataGrid-ariaColumn": "Column",
"dxDataGrid-ariaValue": "Value",
"dxDataGrid-ariaFilterCell": "Filter cell",
"dxDataGrid-ariaCollapse": "Collapse",
"dxDataGrid-ariaExpand": "Expand",
"dxDataGrid-ariaDataGrid": "Data grid",
"dxDataGrid-ariaSearchInGrid": "Search in the data grid",
"dxDataGrid-ariaSelectAll": "Select all",
"dxDataGrid-ariaSelectRow": "Select row",
"dxDataGrid-ariaToolbar": "Data grid toolbar",
"dxDataGrid-filterBuilderPopupTitle": "Filter Builder",
"dxDataGrid-filterPanelCreateFilter": "Create Filter",
"dxDataGrid-filterPanelClearFilter": "Clear",
"dxDataGrid-filterPanelFilterEnabledHint": "Enable the filter",
"dxTreeList-ariaTreeList": "Tree list",
"dxTreeList-ariaSearchInGrid": "Search in the tree list",
"dxTreeList-ariaToolbar": "Tree list toolbar",
"dxTreeList-editingAddRowToNode": "Add",
"dxPager-infoText": "Page {0} of {1} ({2} items)",
"dxPager-pagesCountText": "of",
"dxPager-pageSizesAllText": "All",
"dxPivotGrid-grandTotal": "Grand Total",
"dxPivotGrid-total": "{0} Total",
"dxPivotGrid-fieldChooserTitle": "Field Chooser",
"dxPivotGrid-showFieldChooser": "Show Field Chooser",
"dxPivotGrid-expandAll": "Expand All",
"dxPivotGrid-collapseAll": "Collapse All",
"dxPivotGrid-sortColumnBySummary": 'Sort "{0}" by This Column',
"dxPivotGrid-sortRowBySummary": 'Sort "{0}" by This Row',
"dxPivotGrid-removeAllSorting": "Remove All Sorting",
"dxPivotGrid-dataNotAvailable": "N/A",
"dxPivotGrid-rowFields": "Row Fields",
"dxPivotGrid-columnFields": "Column Fields",
"dxPivotGrid-dataFields": "Data Fields",
"dxPivotGrid-filterFields": "Filter Fields",
"dxPivotGrid-allFields": "All Fields",
"dxPivotGrid-columnFieldArea": "Drop Column Fields Here",
"dxPivotGrid-dataFieldArea": "Drop Data Fields Here",
"dxPivotGrid-rowFieldArea": "Drop Row Fields Here",
"dxPivotGrid-filterFieldArea": "Drop Filter Fields Here",
"dxScheduler-editorLabelTitle": "Subject",
"dxScheduler-editorLabelStartDate": "Start Date",
"dxScheduler-editorLabelEndDate": "End Date",
"dxScheduler-editorLabelDescription": "Description",
"dxScheduler-editorLabelRecurrence": "Repeat",
"dxScheduler-openAppointment": "Open appointment",
"dxScheduler-recurrenceNever": "Never",
"dxScheduler-recurrenceMinutely": "Every minute",
"dxScheduler-recurrenceHourly": "Hourly",
"dxScheduler-recurrenceDaily": "Daily",
"dxScheduler-recurrenceWeekly": "Weekly",
"dxScheduler-recurrenceMonthly": "Monthly",
"dxScheduler-recurrenceYearly": "Yearly",
"dxScheduler-recurrenceRepeatEvery": "Repeat Every",
"dxScheduler-recurrenceRepeatOn": "Repeat On",
"dxScheduler-recurrenceEnd": "End repeat",
"dxScheduler-recurrenceAfter": "After",
"dxScheduler-recurrenceOn": "On",
"dxScheduler-recurrenceRepeatMinutely": "minute(s)",
"dxScheduler-recurrenceRepeatHourly": "hour(s)",
"dxScheduler-recurrenceRepeatDaily": "day(s)",
"dxScheduler-recurrenceRepeatWeekly": "week(s)",
"dxScheduler-recurrenceRepeatMonthly": "month(s)",
"dxScheduler-recurrenceRepeatYearly": "year(s)",
"dxScheduler-switcherDay": "Day",
"dxScheduler-switcherWeek": "Week",
"dxScheduler-switcherWorkWeek": "Work Week",
"dxScheduler-switcherMonth": "Month",
"dxScheduler-switcherAgenda": "Agenda",
"dxScheduler-switcherTimelineDay": "Timeline Day",
"dxScheduler-switcherTimelineWeek": "Timeline Week",
"dxScheduler-switcherTimelineWorkWeek": "Timeline Work Week",
"dxScheduler-switcherTimelineMonth": "Timeline Month",
"dxScheduler-recurrenceRepeatOnDate": "on date",
"dxScheduler-recurrenceRepeatCount": "occurrence(s)",
"dxScheduler-allDay": "All day",
"dxScheduler-confirmRecurrenceEditMessage": "Do you want to edit only this appointment or the whole series?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Do you want to delete only this appointment or the whole series?",
"dxScheduler-confirmRecurrenceEditSeries": "Edit series",
"dxScheduler-confirmRecurrenceDeleteSeries": "Delete series",
"dxScheduler-confirmRecurrenceEditOccurrence": "Edit appointment",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Delete appointment",
"dxScheduler-noTimezoneTitle": "No timezone",
"dxScheduler-moreAppointments": "{0} more",
"dxCalendar-todayButtonText": "Today",
"dxCalendar-ariaWidgetName": "Calendar",
"dxColorView-ariaRed": "Red",
"dxColorView-ariaGreen": "Green",
"dxColorView-ariaBlue": "Blue",
"dxColorView-ariaAlpha": "Transparency",
"dxColorView-ariaHex": "Color code",
"dxTagBox-selected": "{0} selected",
"dxTagBox-allSelected": "All selected ({0})",
"dxTagBox-moreSelected": "{0} more",
"vizExport-printingButtonText": "Print",
"vizExport-titleMenuText": "Exporting/Printing",
"vizExport-exportButtonText": "{0} file",
"dxFilterBuilder-and": "And",
"dxFilterBuilder-or": "Or",
"dxFilterBuilder-notAnd": "Not And",
"dxFilterBuilder-notOr": "Not Or",
"dxFilterBuilder-addCondition": "Add Condition",
"dxFilterBuilder-addGroup": "Add Group",
"dxFilterBuilder-enterValueText": "<enter a value>",
"dxFilterBuilder-filterOperationEquals": "Equals",
"dxFilterBuilder-filterOperationNotEquals": "Does not equal",
"dxFilterBuilder-filterOperationLess": "Is less than",
"dxFilterBuilder-filterOperationLessOrEquals": "Is less than or equal to",
"dxFilterBuilder-filterOperationGreater": "Is greater than",
"dxFilterBuilder-filterOperationGreaterOrEquals": "Is greater than or equal to",
"dxFilterBuilder-filterOperationStartsWith": "Starts with",
"dxFilterBuilder-filterOperationContains": "Contains",
"dxFilterBuilder-filterOperationNotContains": "Does not contain",
"dxFilterBuilder-filterOperationEndsWith": "Ends with",
"dxFilterBuilder-filterOperationIsBlank": "Is blank",
"dxFilterBuilder-filterOperationIsNotBlank": "Is not blank",
"dxFilterBuilder-filterOperationBetween": "Is between",
"dxFilterBuilder-filterOperationAnyOf": "Is any of",
"dxFilterBuilder-filterOperationNoneOf": "Is none of",
"dxHtmlEditor-dialogColorCaption": "Change Font Color",
"dxHtmlEditor-dialogBackgroundCaption": "Change Background Color",
"dxHtmlEditor-dialogLinkCaption": "Add Link",
"dxHtmlEditor-dialogLinkUrlField": "URL",
"dxHtmlEditor-dialogLinkTextField": "Text",
"dxHtmlEditor-dialogLinkTargetField": "Open link in new window",
"dxHtmlEditor-dialogImageCaption": "Add Image",
"dxHtmlEditor-dialogImageUrlField": "URL",
"dxHtmlEditor-dialogImageAltField": "Alternate text",
"dxHtmlEditor-dialogImageWidthField": "Width (px)",
"dxHtmlEditor-dialogImageHeightField": "Height (px)",
"dxHtmlEditor-dialogInsertTableRowsField": "Rows",
"dxHtmlEditor-dialogInsertTableColumnsField": "Columns",
"dxHtmlEditor-dialogInsertTableCaption": "Insert Table",
"dxHtmlEditor-heading": "Heading",
"dxHtmlEditor-normalText": "Normal text",
"dxHtmlEditor-background": "Background Color",
"dxHtmlEditor-bold": "Bold",
"dxHtmlEditor-color": "Font Color",
"dxHtmlEditor-font": "Font",
"dxHtmlEditor-italic": "Italic",
"dxHtmlEditor-link": "Add Link",
"dxHtmlEditor-image": "Add Image",
"dxHtmlEditor-size": "Size",
"dxHtmlEditor-strike": "Strikethrough",
"dxHtmlEditor-subscript": "Subscript",
"dxHtmlEditor-superscript": "Superscript",
"dxHtmlEditor-underline": "Underline",
"dxHtmlEditor-blockquote": "Blockquote",
"dxHtmlEditor-header": "Header",
"dxHtmlEditor-increaseIndent": "Increase Indent",
"dxHtmlEditor-decreaseIndent": "Decrease Indent",
"dxHtmlEditor-orderedList": "Ordered List",
"dxHtmlEditor-bulletList": "Bullet List",
"dxHtmlEditor-alignLeft": "Align Left",
"dxHtmlEditor-alignCenter": "Align Center",
"dxHtmlEditor-alignRight": "Align Right",
"dxHtmlEditor-alignJustify": "Align Justify",
"dxHtmlEditor-codeBlock": "Code Block",
"dxHtmlEditor-variable": "Add Variable",
"dxHtmlEditor-undo": "Undo",
"dxHtmlEditor-redo": "Redo",
"dxHtmlEditor-clear": "Clear Formatting",
"dxHtmlEditor-insertTable": "Insert Table",
"dxHtmlEditor-insertHeaderRow": "Insert Header Row",
"dxHtmlEditor-insertRowAbove": "Insert Row Above",
"dxHtmlEditor-insertRowBelow": "Insert Row Below",
"dxHtmlEditor-insertColumnLeft": "Insert Column Left",
"dxHtmlEditor-insertColumnRight": "Insert Column Right",
"dxHtmlEditor-deleteColumn": "Delete Column",
"dxHtmlEditor-deleteRow": "Delete Row",
"dxHtmlEditor-deleteTable": "Delete Table",
"dxHtmlEditor-cellProperties": "Cell Properties",
"dxHtmlEditor-tableProperties": "Table Properties",
"dxHtmlEditor-insert": "Insert",
"dxHtmlEditor-delete": "Delete",
"dxHtmlEditor-border": "Border",
"dxHtmlEditor-style": "Style",
"dxHtmlEditor-width": "Width",
"dxHtmlEditor-height": "Height",
"dxHtmlEditor-borderColor": "Color",
"dxHtmlEditor-tableBackground": "Background",
"dxHtmlEditor-dimensions": "Dimensions",
"dxHtmlEditor-alignment": "Alignment",
"dxHtmlEditor-horizontal": "Horizontal",
"dxHtmlEditor-vertical": "Vertical",
"dxHtmlEditor-paddingVertical": "Vertical Padding",
"dxHtmlEditor-paddingHorizontal": "Horizontal Padding",
"dxHtmlEditor-pixels": "Pixels",
"dxHtmlEditor-list": "List",
"dxHtmlEditor-ordered": "Ordered",
"dxHtmlEditor-bullet": "Bullet",
"dxHtmlEditor-align": "Align",
"dxHtmlEditor-center": "Center",
"dxHtmlEditor-left": "Left",
"dxHtmlEditor-right": "Right",
"dxHtmlEditor-indent": "Indent",
"dxHtmlEditor-justify": "Justify",
"dxFileManager-newDirectoryName": "Untitled directory",
"dxFileManager-rootDirectoryName": "Files",
"dxFileManager-errorNoAccess": "Access Denied. Operation could not be completed.",
"dxFileManager-errorDirectoryExistsFormat": "Directory '{0}' already exists.",
"dxFileManager-errorFileExistsFormat": "File '{0}' already exists.",
"dxFileManager-errorFileNotFoundFormat": "File '{0}' not found.",
"dxFileManager-errorDirectoryNotFoundFormat": "Directory '{0}' not found.",
"dxFileManager-errorWrongFileExtension": "File extension is not allowed.",
"dxFileManager-errorMaxFileSizeExceeded": "File size exceeds the maximum allowed size.",
"dxFileManager-errorInvalidSymbols": "This name contains invalid characters.",
"dxFileManager-errorDefault": "Unspecified error.",
"dxFileManager-errorDirectoryOpenFailed": "The directory cannot be opened",
"dxFileManager-commandCreate": "New directory",
"dxFileManager-commandRename": "Rename",
"dxFileManager-commandMove": "Move to",
"dxFileManager-commandCopy": "Copy to",
"dxFileManager-commandDelete": "Delete",
"dxFileManager-commandDownload": "Download",
"dxFileManager-commandUpload": "Upload files",
"dxFileManager-commandRefresh": "Refresh",
"dxFileManager-commandThumbnails": "Thumbnails View",
"dxFileManager-commandDetails": "Details View",
"dxFileManager-commandClearSelection": "Clear selection",
"dxFileManager-commandShowNavPane": "Toggle navigation pane",
"dxFileManager-dialogDirectoryChooserMoveTitle": "Move to",
"dxFileManager-dialogDirectoryChooserMoveButtonText": "Move",
"dxFileManager-dialogDirectoryChooserCopyTitle": "Copy to",
"dxFileManager-dialogDirectoryChooserCopyButtonText": "Copy",
"dxFileManager-dialogRenameItemTitle": "Rename",
"dxFileManager-dialogRenameItemButtonText": "Save",
"dxFileManager-dialogCreateDirectoryTitle": "New directory",
"dxFileManager-dialogCreateDirectoryButtonText": "Create",
"dxFileManager-dialogDeleteItemTitle": "Delete",
"dxFileManager-dialogDeleteItemButtonText": "Delete",
"dxFileManager-dialogDeleteItemSingleItemConfirmation": "Are you sure you want to delete {0}?",
"dxFileManager-dialogDeleteItemMultipleItemsConfirmation": "Are you sure you want to delete {0} items?",
"dxFileManager-dialogButtonCancel": "Cancel",
"dxFileManager-editingCreateSingleItemProcessingMessage": "Creating a directory inside {0}",
"dxFileManager-editingCreateSingleItemSuccessMessage": "Created a directory inside {0}",
"dxFileManager-editingCreateSingleItemErrorMessage": "Directory was not created",
"dxFileManager-editingCreateCommonErrorMessage": "Directory was not created",
"dxFileManager-editingRenameSingleItemProcessingMessage": "Renaming an item inside {0}",
"dxFileManager-editingRenameSingleItemSuccessMessage": "Renamed an item inside {0}",
"dxFileManager-editingRenameSingleItemErrorMessage": "Item was not renamed",
"dxFileManager-editingRenameCommonErrorMessage": "Item was not renamed",
"dxFileManager-editingDeleteSingleItemProcessingMessage": "Deleting an item from {0}",
"dxFileManager-editingDeleteMultipleItemsProcessingMessage": "Deleting {0} items from {1}",
"dxFileManager-editingDeleteSingleItemSuccessMessage": "Deleted an item from {0}",
"dxFileManager-editingDeleteMultipleItemsSuccessMessage": "Deleted {0} items from {1}",
"dxFileManager-editingDeleteSingleItemErrorMessage": "Item was not deleted",
"dxFileManager-editingDeleteMultipleItemsErrorMessage": "{0} items were not deleted",
"dxFileManager-editingDeleteCommonErrorMessage": "Some items were not deleted",
"dxFileManager-editingMoveSingleItemProcessingMessage": "Moving an item to {0}",
"dxFileManager-editingMoveMultipleItemsProcessingMessage": "Moving {0} items to {1}",
"dxFileManager-editingMoveSingleItemSuccessMessage": "Moved an item to {0}",
"dxFileManager-editingMoveMultipleItemsSuccessMessage": "Moved {0} items to {1}",
"dxFileManager-editingMoveSingleItemErrorMessage": "Item was not moved",
"dxFileManager-editingMoveMultipleItemsErrorMessage": "{0} items were not moved",
"dxFileManager-editingMoveCommonErrorMessage": "Some items were not moved",
"dxFileManager-editingCopySingleItemProcessingMessage": "Copying an item to {0}",
"dxFileManager-editingCopyMultipleItemsProcessingMessage": "Copying {0} items to {1}",
"dxFileManager-editingCopySingleItemSuccessMessage": "Copied an item to {0}",
"dxFileManager-editingCopyMultipleItemsSuccessMessage": "Copied {0} items to {1}",
"dxFileManager-editingCopySingleItemErrorMessage": "Item was not copied",
"dxFileManager-editingCopyMultipleItemsErrorMessage": "{0} items were not copied",
"dxFileManager-editingCopyCommonErrorMessage": "Some items were not copied",
"dxFileManager-editingUploadSingleItemProcessingMessage": "Uploading an item to {0}",
"dxFileManager-editingUploadMultipleItemsProcessingMessage": "Uploading {0} items to {1}",
"dxFileManager-editingUploadSingleItemSuccessMessage": "Uploaded an item to {0}",
"dxFileManager-editingUploadMultipleItemsSuccessMessage": "Uploaded {0} items to {1}",
"dxFileManager-editingUploadSingleItemErrorMessage": "Item was not uploaded",
"dxFileManager-editingUploadMultipleItemsErrorMessage": "{0} items were not uploaded",
"dxFileManager-editingUploadCanceledMessage": "Canceled",
"dxFileManager-listDetailsColumnCaptionName": "Name",
"dxFileManager-listDetailsColumnCaptionDateModified": "Date Modified",
"dxFileManager-listDetailsColumnCaptionFileSize": "File Size",
"dxFileManager-listThumbnailsTooltipTextSize": "Size",
"dxFileManager-listThumbnailsTooltipTextDateModified": "Date Modified",
"dxFileManager-notificationProgressPanelTitle": "Progress",
"dxFileManager-notificationProgressPanelEmptyListText": "No operations",
"dxFileManager-notificationProgressPanelOperationCanceled": "Canceled",
"dxDiagram-categoryGeneral": "General",
"dxDiagram-categoryFlowchart": "Flowchart",
"dxDiagram-categoryOrgChart": "Org Chart",
"dxDiagram-categoryContainers": "Containers",
"dxDiagram-categoryCustom": "Custom",
"dxDiagram-commandExportToSvg": "Export to SVG",
"dxDiagram-commandExportToPng": "Export to PNG",
"dxDiagram-commandExportToJpg": "Export to JPEG",
"dxDiagram-commandUndo": "Undo",
"dxDiagram-commandRedo": "Redo",
"dxDiagram-commandFontName": "Font Name",
"dxDiagram-commandFontSize": "Font Size",
"dxDiagram-commandBold": "Bold",
"dxDiagram-commandItalic": "Italic",
"dxDiagram-commandUnderline": "Underline",
"dxDiagram-commandTextColor": "Font Color",
"dxDiagram-commandLineColor": "Line Color",
"dxDiagram-commandLineWidth": "Line Width",
"dxDiagram-commandLineStyle": "Line Style",
"dxDiagram-commandLineStyleSolid": "Solid",
"dxDiagram-commandLineStyleDotted": "Dotted",
"dxDiagram-commandLineStyleDashed": "Dashed",
"dxDiagram-commandFillColor": "Fill Color",
"dxDiagram-commandAlignLeft": "Align Left",
"dxDiagram-commandAlignCenter": "Align Center",
"dxDiagram-commandAlignRight": "Align Right",
"dxDiagram-commandConnectorLineType": "Connector Line Type",
"dxDiagram-commandConnectorLineStraight": "Straight",
"dxDiagram-commandConnectorLineOrthogonal": "Orthogonal",
"dxDiagram-commandConnectorLineStart": "Connector Line Start",
"dxDiagram-commandConnectorLineEnd": "Connector Line End",
"dxDiagram-commandConnectorLineNone": "None",
"dxDiagram-commandConnectorLineArrow": "Arrow",
"dxDiagram-commandFullscreen": "Full Screen",
"dxDiagram-commandUnits": "Units",
"dxDiagram-commandPageSize": "Page Size",
"dxDiagram-commandPageOrientation": "Page Orientation",
"dxDiagram-commandPageOrientationLandscape": "Landscape",
"dxDiagram-commandPageOrientationPortrait": "Portrait",
"dxDiagram-commandPageColor": "Page Color",
"dxDiagram-commandShowGrid": "Show Grid",
"dxDiagram-commandSnapToGrid": "Snap to Grid",
"dxDiagram-commandGridSize": "Grid Size",
"dxDiagram-commandZoomLevel": "Zoom Level",
"dxDiagram-commandAutoZoom": "Auto Zoom",
"dxDiagram-commandFitToContent": "Fit to Content",
"dxDiagram-commandFitToWidth": "Fit to Width",
"dxDiagram-commandAutoZoomByContent": "Auto Zoom by Content",
"dxDiagram-commandAutoZoomByWidth": "Auto Zoom by Width",
"dxDiagram-commandSimpleView": "Simple View",
"dxDiagram-commandCut": "Cut",
"dxDiagram-commandCopy": "Copy",
"dxDiagram-commandPaste": "Paste",
"dxDiagram-commandSelectAll": "Select All",
"dxDiagram-commandDelete": "Delete",
"dxDiagram-commandBringToFront": "Bring to Front",
"dxDiagram-commandSendToBack": "Send to Back",
"dxDiagram-commandLock": "Lock",
"dxDiagram-commandUnlock": "Unlock",
"dxDiagram-commandInsertShapeImage": "Insert Image...",
"dxDiagram-commandEditShapeImage": "Change Image...",
"dxDiagram-commandDeleteShapeImage": "Delete Image",
"dxDiagram-commandLayoutLeftToRight": "Left-to-right",
"dxDiagram-commandLayoutRightToLeft": "Right-to-left",
"dxDiagram-commandLayoutTopToBottom": "Top-to-bottom",
"dxDiagram-commandLayoutBottomToTop": "Bottom-to-top",
"dxDiagram-unitIn": "in",
"dxDiagram-unitCm": "cm",
"dxDiagram-unitPx": "px",
"dxDiagram-dialogButtonOK": "OK",
"dxDiagram-dialogButtonCancel": "Cancel",
"dxDiagram-dialogInsertShapeImageTitle": "Insert Image",
"dxDiagram-dialogEditShapeImageTitle": "Change Image",
"dxDiagram-dialogEditShapeImageSelectButton": "Select image",
"dxDiagram-dialogEditShapeImageLabelText": "or drop file here",
"dxDiagram-uiExport": "Export",
"dxDiagram-uiProperties": "Properties",
"dxDiagram-uiSettings": "Settings",
"dxDiagram-uiShowToolbox": "Show Toolbox",
"dxDiagram-uiSearch": "Search",
"dxDiagram-uiStyle": "Style",
"dxDiagram-uiLayout": "Layout",
"dxDiagram-uiLayoutTree": "Tree",
"dxDiagram-uiLayoutLayered": "Layered",
"dxDiagram-uiDiagram": "Diagram",
"dxDiagram-uiText": "Text",
"dxDiagram-uiObject": "Object",
"dxDiagram-uiConnector": "Connector",
"dxDiagram-uiPage": "Page",
"dxDiagram-shapeText": "Text",
"dxDiagram-shapeRectangle": "Rectangle",
"dxDiagram-shapeEllipse": "Ellipse",
"dxDiagram-shapeCross": "Cross",
"dxDiagram-shapeTriangle": "Triangle",
"dxDiagram-shapeDiamond": "Diamond",
"dxDiagram-shapeHeart": "Heart",
"dxDiagram-shapePentagon": "Pentagon",
"dxDiagram-shapeHexagon": "Hexagon",
"dxDiagram-shapeOctagon": "Octagon",
"dxDiagram-shapeStar": "Star",
"dxDiagram-shapeArrowLeft": "Left Arrow",
"dxDiagram-shapeArrowUp": "Up Arrow",
"dxDiagram-shapeArrowRight": "Right Arrow",
"dxDiagram-shapeArrowDown": "Down Arrow",
"dxDiagram-shapeArrowUpDown": "Up Down Arrow",
"dxDiagram-shapeArrowLeftRight": "Left Right Arrow",
"dxDiagram-shapeProcess": "Process",
"dxDiagram-shapeDecision": "Decision",
"dxDiagram-shapeTerminator": "Terminator",
"dxDiagram-shapePredefinedProcess": "Predefined Process",
"dxDiagram-shapeDocument": "Document",
"dxDiagram-shapeMultipleDocuments": "Multiple Documents",
"dxDiagram-shapeManualInput": "Manual Input",
"dxDiagram-shapePreparation": "Preparation",
"dxDiagram-shapeData": "Data",
"dxDiagram-shapeDatabase": "Database",
"dxDiagram-shapeHardDisk": "Hard Disk",
"dxDiagram-shapeInternalStorage": "Internal Storage",
"dxDiagram-shapePaperTape": "Paper Tape",
"dxDiagram-shapeManualOperation": "Manual Operation",
"dxDiagram-shapeDelay": "Delay",
"dxDiagram-shapeStoredData": "Stored Data",
"dxDiagram-shapeDisplay": "Display",
"dxDiagram-shapeMerge": "Merge",
"dxDiagram-shapeConnector": "Connector",
"dxDiagram-shapeOr": "Or",
"dxDiagram-shapeSummingJunction": "Summing Junction",
"dxDiagram-shapeContainerDefaultText": "Container",
"dxDiagram-shapeVerticalContainer": "Vertical Container",
"dxDiagram-shapeHorizontalContainer": "Horizontal Container",
"dxDiagram-shapeCardDefaultText": "Person's Name",
"dxDiagram-shapeCardWithImageOnLeft": "Card with Image on the Left",
"dxDiagram-shapeCardWithImageOnTop": "Card with Image on the Top",
"dxDiagram-shapeCardWithImageOnRight": "Card with Image on the Right",
"dxGantt-dialogTitle": "Title",
"dxGantt-dialogStartTitle": "Start",
"dxGantt-dialogEndTitle": "End",
"dxGantt-dialogProgressTitle": "Progress",
"dxGantt-dialogResourcesTitle": "Resources",
"dxGantt-dialogResourceManagerTitle": "Resource Manager",
"dxGantt-dialogTaskDetailsTitle": "Task Details",
"dxGantt-dialogEditResourceListHint": "Edit Resource List",
"dxGantt-dialogEditNoResources": "No resources",
"dxGantt-dialogButtonAdd": "Add",
"dxGantt-contextMenuNewTask": "New Task",
"dxGantt-contextMenuNewSubtask": "New Subtask",
"dxGantt-contextMenuDeleteTask": "Delete Task",
"dxGantt-contextMenuDeleteDependency": "Delete Dependency",
"dxGantt-dialogTaskDeleteConfirmation": "Deleting a task also deletes all its dependencies and subtasks. Are you sure you want to delete this task?",
"dxGantt-dialogDependencyDeleteConfirmation": "Are you sure you want to delete the dependency from the task?",
"dxGantt-dialogResourcesDeleteConfirmation": "Deleting a resource also deletes it from tasks to which this resource is assigned. Are you sure you want to delete these resources? Resources: {0}",
"dxGantt-dialogConstraintCriticalViolationMessage": "The task you are attempting to move is linked to a second task by a dependency relation. This change would conflict with dependency rules. How would you like to proceed?",
"dxGantt-dialogConstraintViolationMessage": "The task you are attempting to move is linked to a second task by a dependency relation. How would you like to proceed?",
"dxGantt-dialogCancelOperationMessage": "Cancel the operation",
"dxGantt-dialogDeleteDependencyMessage": "Delete the dependency",
"dxGantt-dialogMoveTaskAndKeepDependencyMessage": "Move the task and keep the dependency",
"dxGantt-dialogConstraintCriticalViolationSeveralTasksMessage": "The task you are attempting to move is linked to another tasks by dependency relations. This change would conflict with dependency rules. How would you like to proceed?",
"dxGantt-dialogConstraintViolationSeveralTasksMessage": "The task you are attempting to move is linked to another tasks by dependency relations. How would you like to proceed?",
"dxGantt-dialogDeleteDependenciesMessage": "Delete the dependencies",
"dxGantt-dialogMoveTaskAndKeepDependenciesMessage": "Move the task and keep the dependencies",
"dxGantt-undo": "Undo",
"dxGantt-redo": "Redo",
"dxGantt-expandAll": "Expand All",
"dxGantt-collapseAll": "Collapse All",
"dxGantt-addNewTask": "Add New Task",
"dxGantt-deleteSelectedTask": "Delete Selected Task",
"dxGantt-zoomIn": "Zoom In",
"dxGantt-zoomOut": "Zoom Out",
"dxGantt-fullScreen": "Full Screen",
"dxGantt-quarter": "Q{0}",
"dxGantt-sortingAscendingText": "Sort Ascending",
"dxGantt-sortingDescendingText": "Sort Descending",
"dxGantt-sortingClearText": "Clear Sorting",
"dxGantt-showResources": "Show Resources",
"dxGantt-showDependencies": "Show Dependencies",
"dxGantt-dialogStartDateValidation": "Start date must be after {0}",
"dxGantt-dialogEndDateValidation": "End date must be after {0}"
}
})
}));
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("Navigo", [], factory);
else if(typeof exports === 'object')
exports["Navigo"] = factory();
else
root["Navigo"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/Q.ts":
/*!******************!*\
!*** ./src/Q.ts ***!
\******************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ Q
/* harmony export */ });
function Q(funcs, c, done) {
var context = c || {};
var idx = 0;
(function next() {
if (!funcs[idx]) {
if (done) {
done(context);
}
return;
}
if (Array.isArray(funcs[idx])) {
funcs.splice.apply(funcs, [idx, 1].concat(funcs[idx][0](context) ? funcs[idx][1] : funcs[idx][2]));
next();
} else {
// console.log(funcs[idx].name + " / " + JSON.stringify(context));
// console.log(funcs[idx].name);
funcs[idx](context, function (moveForward) {
if (typeof moveForward === "undefined" || moveForward === true) {
idx += 1;
next();
} else if (done) {
done(context);
}
});
}
})();
}
Q.if = function (condition, one, two) {
if (!Array.isArray(one)) one = [one];
if (!Array.isArray(two)) two = [two];
return [condition, one, two];
};
/***/ }),
/***/ "./src/constants.ts":
/*!**************************!*\
!*** ./src/constants.ts ***!
\**************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "PARAMETER_REGEXP": () => /* binding */ PARAMETER_REGEXP,
/* harmony export */ "REPLACE_VARIABLE_REGEXP": () => /* binding */ REPLACE_VARIABLE_REGEXP,
/* harmony export */ "WILDCARD_REGEXP": () => /* binding */ WILDCARD_REGEXP,
/* harmony export */ "REPLACE_WILDCARD": () => /* binding */ REPLACE_WILDCARD,
/* harmony export */ "NOT_SURE_REGEXP": () => /* binding */ NOT_SURE_REGEXP,
/* harmony export */ "REPLACE_NOT_SURE": () => /* binding */ REPLACE_NOT_SURE,
/* harmony export */ "START_BY_SLASH_REGEXP": () => /* binding */ START_BY_SLASH_REGEXP,
/* harmony export */ "MATCH_REGEXP_FLAGS": () => /* binding */ MATCH_REGEXP_FLAGS
/* harmony export */ });
var PARAMETER_REGEXP = /([:*])(\w+)/g;
var REPLACE_VARIABLE_REGEXP = "([^/]+)";
var WILDCARD_REGEXP = /\*/g;
var REPLACE_WILDCARD = "?(?:.*)";
var NOT_SURE_REGEXP = /\/\?/g;
var REPLACE_NOT_SURE = "/?([^/]+|)";
var START_BY_SLASH_REGEXP = "(?:/^|^)";
var MATCH_REGEXP_FLAGS = "";
/***/ }),
/***/ "./src/index.ts":
/*!**********************!*\
!*** ./src/index.ts ***!
\**********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ Navigo
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./src/utils.ts");
/* harmony import */ var _Q__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Q */ "./src/Q.ts");
/* harmony import */ var _middlewares_setLocationPath__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./middlewares/setLocationPath */ "./src/middlewares/setLocationPath.ts");
/* harmony import */ var _middlewares_matchPathToRegisteredRoutes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./middlewares/matchPathToRegisteredRoutes */ "./src/middlewares/matchPathToRegisteredRoutes.ts");
/* harmony import */ var _middlewares_checkForDeprecationMethods__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./middlewares/checkForDeprecationMethods */ "./src/middlewares/checkForDeprecationMethods.ts");
/* harmony import */ var _middlewares_checkForForceOp__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./middlewares/checkForForceOp */ "./src/middlewares/checkForForceOp.ts");
/* harmony import */ var _middlewares_updateBrowserURL__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./middlewares/updateBrowserURL */ "./src/middlewares/updateBrowserURL.ts");
/* harmony import */ var _middlewares_processMatches__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./middlewares/processMatches */ "./src/middlewares/processMatches.ts");
/* harmony import */ var _lifecycles__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./lifecycles */ "./src/lifecycles.ts");
function Navigo(appRoute, resolveOptions) {
var DEFAULT_RESOLVE_OPTIONS = resolveOptions || {
strategy: "ONE",
hash: false,
noMatchWarning: false
};
var self = this;
var root = "/";
var current = null;
var routes = [];
var destroyed = false;
var genericHooks;
var isPushStateAvailable = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.pushStateAvailable)();
var isWindowAvailable = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.windowAvailable)();
if (!appRoute) {
console.warn('Navigo requires a root path in its constructor. If not provided will use "/" as default.');
} else {
root = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(appRoute);
}
function _checkForAHash(url) {
if (url.indexOf("#") >= 0) {
if (DEFAULT_RESOLVE_OPTIONS.hash === true) {
url = url.split("#")[1] || "/";
} else {
url = url.split("#")[0];
}
}
return url;
}
function composePathWithRoot(path) {
return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(root + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path));
}
function createRoute(path, handler, hooks, name) {
path = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.isString)(path) ? composePathWithRoot(path) : path;
return {
name: name || (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(String(path)),
path: path,
handler: handler,
hooks: (0,_utils__WEBPACK_IMPORTED_MODULE_0__.accumulateHooks)(hooks)
};
} // public APIs
function on(path, handler, hooks) {
var _this = this;
if (typeof path === "object" && !(path instanceof RegExp)) {
Object.keys(path).forEach(function (p) {
if (typeof path[p] === "function") {
_this.on(p, path[p]);
} else {
var _path$p = path[p],
_handler = _path$p.uses,
name = _path$p.as,
_hooks = _path$p.hooks;
routes.push(createRoute(p, _handler, [genericHooks, _hooks], name));
}
});
return this;
} else if (typeof path === "function") {
hooks = handler;
handler = path;
path = root;
}
routes.push(createRoute(path, handler, [genericHooks, hooks]));
return this;
}
function resolve(to, options) {
var context = {
instance: self,
currentLocationPath: to ? (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(root) + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(to) : undefined,
navigateOptions: {},
resolveOptions: options || DEFAULT_RESOLVE_OPTIONS
};
(0,_Q__WEBPACK_IMPORTED_MODULE_1__.default)([_middlewares_setLocationPath__WEBPACK_IMPORTED_MODULE_2__.default, _middlewares_matchPathToRegisteredRoutes__WEBPACK_IMPORTED_MODULE_3__.default, _Q__WEBPACK_IMPORTED_MODULE_1__.default.if(function (_ref) {
var matches = _ref.matches;
return matches && matches.length > 0;
}, _middlewares_processMatches__WEBPACK_IMPORTED_MODULE_7__.default, _lifecycles__WEBPACK_IMPORTED_MODULE_8__.notFoundLifeCycle)], context);
return context.matches ? context.matches : false;
}
function navigate(to, navigateOptions) {
to = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(root) + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(to);
var context = {
instance: self,
to: to,
navigateOptions: navigateOptions || {},
resolveOptions: navigateOptions && navigateOptions.resolveOptions ? navigateOptions.resolveOptions : DEFAULT_RESOLVE_OPTIONS,
currentLocationPath: _checkForAHash(to)
};
(0,_Q__WEBPACK_IMPORTED_MODULE_1__.default)([_middlewares_checkForDeprecationMethods__WEBPACK_IMPORTED_MODULE_4__.default, _middlewares_checkForForceOp__WEBPACK_IMPORTED_MODULE_5__.default, _middlewares_matchPathToRegisteredRoutes__WEBPACK_IMPORTED_MODULE_3__.default, _Q__WEBPACK_IMPORTED_MODULE_1__.default.if(function (_ref2) {
var matches = _ref2.matches;
return matches && matches.length > 0;
}, _middlewares_processMatches__WEBPACK_IMPORTED_MODULE_7__.default, _lifecycles__WEBPACK_IMPORTED_MODULE_8__.notFoundLifeCycle), _middlewares_updateBrowserURL__WEBPACK_IMPORTED_MODULE_6__.default], context);
}
function navigateByName(name, data, options) {
var url = generate(name, data);
navigate(url, options);
}
function off(what) {
this.routes = routes = routes.filter(function (r) {
if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.isString)(what)) {
return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(r.path) !== (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(what);
} else if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(what)) {
return what !== r.handler;
}
return String(r.path) !== String(what);
});
return this;
}
function listen() {
if (isPushStateAvailable) {
this.__popstateListener = function () {
resolve();
};
window.addEventListener("popstate", this.__popstateListener);
}
}
function destroy() {
this.routes = routes = [];
if (isPushStateAvailable) {
window.removeEventListener("popstate", this.__popstateListener);
}
this.destroyed = destroyed = true;
}
function notFound(handler, hooks) {
self._notFoundRoute = createRoute("*", handler, [genericHooks, hooks], "__NOT_FOUND__");
return this;
}
function updatePageLinks() {
if (!isWindowAvailable) return;
findLinks().forEach(function (link) {
if ("false" === link.getAttribute("data-navigo") || "_blank" === link.getAttribute("target")) {
if (link.hasListenerAttached) {
link.removeEventListener("click", link.navigoHandler);
}
return;
}
if (!link.hasListenerAttached) {
link.hasListenerAttached = true;
link.navigoHandler = function (e) {
if ((e.ctrlKey || e.metaKey) && e.target.tagName.toLowerCase() === "a") {
return false;
}
var location = link.getAttribute("href");
if (typeof location === "undefined" || location === null) {
return false;
} // handling absolute paths
if (location.match(/^(http|https)/) && typeof URL !== "undefined") {
try {
var u = new URL(location);
location = u.pathname + u.search;
} catch (err) {}
}
var options = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.parseNavigateOptions)(link.getAttribute("data-navigo-options"));
if (!destroyed) {
e.preventDefault();
e.stopPropagation();
self.navigate((0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(location), options);
}
};
link.addEventListener("click", link.navigoHandler);
}
});
return self;
}
function findLinks() {
if (isWindowAvailable) {
return [].slice.call(document.querySelectorAll("[data-navigo]"));
}
return [];
}
function link(path) {
return "/" + root + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path);
}
function setGenericHooks(hooks) {
genericHooks = hooks;
return this;
}
function lastResolved() {
return current;
}
function generate(name, data) {
var route = routes.find(function (r) {
return r.name === name;
});
if (route) {
var result = route.path;
if (data) {
for (var key in data) {
result = result.replace(":" + key, data[key]);
}
}
return !result.match(/^\//) ? "/" + result : result;
}
return null;
}
function getLinkPath(link) {
return link.getAttribute("href");
}
function pathToMatchObject(path) {
var _extractGETParameters = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.extractGETParameters)((0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path)),
url = _extractGETParameters[0],
queryString = _extractGETParameters[1];
var params = queryString === "" ? null : (0,_utils__WEBPACK_IMPORTED_MODULE_0__.parseQuery)(queryString);
var route = createRoute(url, function () {}, [genericHooks], url);
return {
url: url,
queryString: queryString,
route: route,
data: null,
params: params
};
}
function getCurrentLocation() {
return pathToMatchObject((0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)((0,_utils__WEBPACK_IMPORTED_MODULE_0__.getCurrentEnvURL)(root)).replace(new RegExp("^" + root), ""));
}
function directMatchWithRegisteredRoutes(path) {
var context = {
instance: self,
currentLocationPath: path,
navigateOptions: {},
resolveOptions: DEFAULT_RESOLVE_OPTIONS
};
(0,_middlewares_matchPathToRegisteredRoutes__WEBPACK_IMPORTED_MODULE_3__.default)(context, function () {});
return context.matches ? context.matches : false;
}
function directMatchWithLocation(path, currentLocation) {
var context = {
instance: self,
currentLocationPath: currentLocation
};
(0,_middlewares_setLocationPath__WEBPACK_IMPORTED_MODULE_2__.default)(context, function () {});
path = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path);
var match = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.matchRoute)(context.currentLocationPath, {
name: path,
path: path,
handler: function handler() {},
hooks: {}
});
return match ? match : false;
}
function addHook(type, route, func) {
if (typeof route === "string") {
route = getRoute(route);
}
if (route) {
if (!route.hooks[type]) route.hooks[type] = [];
route.hooks[type].push(func);
return function () {
route.hooks[type] = route.hooks[type].filter(function (f) {
return f !== func;
});
};
} else {
console.warn("Route doesn't exists: " + route);
}
return function () {};
}
function getRoute(nameOrHandler) {
if (typeof nameOrHandler === "string") {
return routes.find(function (r) {
return r.name === composePathWithRoot(nameOrHandler);
});
}
return routes.find(function (r) {
return r.handler === nameOrHandler;
});
}
this.root = root;
this.routes = routes;
this.destroyed = destroyed;
this.current = current;
this.on = on;
this.off = off;
this.resolve = resolve;
this.navigate = navigate;
this.navigateByName = navigateByName;
this.destroy = destroy;
this.notFound = notFound;
this.updatePageLinks = updatePageLinks;
this.link = link;
this.hooks = setGenericHooks;
this.extractGETParameters = function (url) {
return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.extractGETParameters)(_checkForAHash(url));
};
this.lastResolved = lastResolved;
this.generate = generate;
this.getLinkPath = getLinkPath;
this.match = directMatchWithRegisteredRoutes;
this.matchLocation = directMatchWithLocation;
this.getCurrentLocation = getCurrentLocation;
this.addBeforeHook = addHook.bind(this, "before");
this.addAfterHook = addHook.bind(this, "after");
this.addAlreadyHook = addHook.bind(this, "already");
this.addLeaveHook = addHook.bind(this, "leave");
this.getRoute = getRoute;
this._pathToMatchObject = pathToMatchObject;
this._clean = _utils__WEBPACK_IMPORTED_MODULE_0__.clean;
this._checkForAHash = _checkForAHash;
this._setCurrent = function (c) {
return current = self.current = c;
};
listen.call(this);
updatePageLinks.call(this);
}
/***/ }),
/***/ "./src/lifecycles.ts":
/*!***************************!*\
!*** ./src/lifecycles.ts ***!
\***************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "foundLifecycle": () => /* binding */ foundLifecycle,
/* harmony export */ "notFoundLifeCycle": () => /* binding */ notFoundLifeCycle
/* harmony export */ });
/* harmony import */ var _Q__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Q */ "./src/Q.ts");
/* harmony import */ var _middlewares_checkForLeaveHook__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./middlewares/checkForLeaveHook */ "./src/middlewares/checkForLeaveHook.ts");
/* harmony import */ var _middlewares_checkForBeforeHook__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./middlewares/checkForBeforeHook */ "./src/middlewares/checkForBeforeHook.ts");
/* harmony import */ var _middlewares_callHandler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./middlewares/callHandler */ "./src/middlewares/callHandler.ts");
/* harmony import */ var _middlewares_checkForAfterHook__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./middlewares/checkForAfterHook */ "./src/middlewares/checkForAfterHook.ts");
/* harmony import */ var _middlewares_checkForAlreadyHook__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./middlewares/checkForAlreadyHook */ "./src/middlewares/checkForAlreadyHook.ts");
/* harmony import */ var _middlewares_checkForNotFoundHandler__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./middlewares/checkForNotFoundHandler */ "./src/middlewares/checkForNotFoundHandler.ts");
/* harmony import */ var _middlewares_errorOut__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./middlewares/errorOut */ "./src/middlewares/errorOut.ts");
/* harmony import */ var _middlewares_flushCurrent__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./middlewares/flushCurrent */ "./src/middlewares/flushCurrent.ts");
var foundLifecycle = [_middlewares_checkForAlreadyHook__WEBPACK_IMPORTED_MODULE_5__.default, _middlewares_checkForBeforeHook__WEBPACK_IMPORTED_MODULE_2__.default, _middlewares_callHandler__WEBPACK_IMPORTED_MODULE_3__.default, _middlewares_checkForAfterHook__WEBPACK_IMPORTED_MODULE_4__.default];
var notFoundLifeCycle = [_middlewares_checkForLeaveHook__WEBPACK_IMPORTED_MODULE_1__.default, _middlewares_checkForNotFoundHandler__WEBPACK_IMPORTED_MODULE_6__.default, _Q__WEBPACK_IMPORTED_MODULE_0__.default.if(function (_ref) {
var notFoundHandled = _ref.notFoundHandled;
return notFoundHandled;
}, foundLifecycle, [_middlewares_errorOut__WEBPACK_IMPORTED_MODULE_7__.default]), _middlewares_flushCurrent__WEBPACK_IMPORTED_MODULE_8__.default];
/***/ }),
/***/ "./src/middlewares/callHandler.ts":
/*!****************************************!*\
!*** ./src/middlewares/callHandler.ts ***!
\****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ callHandler
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function callHandler(context, done) {
if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.navigateOptions, "callHandler")) {
context.match.route.handler(context.match);
}
context.instance.updatePageLinks();
done();
}
/***/ }),
/***/ "./src/middlewares/checkForAfterHook.ts":
/*!**********************************************!*\
!*** ./src/middlewares/checkForAfterHook.ts ***!
\**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ _checkForAfterHook
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function _checkForAfterHook(context, done) {
if (context.match.route.hooks && context.match.route.hooks.after && (0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.navigateOptions, "callHooks")) {
context.match.route.hooks.after.forEach(function (f) {
return f(context.match);
});
}
done();
}
/***/ }),
/***/ "./src/middlewares/checkForAlreadyHook.ts":
/*!************************************************!*\
!*** ./src/middlewares/checkForAlreadyHook.ts ***!
\************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ checkForAlreadyHook
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function checkForAlreadyHook(context, done) {
var current = context.instance.lastResolved();
if (current && current[0] && current[0].route === context.match.route && current[0].url === context.match.url && current[0].queryString === context.match.queryString) {
current.forEach(function (c) {
if (c.route.hooks && c.route.hooks.already) {
if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.navigateOptions, "callHooks")) {
c.route.hooks.already.forEach(function (f) {
return f(context.match);
});
}
}
});
done(false);
return;
}
done();
}
/***/ }),
/***/ "./src/middlewares/checkForBeforeHook.ts":
/*!***********************************************!*\
!*** ./src/middlewares/checkForBeforeHook.ts ***!
\***********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ checkForBeforeHook
/* harmony export */ });
/* harmony import */ var _Q__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Q */ "./src/Q.ts");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function checkForBeforeHook(context, done) {
if (context.match.route.hooks && context.match.route.hooks.before && (0,_utils__WEBPACK_IMPORTED_MODULE_1__.undefinedOrTrue)(context.navigateOptions, "callHooks")) {
(0,_Q__WEBPACK_IMPORTED_MODULE_0__.default)(context.match.route.hooks.before.map(function (f) {
// just so we match the Q interface
return function beforeHookInternal(_, d) {
return f(d, context.match);
};
}).concat([function () {
return done();
}]));
} else {
done();
}
}
/***/ }),
/***/ "./src/middlewares/checkForDeprecationMethods.ts":
/*!*******************************************************!*\
!*** ./src/middlewares/checkForDeprecationMethods.ts ***!
\*******************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ checkForDeprecationMethods
/* harmony export */ });
function checkForDeprecationMethods(context, done) {
if (context.navigateOptions) {
if (typeof context.navigateOptions["shouldResolve"] !== "undefined") {
console.warn("\"shouldResolve\" is deprecated. Please check the documentation.");
}
if (typeof context.navigateOptions["silent"] !== "undefined") {
console.warn("\"silent\" is deprecated. Please check the documentation.");
}
}
done();
}
/***/ }),
/***/ "./src/middlewares/checkForForceOp.ts":
/*!********************************************!*\
!*** ./src/middlewares/checkForForceOp.ts ***!
\********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ checkForForceOp
/* harmony export */ });
function checkForForceOp(context, done) {
if (context.navigateOptions.force === true) {
context.instance._setCurrent([context.instance._pathToMatchObject(context.to)]);
done(false);
} else {
done();
}
}
/***/ }),
/***/ "./src/middlewares/checkForLeaveHook.ts":
/*!**********************************************!*\
!*** ./src/middlewares/checkForLeaveHook.ts ***!
\**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ checkForLeaveHook
/* harmony export */ });
/* harmony import */ var _Q__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Q */ "./src/Q.ts");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function checkForLeaveHook(context, done) {
var instance = context.instance;
if (!instance.lastResolved()) {
done();
return;
}
(0,_Q__WEBPACK_IMPORTED_MODULE_0__.default)(instance.lastResolved().map(function (oldMatch) {
return function (_, leaveLoopDone) {
// no leave hook
if (!oldMatch.route.hooks || !oldMatch.route.hooks.leave) {
leaveLoopDone();
return;
}
var runHook = false;
var newLocationVSOldMatch = context.instance.matchLocation(oldMatch.route.path, context.currentLocationPath);
if (oldMatch.route.path !== "*") {
runHook = !newLocationVSOldMatch;
} else {
var someOfTheLastOnesMatch = context.matches ? context.matches.find(function (match) {
return oldMatch.route.path === match.route.path;
}) : false;
runHook = !someOfTheLastOnesMatch;
}
if ((0,_utils__WEBPACK_IMPORTED_MODULE_1__.undefinedOrTrue)(context.navigateOptions, "callHooks") && runHook) {
(0,_Q__WEBPACK_IMPORTED_MODULE_0__.default)(oldMatch.route.hooks.leave.map(function (f) {
// just so we match the Q interface
return function (_, d) {
return f(d, context.matches && context.matches.length > 0 ? context.matches.length === 1 ? context.matches[0] : context.matches : undefined);
};
}).concat([function () {
return leaveLoopDone();
}]));
return;
} else {
leaveLoopDone();
}
};
}), {}, function () {
return done();
});
}
/***/ }),
/***/ "./src/middlewares/checkForNotFoundHandler.ts":
/*!****************************************************!*\
!*** ./src/middlewares/checkForNotFoundHandler.ts ***!
\****************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ checkForNotFoundHandler
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function checkForNotFoundHandler(context, done) {
var notFoundRoute = context.instance._notFoundRoute;
if (notFoundRoute) {
context.notFoundHandled = true;
var _extractGETParameters = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.extractGETParameters)(context.currentLocationPath),
url = _extractGETParameters[0],
queryString = _extractGETParameters[1];
notFoundRoute.path = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(url);
var notFoundMatch = {
url: notFoundRoute.path,
queryString: queryString,
data: null,
route: notFoundRoute,
params: queryString !== "" ? (0,_utils__WEBPACK_IMPORTED_MODULE_0__.parseQuery)(queryString) : null
};
context.matches = [notFoundMatch];
context.match = notFoundMatch;
}
done();
}
/***/ }),
/***/ "./src/middlewares/errorOut.ts":
/*!*************************************!*\
!*** ./src/middlewares/errorOut.ts ***!
\*************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ errorOut
/* harmony export */ });
function errorOut(context, done) {
if (!context.resolveOptions || context.resolveOptions.noMatchWarning === false || typeof context.resolveOptions.noMatchWarning === "undefined") console.warn("Navigo: \"" + context.currentLocationPath + "\" didn't match any of the registered routes.");
done();
}
/***/ }),
/***/ "./src/middlewares/flushCurrent.ts":
/*!*****************************************!*\
!*** ./src/middlewares/flushCurrent.ts ***!
\*****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ flushCurrent
/* harmony export */ });
function flushCurrent(context, done) {
context.instance._setCurrent(null);
done();
}
/***/ }),
/***/ "./src/middlewares/matchPathToRegisteredRoutes.ts":
/*!********************************************************!*\
!*** ./src/middlewares/matchPathToRegisteredRoutes.ts ***!
\********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ matchPathToRegisteredRoutes
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function matchPathToRegisteredRoutes(context, done) {
for (var i = 0; i < context.instance.routes.length; i++) {
var route = context.instance.routes[i];
var match = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.matchRoute)(context.currentLocationPath, route);
if (match) {
if (!context.matches) context.matches = [];
context.matches.push(match);
if (context.resolveOptions.strategy === "ONE") {
done();
return;
}
}
}
done();
}
/***/ }),
/***/ "./src/middlewares/processMatches.ts":
/*!*******************************************!*\
!*** ./src/middlewares/processMatches.ts ***!
\*******************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ processMatches
/* harmony export */ });
/* harmony import */ var _Q__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Q */ "./src/Q.ts");
/* harmony import */ var _lifecycles__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../lifecycles */ "./src/lifecycles.ts");
/* harmony import */ var _updateState__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./updateState */ "./src/middlewares/updateState.ts");
/* harmony import */ var _checkForLeaveHook__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./checkForLeaveHook */ "./src/middlewares/checkForLeaveHook.ts");
function _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); }
function processMatches(context, done) {
var idx = 0;
function nextMatch() {
if (idx === context.matches.length) {
(0,_updateState__WEBPACK_IMPORTED_MODULE_2__.default)(context, done);
return;
}
(0,_Q__WEBPACK_IMPORTED_MODULE_0__.default)(_lifecycles__WEBPACK_IMPORTED_MODULE_1__.foundLifecycle, _extends({}, context, {
match: context.matches[idx]
}), function end() {
idx += 1;
nextMatch();
});
}
(0,_checkForLeaveHook__WEBPACK_IMPORTED_MODULE_3__.default)(context, nextMatch);
}
/***/ }),
/***/ "./src/middlewares/setLocationPath.ts":
/*!********************************************!*\
!*** ./src/middlewares/setLocationPath.ts ***!
\********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ _setLocationPath
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function _setLocationPath(context, done) {
if (typeof context.currentLocationPath === "undefined") {
context.currentLocationPath = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.getCurrentEnvURL)(context.instance.root);
}
context.currentLocationPath = context.instance._checkForAHash(context.currentLocationPath);
done();
}
/***/ }),
/***/ "./src/middlewares/updateBrowserURL.ts":
/*!*********************************************!*\
!*** ./src/middlewares/updateBrowserURL.ts ***!
\*********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ updateBrowserURL
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
var isWindowAvailable = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.windowAvailable)();
var isPushStateAvailable = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.pushStateAvailable)();
function updateBrowserURL(context, done) {
if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.navigateOptions, "updateBrowserURL")) {
var value = ("/" + context.to).replace(/\/\//g, "/"); // making sure that we don't have two slashes
var isItUsingHash = isWindowAvailable && context.resolveOptions && context.resolveOptions.hash === true;
if (isPushStateAvailable) {
history[context.navigateOptions.historyAPIMethod || "pushState"](context.navigateOptions.stateObj || {}, context.navigateOptions.title || "", isItUsingHash ? "#" + value : value); // This is to solve a nasty bug where the page doesn't scroll to the anchor.
// We set a microtask to update the hash only.
if (location && location.hash) {
setTimeout(function () {
var tmp = location.hash;
location.hash = "";
location.hash = tmp;
}, 1);
}
} else if (isWindowAvailable) {
window.location.href = context.to;
}
}
done();
}
/***/ }),
/***/ "./src/middlewares/updateState.ts":
/*!****************************************!*\
!*** ./src/middlewares/updateState.ts ***!
\****************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => /* binding */ callHandler
/* harmony export */ });
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../utils */ "./src/utils.ts");
function callHandler(context, done) {
if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.navigateOptions, "updateState")) {
context.instance._setCurrent(context.matches);
}
done();
}
/***/ }),
/***/ "./src/utils.ts":
/*!**********************!*\
!*** ./src/utils.ts ***!
\**********************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "getCurrentEnvURL": () => /* binding */ getCurrentEnvURL,
/* harmony export */ "clean": () => /* binding */ clean,
/* harmony export */ "isString": () => /* binding */ isString,
/* harmony export */ "isFunction": () => /* binding */ isFunction,
/* harmony export */ "regExpResultToParams": () => /* binding */ regExpResultToParams,
/* harmony export */ "extractGETParameters": () => /* binding */ extractGETParameters,
/* harmony export */ "parseQuery": () => /* binding */ parseQuery,
/* harmony export */ "matchRoute": () => /* binding */ matchRoute,
/* harmony export */ "pushStateAvailable": () => /* binding */ pushStateAvailable,
/* harmony export */ "undefinedOrTrue": () => /* binding */ undefinedOrTrue,
/* harmony export */ "parseNavigateOptions": () => /* binding */ parseNavigateOptions,
/* harmony export */ "windowAvailable": () => /* binding */ windowAvailable,
/* harmony export */ "accumulateHooks": () => /* binding */ accumulateHooks
/* harmony export */ });
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./src/constants.ts");
function getCurrentEnvURL(fallback) {
if (fallback === void 0) {
fallback = "/";
}
if (windowAvailable()) {
return location.pathname + location.search + location.hash;
}
return fallback;
}
function clean(s) {
return s.replace(/\/+$/, "").replace(/^\/+/, "");
}
function isString(s) {
return typeof s === "string";
}
function isFunction(s) {
return typeof s === "function";
}
function regExpResultToParams(match, names) {
if (names.length === 0) return null;
if (!match) return null;
return match.slice(1, match.length).reduce(function (params, value, index) {
if (params === null) params = {};
params[names[index]] = decodeURIComponent(value);
return params;
}, null);
}
function extractGETParameters(url) {
var tmp = clean(url).split(/\?(.*)?$/);
return [clean(tmp[0]), tmp.slice(1).join("")];
}
function parseQuery(queryString) {
var query = {};
var pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
if (pair[0] !== "") {
var key = decodeURIComponent(pair[0]);
if (!query[key]) {
query[key] = decodeURIComponent(pair[1] || "");
} else {
if (!Array.isArray(query[key])) query[key] = [query[key]];
query[key].push(decodeURIComponent(pair[1] || ""));
}
}
}
return query;
}
function matchRoute(currentPath, route) {
var _extractGETParameters = extractGETParameters(clean(currentPath)),
current = _extractGETParameters[0],
GETParams = _extractGETParameters[1];
var params = GETParams === "" ? null : parseQuery(GETParams);
var paramNames = [];
var pattern;
if (isString(route.path)) {
pattern = _constants__WEBPACK_IMPORTED_MODULE_0__.START_BY_SLASH_REGEXP + clean(route.path).replace(_constants__WEBPACK_IMPORTED_MODULE_0__.PARAMETER_REGEXP, function (full, dots, name) {
paramNames.push(name);
return _constants__WEBPACK_IMPORTED_MODULE_0__.REPLACE_VARIABLE_REGEXP;
}).replace(_constants__WEBPACK_IMPORTED_MODULE_0__.WILDCARD_REGEXP, _constants__WEBPACK_IMPORTED_MODULE_0__.REPLACE_WILDCARD).replace(_constants__WEBPACK_IMPORTED_MODULE_0__.NOT_SURE_REGEXP, _constants__WEBPACK_IMPORTED_MODULE_0__.REPLACE_NOT_SURE) + "$";
if (clean(route.path) === "") {
if (clean(current) === "") {
return {
url: current,
queryString: GETParams,
route: route,
data: null,
params: params
};
}
}
} else {
pattern = route.path;
}
var regexp = new RegExp(pattern, _constants__WEBPACK_IMPORTED_MODULE_0__.MATCH_REGEXP_FLAGS);
var match = current.match(regexp); // console.log(current, regexp);
if (match) {
var data = isString(route.path) ? regExpResultToParams(match, paramNames) : match.slice(1);
return {
url: current,
queryString: GETParams,
route: route,
data: data,
params: params
};
}
return false;
}
function pushStateAvailable() {
return !!(typeof window !== "undefined" && window.history && window.history.pushState);
}
function undefinedOrTrue(obj, key) {
return typeof obj[key] === "undefined" || obj[key] === true;
}
function parseNavigateOptions(source) {
if (!source) return {};
var pairs = source.split(",");
var options = {};
var resolveOptions;
pairs.forEach(function (str) {
var temp = str.split(":").map(function (v) {
return v.replace(/(^ +| +$)/g, "");
});
switch (temp[0]) {
case "historyAPIMethod":
options.historyAPIMethod = temp[1];
break;
case "resolveOptionsStrategy":
if (!resolveOptions) resolveOptions = {};
resolveOptions.strategy = temp[1];
break;
case "resolveOptionsHash":
if (!resolveOptions) resolveOptions = {};
resolveOptions.hash = temp[1] === "true";
break;
case "updateBrowserURL":
case "callHandler":
case "updateState":
case "force":
options[temp[0]] = temp[1] === "true";
break;
}
});
if (resolveOptions) {
options.resolveOptions = resolveOptions;
}
return options;
}
function windowAvailable() {
return typeof window !== "undefined";
}
function accumulateHooks(hooks, result) {
if (hooks === void 0) {
hooks = [];
}
if (result === void 0) {
result = {};
}
hooks.filter(function (h) {
return h;
}).forEach(function (h) {
["before", "after", "already", "leave"].forEach(function (type) {
if (h[type]) {
if (!result[type]) result[type] = [];
result[type].push(h[type]);
}
});
});
return result;
}
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(__webpack_module_cache__[moduleId]) {
/******/ return __webpack_module_cache__[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* 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/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 });
/******/ };
/******/ })();
/******/
/************************************************************************/
/******/ // module exports must be returned from runtime so entry inlining is disabled
/******/ // startup
/******/ // Load entry module and return exports
/******/ return __webpack_require__("./src/index.ts");
/******/ })()
.default;
});
//# sourceMappingURL=navigo.js.map
|
import{B as e}from"./index-5cf9ee19.js";export default class extends e{constructor(e){super(e);const t=document.documentElement,o=e=>{this.setMod("active",e)},n=e=>{"webkitUserSelect"in t.style?t.style.webkitUserSelect=e?"":"none":t.style.userSelect=e?"":"none"};this.on("click",(t=>{o(!1),e.nuDisabled||(t.stopPropagation(),this.tap(t))})),this.on("keydown",(t=>{e.nuDisabled||"Enter"!==t.key&&" "!==t.key||(t.stopPropagation(),t.preventDefault(),o(!0))})),this.on("keyup",(t=>{e.nuDisabled||"Enter"!==t.key&&" "!==t.key||(t.stopPropagation(),t.preventDefault(),this.tap(t),o(!1))})),this.on("blur",(()=>o(!1))),this.on(["mousedown","touchstart"],(t=>{e.nuDisabled||(t.stopPropagation(),o(!0),"mousedown"===t.type&&(n(!1),window.addEventListener("mouseup",(function e(){n(!0),window.removeEventListener("mouseup",e)}))))})),this.on(["mouseleave","mouseup","touchend"],(e=>{o(!1)}))}tap(e){const t=this.host.NuAction;t&&t.tap(e)}}
|
import{W as t,d as e,s,b as i}from"./index-19c813a5.js";import n from"./menu-29457b97.js";const o=n.prototype;export default class extends t{static get params(){return{input:!0,provideValue:!0,itemRole:"radio",contextValue:!0}}init(){this.props.disabled=t=>{const{host:n}=this,o=i(t);return e(n,"[nu-action]").forEach(t=>{s(t,"disabled",o)}),o},super.init(),this._items=[],null==this.value&&this.setValue("0"),this.setContext("radiogroup",this),this.on("keydown",this.onKeyDown.bind(this))}addItem(t){o.addItem.call(this,t)}removeItem(t){o.removeItem.call(this,t)}setCurrent(t){o.setCurrent.call(this,t)}getItemsInOrder(){return o.getItemsInOrder.call(this,"[nu-action]","NuAction")}onKeyDown(t){o.onKeyDown.call(this,t)}}
|
/**
* @version : 17.8.0 - Bridge.NET
* @author : Object.NET, Inc. http://bridge.net/
* @copyright : Copyright 2008-2019 Object.NET, Inc. http://object.net/
* @license : See license.txt and https://github.com/bridgedotnet/Bridge/blob/master/LICENSE.md
*/
Bridge.assembly("Bridge", function ($asm, globals) {
"use strict";
Bridge.define("Bridge.Console", {
statics: {
fields: {
BODY_WRAPPER_ID: null,
CONSOLE_MESSAGES_ID: null,
position: null,
instance$1: null
},
props: {
instance: {
get: function () {
if (Bridge.Console.instance$1 == null) {
Bridge.Console.instance$1 = new Bridge.Console();
}
return Bridge.Console.instance$1;
}
}
},
ctors: {
init: function () {
this.BODY_WRAPPER_ID = "bridge-body-wrapper";
this.CONSOLE_MESSAGES_ID = "bridge-console-messages";
this.position = "horizontal";
}
},
methods: {
initConsoleFunctions: function () {
var wl = System.Console.WriteLine;
var w = System.Console.Write;
var clr = System.Console.Clear;
var debug = System.Diagnostics.Debug.writeln;
var con = Bridge.global.console;
if (wl) {
System.Console.WriteLine = function (value) {
wl(value);
Bridge.Console.log(value, true);
}
}
if (w) {
System.Console.Write = function (value) {
w(value);
Bridge.Console.log(value, false);
}
}
if (clr) {
System.Console.Clear = function () {
clr();
Bridge.Console.clear();
}
}
if (debug) {
System.Diagnostics.Debug.writeln = function (value) {
debug(value);
Bridge.Console.debug(value);
}
}
if (con && con.error) {
var err = con.error;
con.error = function (msg) {
err.apply(con, arguments);
Bridge.Console.error(msg);
}
}
if (Bridge.isDefined(Bridge.global.window)) {
Bridge.global.window.addEventListener("error", function (e) {
Bridge.Console.error(System.Exception.create(e));
});
}
},
logBase: function (value, newLine, messageType) {
var $t;
if (newLine === void 0) { newLine = true; }
if (messageType === void 0) { messageType = 0; }
var self = Bridge.Console.instance;
var v = "";
if (value != null) {
var hasToString = value.ToString !== undefined;
v = (value.toString == { }.toString && !hasToString) ? JSON.stringify(value, null, 2) : hasToString ? value.ToString() : value.toString();
}
if (self.bufferedOutput != null) {
self.bufferedOutput = (self.bufferedOutput || "") + (v || "");
if (newLine) {
self.bufferedOutput = (self.bufferedOutput || "") + ("\n" || "");
}
return;
}
Bridge.Console.show();
if (self.isNewLine || self.currentMessageElement == null) {
var m = self.buildConsoleMessage(v, messageType);
self.consoleMessages.appendChild(m);
self.currentMessageElement = m;
} else {
var m1 = Bridge.unbox(self.currentMessageElement);
($t = m1.lastChild).innerHTML = ($t.innerHTML || "") + (v || "");
}
self.isNewLine = newLine;
},
error: function (value) {
Bridge.Console.logBase(value, true, 2);
},
debug: function (value) {
Bridge.Console.logBase(value, true, 1);
},
log: function (value, newLine) {
if (newLine === void 0) { newLine = true; }
Bridge.Console.logBase(value, newLine);
},
clear: function () {
var self = Bridge.Console.instance$1;
if (self == null) {
return;
}
var m = self.consoleMessages;
if (m != null) {
while (m.firstChild != null) {
m.removeChild(m.firstChild);
}
self.currentMessageElement = null;
}
if (self.bufferedOutput != null) {
self.bufferedOutput = "";
}
self.isNewLine = false;
},
hide: function () {
if (Bridge.Console.instance$1 == null) {
return;
}
var self = Bridge.Console.instance;
if (self.hidden) {
return;
}
self.close();
},
show: function () {
var self = Bridge.Console.instance;
if (!self.hidden) {
return;
}
self.init(true);
},
toggle: function () {
if (Bridge.Console.instance.hidden) {
Bridge.Console.show();
} else {
Bridge.Console.hide();
}
}
}
},
fields: {
svgNS: null,
consoleHeight: null,
consoleHeaderHeight: null,
tooltip: null,
consoleWrap: null,
consoleMessages: null,
bridgeIcon: null,
bridgeIconPath: null,
bridgeConsoleLabel: null,
closeBtn: null,
closeIcon: null,
closeIconPath: null,
consoleHeader: null,
consoleBody: null,
hidden: false,
isNewLine: false,
currentMessageElement: null,
bufferedOutput: null
},
ctors: {
init: function () {
this.svgNS = "http://www.w3.org/2000/svg";
this.consoleHeight = "300px";
this.consoleHeaderHeight = "35px";
this.hidden = true;
this.isNewLine = false;
},
ctor: function () {
this.$initialize();
this.init();
}
},
methods: {
init: function (reinit) {
if (reinit === void 0) { reinit = false; }
this.hidden = false;
var consoleWrapStyles = Bridge.fn.bind(this, $asm.$.Bridge.Console.f1)(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
var consoleHeaderStyles = $asm.$.Bridge.Console.f2(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
var consoleBodyStyles = $asm.$.Bridge.Console.f3(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
this.bridgeIcon = this.bridgeIcon || document.createElementNS(this.svgNS, "svg");
var items = Bridge.fn.bind(this, $asm.$.Bridge.Console.f4)(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
this.setAttributes(this.bridgeIcon, items);
this.bridgeIconPath = this.bridgeIconPath || document.createElementNS(this.svgNS, "path");
var items2 = new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor();
items2.setItem("d", "M19 14.4h2.2V9.6L19 7.1v7.3zm4.3-2.5v2.5h2.2l-2.2-2.5zm-8.5 2.5H17V4.8l-2.2-2.5v12.1zM0 14.4h3l7.5-8.5v8.5h2.2V0L0 14.4z");
items2.setItem("fill", "#555");
this.setAttributes(this.bridgeIconPath, items2);
this.bridgeConsoleLabel = this.bridgeConsoleLabel || document.createElement("span");
this.bridgeConsoleLabel.innerHTML = "Bridge Console";
this.closeBtn = this.closeBtn || document.createElement("span");
this.closeBtn.setAttribute("style", "position: relative;display: inline-block;float: right;cursor: pointer");
this.closeIcon = this.closeIcon || document.createElementNS(this.svgNS, "svg");
var items3 = Bridge.fn.bind(this, $asm.$.Bridge.Console.f5)(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
this.setAttributes(this.closeIcon, items3);
this.closeIconPath = this.closeIconPath || document.createElementNS(this.svgNS, "path");
var items4 = $asm.$.Bridge.Console.f6(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
this.setAttributes(this.closeIconPath, items4);
this.tooltip = this.tooltip || document.createElement("div");
this.tooltip.innerHTML = "Refresh page to open Bridge Console";
this.tooltip.setAttribute("style", "position: absolute;right: 30px;top: -6px;white-space: nowrap;padding: 7px;border-radius: 3px;background-color: rgba(0, 0, 0, 0.75);color: #eee;text-align: center;visibility: hidden;opacity: 0;-webkit-transition: all 0.25s ease-in-out;transition: all 0.25s ease-in-out;z-index: 1;");
Bridge.Console.position = "horizontal";
if (Bridge.referenceEquals(Bridge.Console.position, "horizontal")) {
this.wrapBodyContent();
consoleWrapStyles.setItem("right", "0");
consoleHeaderStyles.setItem("border-top", "1px solid #a3a3a3");
consoleBodyStyles.setItem("height", this.consoleHeight);
} else if (Bridge.referenceEquals(Bridge.Console.position, "vertical")) {
var consoleWidth = "400px";
document.body.style.marginLeft = consoleWidth;
consoleWrapStyles.setItem("top", "0");
consoleWrapStyles.setItem("width", consoleWidth);
consoleWrapStyles.setItem("border-right", "1px solid #a3a3a3");
consoleBodyStyles.setItem("height", "100%");
}
this.consoleWrap = this.consoleWrap || document.createElement("div");
this.consoleWrap.setAttribute("style", this.obj2Css(consoleWrapStyles));
this.consoleHeader = this.consoleHeader || document.createElement("div");
this.consoleHeader.setAttribute("style", this.obj2Css(consoleHeaderStyles));
this.consoleBody = this.consoleBody || document.createElement("div");
this.consoleBody.setAttribute("style", this.obj2Css(consoleBodyStyles));
this.consoleMessages = this.consoleMessages || document.createElement("ul");
var cm = this.consoleMessages;
cm.id = Bridge.Console.CONSOLE_MESSAGES_ID;
cm.setAttribute("style", "margin: 0;padding: 0;list-style: none;");
if (!reinit) {
this.bridgeIcon.appendChild(this.bridgeIconPath);
this.closeIcon.appendChild(this.closeIconPath);
this.closeBtn.appendChild(this.closeIcon);
this.closeBtn.appendChild(this.tooltip);
this.consoleHeader.appendChild(this.bridgeIcon);
this.consoleHeader.appendChild(this.bridgeConsoleLabel);
this.consoleHeader.appendChild(this.closeBtn);
this.consoleBody.appendChild(cm);
this.consoleWrap.appendChild(this.consoleHeader);
this.consoleWrap.appendChild(this.consoleBody);
document.body.appendChild(this.consoleWrap);
this.closeBtn.addEventListener("click", Bridge.fn.cacheBind(this, this.close));
this.closeBtn.addEventListener("mouseover", Bridge.fn.cacheBind(this, this.showTooltip));
this.closeBtn.addEventListener("mouseout", Bridge.fn.cacheBind(this, this.hideTooltip));
}
},
showTooltip: function () {
var self = Bridge.Console.instance;
self.tooltip.style.right = "20px";
self.tooltip.style.visibility = "visible";
self.tooltip.style.opacity = "1";
},
hideTooltip: function () {
var self = Bridge.Console.instance;
self.tooltip.style.right = "30px";
self.tooltip.style.opacity = "0";
},
close: function () {
this.hidden = true;
this.consoleWrap.style.display = "none";
if (Bridge.referenceEquals(Bridge.Console.position, "horizontal")) {
this.unwrapBodyContent();
} else if (Bridge.referenceEquals(Bridge.Console.position, "vertical")) {
document.body.removeAttribute("style");
}
},
wrapBodyContent: function () {
if (document.body == null) {
return;
}
var bodyStyle = document.defaultView.getComputedStyle(document.body, null);
var bodyPaddingTop = bodyStyle.paddingTop;
var bodyPaddingRight = bodyStyle.paddingRight;
var bodyPaddingBottom = bodyStyle.paddingBottom;
var bodyPaddingLeft = bodyStyle.paddingLeft;
var bodyMarginTop = bodyStyle.marginTop;
var bodyMarginRight = bodyStyle.marginRight;
var bodyMarginBottom = bodyStyle.marginBottom;
var bodyMarginLeft = bodyStyle.marginLeft;
var div = document.createElement("div");
div.id = Bridge.Console.BODY_WRAPPER_ID;
div.setAttribute("style", "height: calc(100vh - " + (this.consoleHeight || "") + " - " + (this.consoleHeaderHeight || "") + ");" + "margin-top: calc(-1 * " + "(" + (((bodyMarginTop || "") + " + " + (bodyPaddingTop || "")) || "") + "));" + "margin-right: calc(-1 * " + "(" + (((bodyMarginRight || "") + " + " + (bodyPaddingRight || "")) || "") + "));" + "margin-left: calc(-1 * " + "(" + (((bodyMarginLeft || "") + " + " + (bodyPaddingLeft || "")) || "") + "));" + "padding-top: calc(" + (((bodyMarginTop || "") + " + " + (bodyPaddingTop || "")) || "") + ");" + "padding-right: calc(" + (((bodyMarginRight || "") + " + " + (bodyPaddingRight || "")) || "") + ");" + "padding-bottom: calc(" + (((bodyMarginBottom || "") + " + " + (bodyPaddingBottom || "")) || "") + ");" + "padding-left: calc(" + (((bodyMarginLeft || "") + " + " + (bodyPaddingLeft || "")) || "") + ");" + "overflow-x: auto;" + "box-sizing: border-box !important;");
while (document.body.firstChild != null) {
div.appendChild(document.body.firstChild);
}
document.body.appendChild(div);
},
unwrapBodyContent: function () {
var bridgeBodyWrap = document.getElementById(Bridge.Console.BODY_WRAPPER_ID);
if (bridgeBodyWrap == null) {
return;
}
while (bridgeBodyWrap.firstChild != null) {
document.body.insertBefore(bridgeBodyWrap.firstChild, bridgeBodyWrap);
}
document.body.removeChild(bridgeBodyWrap);
},
buildConsoleMessage: function (message, messageType) {
var messageItem = document.createElement("li");
messageItem.setAttribute("style", "padding:5px 10px;border-bottom:1px solid #f0f0f0;position:relative;");
var messageIcon = document.createElementNS(this.svgNS, "svg");
var items5 = Bridge.fn.bind(this, $asm.$.Bridge.Console.f7)(new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor());
this.setAttributes(messageIcon, items5);
var color = "#555";
if (messageType === 2) {
color = "#d65050";
} else if (messageType === 1) {
color = "#1800FF";
}
var messageIconPath = document.createElementNS(this.svgNS, "path");
var items6 = new (System.Collections.Generic.Dictionary$2(System.String,System.String)).ctor();
items6.setItem("d", "M3.8 3.5L.7 6.6s-.1.1-.2.1-.1 0-.2-.1l-.2-.3C0 6.2 0 6.2 0 6.1c0 0 0-.1.1-.1l2.6-2.6L.1.7C0 .7 0 .6 0 .6 0 .5 0 .5.1.4L.4.1c0-.1.1-.1.2-.1s.1 0 .2.1l3.1 3.1s.1.1.1.2-.1.1-.2.1z");
items6.setItem("fill", color);
this.setAttributes(messageIconPath, items6);
messageIcon.appendChild(messageIconPath);
var messageContainer = document.createElement("div");
messageContainer.innerText = message;
messageContainer.setAttribute("style", "color:" + (color || "") + ";white-space:pre;margin-left:12px;line-height:1.4;min-height:18px;");
messageItem.appendChild(messageIcon);
messageItem.appendChild(messageContainer);
return messageItem;
},
setAttributes: function (el, attrs) {
var $t;
$t = Bridge.getEnumerator(attrs);
try {
while ($t.moveNext()) {
var item = $t.Current;
el.setAttribute(item.key, item.value);
}
} finally {
if (Bridge.is($t, System.IDisposable)) {
$t.System$IDisposable$Dispose();
}
}
},
obj2Css: function (obj) {
var $t;
var str = "";
$t = Bridge.getEnumerator(obj);
try {
while ($t.moveNext()) {
var item = $t.Current;
str = (str || "") + (((item.key.toLowerCase() || "") + ":" + (item.value || "") + ";") || "");
}
} finally {
if (Bridge.is($t, System.IDisposable)) {
$t.System$IDisposable$Dispose();
}
}
return str;
}
}
});
Bridge.ns("Bridge.Console", $asm.$);
Bridge.apply($asm.$.Bridge.Console, {
f1: function (_o1) {
_o1.add("position", "fixed");
_o1.add("left", "0");
_o1.add("bottom", "0");
_o1.add("padding-top", this.consoleHeaderHeight);
_o1.add("background-color", "#fff");
_o1.add("font", "normal normal normal 13px/1 sans-serif");
_o1.add("color", "#555");
return _o1;
},
f2: function (_o2) {
_o2.add("position", "absolute");
_o2.add("top", "0");
_o2.add("left", "0");
_o2.add("right", "0");
_o2.add("height", "35px");
_o2.add("padding", "9px 15px 7px 10px");
_o2.add("border-bottom", "1px solid #ccc");
_o2.add("background-color", "#f3f3f3");
_o2.add("box-sizing", "border-box");
return _o2;
},
f3: function (_o3) {
_o3.add("overflow-x", "auto");
_o3.add("font-family", "Menlo, Monaco, Consolas, 'Courier New', monospace");
return _o3;
},
f4: function (_o4) {
_o4.add("xmlns", this.svgNS);
_o4.add("width", "25.5");
_o4.add("height", "14.4");
_o4.add("viewBox", "0 0 25.5 14.4");
_o4.add("style", "margin: 0 3px 3px 0;vertical-align:middle;");
return _o4;
},
f5: function (_o5) {
_o5.add("xmlns", this.svgNS);
_o5.add("width", "11.4");
_o5.add("height", "11.4");
_o5.add("viewBox", "0 0 11.4 11.4");
_o5.add("style", "vertical-align: middle;");
return _o5;
},
f6: function (_o6) {
_o6.add("d", "M11.4 1.4L10 0 5.7 4.3 1.4 0 0 1.4l4.3 4.3L0 10l1.4 1.4 4.3-4.3 4.3 4.3 1.4-1.4-4.3-4.3");
_o6.add("fill", "#555");
return _o6;
},
f7: function (_o1) {
_o1.add("xmlns", this.svgNS);
_o1.add("width", "3.9");
_o1.add("height", "6.7");
_o1.add("viewBox", "0 0 3.9 6.7");
_o1.add("style", "vertical-align:middle;position: absolute;top: 10.5px;");
return _o1;
}
});
Bridge.init(function () { Bridge.Console.initConsoleFunctions(); });
});
|
/*!
* Native JavaScript for Bootstrap Modal v3.0.15-alpha2 (https://thednp.github.io/bootstrap.native/)
* Copyright 2015-2021 © dnp_theme
* Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE)
*/
var addEventListener = 'addEventListener';
var removeEventListener = 'removeEventListener';
var supportPassive = (function () {
var result = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function get() {
result = true;
return result;
},
});
document[addEventListener]('DOMContentLoaded', function wrap() {
document[removeEventListener]('DOMContentLoaded', wrap, opts);
}, opts);
} catch (e) {
throw Error('Passive events are not supported');
}
return result;
})();
// general event options
var passiveHandler = supportPassive ? { passive: true } : false;
var transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend';
var supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style;
var transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration';
var transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty';
function getElementTransitionDuration(element) {
var computedStyle = getComputedStyle(element);
var propertyValue = computedStyle[transitionProperty];
var durationValue = computedStyle[transitionDuration];
var durationScale = durationValue.includes('ms') ? 1 : 1000;
var duration = supportTransition && propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
function emulateTransitionEnd(element, handler) {
var called = 0;
var endEvent = new Event(transitionEndEvent);
var duration = getElementTransitionDuration(element);
if (duration) {
element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) {
if (e.target === element) {
handler.apply(element, [e]);
element.removeEventListener(transitionEndEvent, transitionEndWrapper);
called = 1;
}
});
setTimeout(function () {
if (!called) { element.dispatchEvent(endEvent); }
}, duration + 17);
} else {
handler.apply(element, [endEvent]);
}
}
function queryElement(selector, parent) {
var lookUp = parent && parent instanceof Element ? parent : document;
return selector instanceof Element ? selector : lookUp.querySelector(selector);
}
function reflow(element) {
return element.offsetHeight;
}
function bootstrapCustomEvent(eventType, componentName, eventProperties) {
var OriginalCustomEvent = new CustomEvent((eventType + ".bs." + componentName), { cancelable: true });
if (typeof eventProperties !== 'undefined') {
Object.keys(eventProperties).forEach(function (key) {
Object.defineProperty(OriginalCustomEvent, key, {
value: eventProperties[key],
});
});
}
return OriginalCustomEvent;
}
function dispatchCustomEvent(customEvent) {
if (this) { this.dispatchEvent(customEvent); }
}
function setFocus(element) {
element.focus();
}
/* Native JavaScript for Bootstrap 4 | Modal
-------------------------------------------- */
// MODAL DEFINITION
// ================
function Modal(elem, opsInput) { // element can be the modal/triggering button
var element;
// set options
var options = opsInput || {};
// bind, modal
var self = this;
var modal;
// custom events
var showCustomEvent;
var shownCustomEvent;
var hideCustomEvent;
var hiddenCustomEvent;
// event targets and other
var relatedTarget = null;
var scrollBarWidth;
var overlay;
var overlayDelay;
// also find fixed-top / fixed-bottom items
var fixedItems;
var ops = {};
// private methods
function setScrollbar() {
var bodyClassList = document.body.classList;
var openModal = bodyClassList.contains('modal-open');
var bodyPad = parseInt(getComputedStyle(document.body).paddingRight, 10);
var docClientHeight = document.documentElement.clientHeight;
var docScrollHeight = document.documentElement.scrollHeight;
var bodyClientHeight = document.body.clientHeight;
var bodyScrollHeight = document.body.scrollHeight;
var bodyOverflow = docClientHeight !== docScrollHeight
|| bodyClientHeight !== bodyScrollHeight;
var modalOverflow = modal.clientHeight !== modal.scrollHeight;
scrollBarWidth = measureScrollbar();
modal.style.paddingRight = !modalOverflow && scrollBarWidth ? (scrollBarWidth + "px") : '';
document.body.style.paddingRight = modalOverflow || bodyOverflow
? ((bodyPad + (openModal ? 0 : scrollBarWidth)) + "px") : '';
if (fixedItems.length) {
fixedItems.forEach(function (fixed) {
var itemPad = getComputedStyle(fixed).paddingRight;
fixed.style.paddingRight = modalOverflow || bodyOverflow
? ((parseInt(itemPad, 10) + (openModal ? 0 : scrollBarWidth)) + "px")
: ((parseInt(itemPad, 10)) + "px");
});
}
}
function resetScrollbar() {
document.body.style.paddingRight = '';
modal.style.paddingRight = '';
if (fixedItems.length) {
fixedItems.forEach(function (fixed) {
fixed.style.paddingRight = '';
});
}
}
function measureScrollbar() {
var scrollDiv = document.createElement('div');
scrollDiv.className = 'modal-scrollbar-measure'; // this is here to stay
document.body.appendChild(scrollDiv);
var widthValue = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return widthValue;
}
function createOverlay() {
var newOverlay = document.createElement('div');
overlay = queryElement('.modal-backdrop');
if (overlay === null) {
newOverlay.setAttribute('class', ("modal-backdrop" + (ops.animation ? ' fade' : '')));
overlay = newOverlay;
document.body.appendChild(overlay);
}
return overlay;
}
function removeOverlay() {
overlay = queryElement('.modal-backdrop');
if (overlay && !document.getElementsByClassName('modal show')[0]) {
document.body.removeChild(overlay); overlay = null;
}
if (overlay === null) {
document.body.classList.remove('modal-open');
resetScrollbar();
}
}
function toggleEvents(add) {
var action = add ? 'addEventListener' : 'removeEventListener';
window[action]('resize', self.update, passiveHandler);
modal[action]('click', dismissHandler, false);
document[action]('keydown', keyHandler, false);
}
// triggers
function beforeShow() {
modal.style.display = 'block';
setScrollbar();
if (!document.getElementsByClassName('modal show')[0]) { document.body.classList.add('modal-open'); }
modal.classList.add('show');
modal.setAttribute('aria-hidden', false);
if (modal.classList.contains('fade')) { emulateTransitionEnd(modal, triggerShow); }
else { triggerShow(); }
}
function triggerShow() {
setFocus(modal);
modal.isAnimating = false;
toggleEvents(1);
shownCustomEvent = bootstrapCustomEvent('shown', 'modal', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(modal, shownCustomEvent);
}
function triggerHide(force) {
modal.style.display = '';
if (element) { setFocus(element); }
overlay = queryElement('.modal-backdrop');
// force can also be the transitionEvent object, we wanna make sure it's not
if (force !== 1 && overlay && overlay.classList.contains('show') && !document.getElementsByClassName('modal show')[0]) {
overlay.classList.remove('show');
emulateTransitionEnd(overlay, removeOverlay);
} else {
removeOverlay();
}
toggleEvents();
modal.isAnimating = false;
hiddenCustomEvent = bootstrapCustomEvent('hidden', 'modal');
dispatchCustomEvent.call(modal, hiddenCustomEvent);
}
// handlers
function clickHandler(e) {
if (modal.isAnimating) { return; }
var clickTarget = e.target;
var modalID = "#" + (modal.getAttribute('id'));
var targetAttrValue = clickTarget.getAttribute('data-target') || clickTarget.getAttribute('href');
var elemAttrValue = element.getAttribute('data-target') || element.getAttribute('href');
if (!modal.classList.contains('show')
&& ((clickTarget === element && targetAttrValue === modalID)
|| (element.contains(clickTarget) && elemAttrValue === modalID))) {
modal.modalTrigger = element;
relatedTarget = element;
self.show();
e.preventDefault();
}
}
function keyHandler(ref) {
var which = ref.which;
if (!modal.isAnimating && ops.keyboard && which === 27 && modal.classList.contains('show')) {
self.hide();
}
}
function dismissHandler(e) {
if (modal.isAnimating) { return; }
var clickTarget = e.target;
var hasData = clickTarget.getAttribute('data-dismiss') === 'modal';
var parentWithData = clickTarget.closest('[data-dismiss="modal"]');
if (modal.classList.contains('show') && (parentWithData || hasData
|| (clickTarget === modal && ops.backdrop !== 'static'))) {
self.hide(); relatedTarget = null;
e.preventDefault();
}
}
// public methods
self.toggle = function () {
if (modal.classList.contains('show')) { self.hide(); } else { self.show(); }
};
self.show = function () {
if (modal.classList.contains('show') && !!modal.isAnimating) { return; }
showCustomEvent = bootstrapCustomEvent('show', 'modal', { relatedTarget: relatedTarget });
dispatchCustomEvent.call(modal, showCustomEvent);
if (showCustomEvent.defaultPrevented) { return; }
modal.isAnimating = true;
// we elegantly hide any opened modal
var currentOpen = document.getElementsByClassName('modal show')[0];
if (currentOpen && currentOpen !== modal) {
if (currentOpen.modalTrigger) { currentOpen.modalTrigger.Modal.hide(); }
if (currentOpen.Modal) { currentOpen.Modal.hide(); }
}
if (ops.backdrop) { overlay = createOverlay(); }
if (overlay && !currentOpen && !overlay.classList.contains('show')) {
reflow(overlay);
overlayDelay = getElementTransitionDuration(overlay);
overlay.classList.add('show');
}
if (!currentOpen) { setTimeout(beforeShow, overlay && overlayDelay ? overlayDelay : 0); }
else { beforeShow(); }
};
self.hide = function (force) {
if (!modal.classList.contains('show')) { return; }
hideCustomEvent = bootstrapCustomEvent('hide', 'modal');
dispatchCustomEvent.call(modal, hideCustomEvent);
if (hideCustomEvent.defaultPrevented) { return; }
modal.isAnimating = true;
modal.classList.remove('show');
modal.setAttribute('aria-hidden', true);
if (modal.classList.contains('fade') && force !== 1) { emulateTransitionEnd(modal, triggerHide); }
else { triggerHide(); }
};
self.setContent = function (content) {
queryElement('.modal-content', modal).innerHTML = content;
};
self.update = function () {
if (modal.classList.contains('show')) {
setScrollbar();
}
};
self.dispose = function () {
self.hide(1);
if (element) { element.removeEventListener('click', clickHandler, false); delete element.Modal; } else { delete modal.Modal; }
};
// init
// the modal (both JavaScript / DATA API init) / triggering button element (DATA API)
element = queryElement(elem);
// determine modal, triggering element
var checkModal = queryElement(element.getAttribute('data-target') || element.getAttribute('href'));
modal = element.classList.contains('modal') ? element : checkModal;
// set fixed items
fixedItems = Array.from(document.getElementsByClassName('fixed-top'))
.concat(Array.from(document.getElementsByClassName('fixed-bottom')));
if (element.classList.contains('modal')) { element = null; } // modal is now independent of it's triggering element
// reset on re-init
if (element && element.Modal) { element.Modal.dispose(); }
if (modal && modal.Modal) { modal.Modal.dispose(); }
// set options
ops.keyboard = !(options.keyboard === false || modal.getAttribute('data-keyboard') === 'false');
ops.backdrop = options.backdrop === 'static' || modal.getAttribute('data-backdrop') === 'static' ? 'static' : true;
ops.backdrop = options.backdrop === false || modal.getAttribute('data-backdrop') === 'false' ? false : ops.backdrop;
ops.animation = !!modal.classList.contains('fade');
ops.content = options.content; // JavaScript only
// set an initial state of the modal
modal.isAnimating = false;
// prevent adding event handlers over and over
// modal is independent of a triggering element
if (element && !element.Modal) {
element.addEventListener('click', clickHandler, false);
}
if (ops.content) {
self.setContent(ops.content.trim());
}
// set associations
if (element) {
modal.modalTrigger = element;
element.Modal = self;
} else {
modal.Modal = self;
}
}
export default Modal;
|
/*
Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("devtools","ko",{title:"구성 요소 정보",dialogName:"다이얼로그 윈도우 이름",tabName:"탭 이름",elementId:"요소 ID",elementType:"요소 형식"});
|
/*! shepherd.js 8.0.1 */
'use strict';(function(E,Y){"object"===typeof exports&&"undefined"!==typeof module?module.exports=Y():"function"===typeof define&&define.amd?define(Y):(E=E||self,E.Shepherd=Y())})(this,function(){function E(a,b){return!1!==b.clone&&b.isMergeableObject(a)?R(Array.isArray(a)?[]:{},a,b):a}function Y(a,b,c){return a.concat(b).map(function(a){return E(a,c)})}function ob(a){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(a).filter(function(b){return a.propertyIsEnumerable(b)}):[]}function Ca(a){return Object.keys(a).concat(ob(a))}
function Da(a,b){try{return b in a}catch(c){return!1}}function pb(a,b,c){var d={};c.isMergeableObject(a)&&Ca(a).forEach(function(b){d[b]=E(a[b],c)});Ca(b).forEach(function(e){if(!Da(a,e)||Object.hasOwnProperty.call(a,e)&&Object.propertyIsEnumerable.call(a,e))if(Da(a,e)&&c.isMergeableObject(b[e])){if(c.customMerge){var f=c.customMerge(e);f="function"===typeof f?f:R}else f=R;d[e]=f(a[e],b[e],c)}else d[e]=E(b[e],c)});return d}function R(a,b,c){c=c||{};c.arrayMerge=c.arrayMerge||Y;c.isMergeableObject=
c.isMergeableObject||qb;c.cloneUnlessOtherwiseSpecified=E;var d=Array.isArray(b),e=Array.isArray(a);return d!==e?E(b,c):d?c.arrayMerge(a,b,c):pb(a,b,c)}function S(a){return"function"===typeof a}function Z(a){return"string"===typeof a}function Ea(a){let b=Object.getOwnPropertyNames(a.constructor.prototype);for(let c=0;c<b.length;c++){let d=b[c],e=a[d];"constructor"!==d&&"function"===typeof e&&(a[d]=e.bind(a))}return a}function rb(a,b){return c=>{if(b.isOpen()){let d=b.el&&c.currentTarget===b.el;(void 0!==
a&&c.currentTarget.matches(a)||d)&&b.tour.next()}}}function sb(a){let {event:b,selector:c}=a.options.advanceOn||{};if(b){let d=rb(c,a),e;try{e=document.querySelector(c)}catch(f){}if(void 0===c||e)e?(e.addEventListener(b,d),a.on("destroy",()=>e.removeEventListener(b,d))):(document.body.addEventListener(b,d,!0),a.on("destroy",()=>document.body.removeEventListener(b,d,!0)));else return console.error(`No element was found for the selector supplied to advanceOn: ${c}`)}else return console.error("advanceOn was defined, but no event name was passed.")}
function aa(a){a=a.getBoundingClientRect();return{width:a.width,height:a.height,top:a.top,right:a.right,bottom:a.bottom,left:a.left,x:a.left,y:a.top}}function x(a){return"[object Window]"!==a.toString()?(a=a.ownerDocument)?a.defaultView:window:a}function pa(a){a=x(a);return{scrollLeft:a.pageXOffset,scrollTop:a.pageYOffset}}function ba(a){var b=x(a).Element;return a instanceof b||a instanceof Element}function C(a){var b=x(a).HTMLElement;return a instanceof b||a instanceof HTMLElement}function F(a){return a?
(a.nodeName||"").toLowerCase():null}function J(a){return(ba(a)?a.ownerDocument:a.document).documentElement}function Fa(a){return aa(J(a)).left+pa(a).scrollLeft}function ca(a){return x(a).getComputedStyle(a)}function qa(a){a=ca(a);return/auto|scroll|overlay|hidden/.test(a.overflow+a.overflowY+a.overflowX)}function Ga(a,b,c){void 0===c&&(c=!1);var d=J(b);a=aa(a);var e={scrollLeft:0,scrollTop:0},f={x:0,y:0};if(!c){if("body"!==F(b)||qa(d))e=b!==x(b)&&C(b)?{scrollLeft:b.scrollLeft,scrollTop:b.scrollTop}:
pa(b);C(b)?(f=aa(b),f.x+=b.clientLeft,f.y+=b.clientTop):d&&(f.x=Fa(d))}return{x:a.left+e.scrollLeft-f.x,y:a.top+e.scrollTop-f.y,width:a.width,height:a.height}}function ra(a){return{x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}}function Ha(a){return"html"===F(a)?a:a.assignedSlot||a.parentNode||a.host||J(a)}function Ia(a){return 0<=["html","body","#document"].indexOf(F(a))?a.ownerDocument.body:C(a)&&qa(a)?a:Ia(Ha(a))}function da(a,b){void 0===b&&(b=[]);var c=Ia(a);a="body"===
F(c);var d=x(c);c=a?[d].concat(d.visualViewport||[],qa(c)?c:[]):c;b=b.concat(c);return a?b:b.concat(da(Ha(c)))}function Ja(a){return C(a)&&"fixed"!==ca(a).position?a.offsetParent:null}function ea(a){var b=x(a);for(a=Ja(a);a&&0<=["table","td","th"].indexOf(F(a));)a=Ja(a);return a&&"body"===F(a)&&"static"===ca(a).position?b:a||b}function tb(a){function b(a){d.add(a.name);[].concat(a.requires||[],a.requiresIfExists||[]).forEach(function(a){d.has(a)||(a=c.get(a))&&b(a)});e.push(a)}var c=new Map,d=new Set,
e=[];a.forEach(function(a){c.set(a.name,a)});a.forEach(function(a){d.has(a.name)||b(a)});return e}function ub(a){var b=tb(a);return vb.reduce(function(a,d){return a.concat(b.filter(function(a){return a.phase===d}))},[])}function wb(a){var b;return function(){b||(b=new Promise(function(c){Promise.resolve().then(function(){b=void 0;c(a())})}));return b}}function D(a){return a.split("-")[0]}function xb(a){var b=a.reduce(function(a,b){var c=a[b.name];a[b.name]=c?Object.assign({},c,{},b,{options:Object.assign({},
c.options,{},b.options),data:Object.assign({},c.data,{},b.data)}):b;return a},{});return Object.keys(b).map(function(a){return b[a]})}function Ka(){for(var a=arguments.length,b=Array(a),c=0;c<a;c++)b[c]=arguments[c];return!b.some(function(a){return!(a&&"function"===typeof a.getBoundingClientRect)})}function sa(a){return 0<=["top","bottom"].indexOf(a)?"x":"y"}function La(a){var b=a.reference,c=a.element,d=(a=a.placement)?D(a):null;a=a?a.split("-")[1]:null;var e=b.x+b.width/2-c.width/2,f=b.y+b.height/
2-c.height/2;switch(d){case "top":e={x:e,y:b.y-c.height};break;case "bottom":e={x:e,y:b.y+b.height};break;case "right":e={x:b.x+b.width,y:f};break;case "left":e={x:b.x-c.width,y:f};break;default:e={x:b.x,y:b.y}}d=d?sa(d):null;if(null!=d)switch(f="y"===d?"height":"width",a){case "start":e[d]=Math.floor(e[d])-Math.floor(b[f]/2-c[f]/2);break;case "end":e[d]=Math.floor(e[d])+Math.ceil(b[f]/2-c[f]/2)}return e}function Ma(a){var b,c=a.popper,d=a.popperRect,e=a.placement,f=a.offsets,h=a.position,k=a.gpuAcceleration,
m=a.adaptive,g=window.devicePixelRatio||1;a=Math.round(f.x*g)/g||0;g=Math.round(f.y*g)/g||0;var l=f.hasOwnProperty("x");f=f.hasOwnProperty("y");var q="left",t="top",p=window;if(m){var B=ea(c);B===x(c)&&(B=J(c));"top"===e&&(t="bottom",g-=B.clientHeight-d.height,g*=k?1:-1);"left"===e&&(q="right",a-=B.clientWidth-d.width,a*=k?1:-1)}c=Object.assign({position:h},m&&yb);if(k){var r;return Object.assign({},c,(r={},r[t]=f?"0":"",r[q]=l?"0":"",r.transform=2>(p.devicePixelRatio||1)?"translate("+a+"px, "+g+
"px)":"translate3d("+a+"px, "+g+"px, 0)",r))}return Object.assign({},c,(b={},b[t]=f?g+"px":"",b[q]=l?a+"px":"",b.transform="",b))}function ja(a){return a.replace(/left|right|bottom|top/g,function(a){return zb[a]})}function Na(a){return a.replace(/start|end/g,function(a){return Ab[a]})}function Oa(a,b){var c=!(!b.getRootNode||!b.getRootNode().host);if(a.contains(b))return!0;if(c){do{if(b&&a.isSameNode(b))return!0;b=b.parentNode||b.host}while(b)}return!1}function ta(a){return Object.assign({},a,{left:a.x,
top:a.y,right:a.x+a.width,bottom:a.y+a.height})}function Pa(a,b){if("viewport"===b){var c=x(a);a=c.visualViewport;b=c.innerWidth;c=c.innerHeight;a&&/iPhone|iPod|iPad/.test(navigator.platform)&&(b=a.width,c=a.height);a=ta({width:b,height:c,x:0,y:0})}else C(b)?a=aa(b):(c=J(a),a=x(c),b=pa(c),c=Ga(J(c),a),c.height=Math.max(c.height,a.innerHeight),c.width=Math.max(c.width,a.innerWidth),c.x=-b.scrollLeft,c.y=-b.scrollTop,a=ta(c));return a}function Bb(a){var b=da(a),c=0<=["absolute","fixed"].indexOf(ca(a).position)&&
C(a)?ea(a):a;return ba(c)?b.filter(function(a){return ba(a)&&Oa(a,c)}):[]}function Cb(a,b,c){b="clippingParents"===b?Bb(a):[].concat(b);c=[].concat(b,[c]);c=c.reduce(function(b,c){var d=Pa(a,c);c=C(c)?c:J(a);var e=x(c);var k=C(c)?ca(c):{};parseFloat(k.borderTopWidth);var m=parseFloat(k.borderRightWidth)||0;var g=parseFloat(k.borderBottomWidth)||0;var l=parseFloat(k.borderLeftWidth)||0;k="html"===F(c);var q=Fa(c),t=c.clientWidth+m,p=c.clientHeight+g;k&&50<e.innerHeight-c.clientHeight&&(p=e.innerHeight-
g);g=k?0:c.clientTop;m=c.clientLeft>l?m:k?e.innerWidth-t-q:c.offsetWidth-t;e=k?e.innerHeight-p:c.offsetHeight-p;c=k?q:c.clientLeft;b.top=Math.max(d.top+g,b.top);b.right=Math.min(d.right-m,b.right);b.bottom=Math.min(d.bottom-e,b.bottom);b.left=Math.max(d.left+c,b.left);return b},Pa(a,c[0]));c.width=c.right-c.left;c.height=c.bottom-c.top;c.x=c.left;c.y=c.top;return c}function Qa(a){return Object.assign({},{top:0,right:0,bottom:0,left:0},{},a)}function Ra(a,b){return b.reduce(function(b,d){b[d]=a;return b},
{})}function fa(a,b){void 0===b&&(b={});var c=b;b=c.placement;b=void 0===b?a.placement:b;var d=c.boundary,e=void 0===d?"clippingParents":d;d=c.rootBoundary;var f=void 0===d?"viewport":d;d=c.elementContext;d=void 0===d?"popper":d;var h=c.altBoundary,k=void 0===h?!1:h;c=c.padding;c=void 0===c?0:c;c=Qa("number"!==typeof c?c:Ra(c,ha));var m=a.elements.reference;h=a.rects.popper;k=a.elements[k?"popper"===d?"reference":"popper":d];e=Cb(ba(k)?k:k.contextElement||J(a.elements.popper),e,f);f=aa(m);k=La({reference:f,
element:h,strategy:"absolute",placement:b});h=ta(Object.assign({},h,{},k));f="popper"===d?h:f;var g={top:e.top-f.top+c.top,bottom:f.bottom-e.bottom+c.bottom,left:e.left-f.left+c.left,right:f.right-e.right+c.right};a=a.modifiersData.offset;if("popper"===d&&a){var l=a[b];Object.keys(g).forEach(function(a){var b=0<=["right","bottom"].indexOf(a)?1:-1,c=0<=["top","bottom"].indexOf(a)?"y":"x";g[a]+=l[c]*b})}return g}function Db(a,b){void 0===b&&(b={});var c=b.boundary,d=b.rootBoundary,e=b.padding,f=b.flipVariations,
h=b.allowedAutoPlacements,k=void 0===h?Sa:h,m=b.placement.split("-")[1],g=(m?f?Ta:Ta.filter(function(a){return a.split("-")[1]===m}):ha).filter(function(a){return 0<=k.indexOf(a)}).reduce(function(b,f){b[f]=fa(a,{placement:f,boundary:c,rootBoundary:d,padding:e})[D(f)];return b},{});return Object.keys(g).sort(function(a,b){return g[a]-g[b]})}function Eb(a){if("auto"===D(a))return[];var b=ja(a);return[Na(a),b,Na(b)]}function Ua(a,b,c){void 0===c&&(c={x:0,y:0});return{top:a.top-b.height-c.y,right:a.right-
b.width+c.x,bottom:a.bottom-b.height+c.y,left:a.left-b.width-c.x}}function Va(a){return["top","right","bottom","left"].some(function(b){return 0<=a[b]})}function Fb(){return[{name:"applyStyles",fn({state:a}){Object.keys(a.elements).forEach(b=>{if("popper"===b){var c=a.attributes[b]||{},d=a.elements[b];Object.assign(d.style,{position:"fixed",left:"50%",top:"50%",transform:"translate(-50%, -50%)"});Object.keys(c).forEach(a=>{let b=c[a];!1===b?d.removeAttribute(a):d.setAttribute(a,!0===b?"":b)})}})}},
{name:"computeStyles",options:{adaptive:!1}}]}function Gb(a){let b=Fb(),c={placement:"top",strategy:"fixed",modifiers:[{name:"focusAfterRender",enabled:!0,phase:"afterWrite",fn(){setTimeout(()=>{a.el&&a.el.focus()},300)}}]};return c={...c,modifiers:Array.from(new Set([...c.modifiers,...b]))}}function Wa(a){return Z(a)&&""!==a?"-"!==a.charAt(a.length-1)?`${a}-`:a:""}function ua(a){a=a.options.attachTo||{};let b=Object.assign({},a);if(Z(a.element)){try{b.element=document.querySelector(a.element)}catch(c){}b.element||
console.error(`The element for this Shepherd step was not found ${a.element}`)}return b}function va(){let a=Date.now();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,b=>{let c=(a+16*Math.random())%16|0;a=Math.floor(a/16);return("x"==b?c:c&3|8).toString(16)})}function Hb(a,b){let c={modifiers:[{name:"preventOverflow",options:{altAxis:!0}},{name:"focusAfterRender",enabled:!0,phase:"afterWrite",fn(){setTimeout(()=>{b.el&&b.el.focus()},300)}}],strategy:"absolute"};b.isCentered()?c=Gb(b):
c.placement=a.on;(a=b.tour&&b.tour.options&&b.tour.options.defaultStepOptions)&&(c=Xa(a,c));return c=Xa(b.options,c)}function Xa(a,b){if(a.popperOptions){let c=Object.assign({},b,a.popperOptions);if(a.popperOptions.modifiers&&0<a.popperOptions.modifiers.length){let d=a.popperOptions.modifiers.map(a=>a.name);b=b.modifiers.filter(a=>!d.includes(a.name));c.modifiers=Array.from(new Set([...b,...a.popperOptions.modifiers]))}return c}return b}function y(){}function Ib(a,b){for(let c in b)a[c]=b[c];return a}
function T(a){return a()}function Ya(a){return"function"===typeof a}function G(a,b){return a!=a?b==b:a!==b||a&&"object"===typeof a||"function"===typeof a}function z(a){a.parentNode.removeChild(a)}function Za(a){return document.createElementNS("http://www.w3.org/2000/svg",a)}function ka(a,b,c,d){a.addEventListener(b,c,d);return()=>a.removeEventListener(b,c,d)}function u(a,b,c){null==c?a.removeAttribute(b):a.getAttribute(b)!==c&&a.setAttribute(b,c)}function $a(a,b){let c=Object.getOwnPropertyDescriptors(a.__proto__);
for(let d in b)null==b[d]?a.removeAttribute(d):"style"===d?a.style.cssText=b[d]:"__value"===d?a.value=a[d]=b[d]:c[d]&&c[d].set?a[d]=b[d]:u(a,d,b[d])}function U(a,b,c){a.classList[c?"add":"remove"](b)}function la(){if(!V)throw Error("Function called outside component initialization");return V}function wa(a){ma.push(a)}function ab(){if(!xa){xa=!0;do{for(var a=0;a<ia.length;a+=1){var b=ia[a];V=b;b=b.$$;if(null!==b.fragment){b.update();b.before_update.forEach(T);let a=b.dirty;b.dirty=[-1];b.fragment&&
b.fragment.p(b.ctx,a);b.after_update.forEach(wa)}}for(ia.length=0;W.length;)W.pop()();for(a=0;a<ma.length;a+=1)b=ma[a],ya.has(b)||(ya.add(b),b());ma.length=0}while(ia.length);for(;bb.length;)bb.pop()();xa=za=!1;ya.clear()}}function M(){N={r:0,c:[],p:N}}function O(){N.r||N.c.forEach(T);N=N.p}function n(a,b){a&&a.i&&(na.delete(a),a.i(b))}function v(a,b,c,d){a&&a.o&&!na.has(a)&&(na.add(a),N.c.push(()=>{na.delete(a);d&&(c&&a.d(1),d())}),a.o(b))}function P(a){a&&a.c()}function K(a,b,c){let {fragment:d,
on_mount:e,on_destroy:f,after_update:h}=a.$$;d&&d.m(b,c);wa(()=>{let b=e.map(T).filter(Ya);f?f.push(...b):b.forEach(T);a.$$.on_mount=[]});h.forEach(wa)}function L(a,b){a=a.$$;null!==a.fragment&&(a.on_destroy.forEach(T),a.fragment&&a.fragment.d(b),a.on_destroy=a.fragment=null,a.ctx=[])}function H(a,b,c,d,e,f,h=[-1]){let k=V;V=a;let m=b.props||{},g=a.$$={fragment:null,ctx:null,props:f,update:y,not_equal:e,bound:Object.create(null),on_mount:[],on_destroy:[],before_update:[],after_update:[],context:new Map(k?
k.$$.context:[]),callbacks:Object.create(null),dirty:h},l=!1;g.ctx=c?c(a,m,(b,c,...d)=>{d=d.length?d[0]:c;if(g.ctx&&e(g.ctx[b],g.ctx[b]=d)){if(g.bound[b])g.bound[b](d);l&&(-1===a.$$.dirty[0]&&(ia.push(a),za||(za=!0,Jb.then(ab)),a.$$.dirty.fill(0)),a.$$.dirty[b/31|0]|=1<<b%31)}return c}):[];g.update();l=!0;g.before_update.forEach(T);g.fragment=d?d(g.ctx):!1;b.target&&(b.hydrate?(c=Array.from(b.target.childNodes),g.fragment&&g.fragment.l(c),c.forEach(z)):g.fragment&&g.fragment.c(),b.intro&&n(a.$$.fragment),
K(a,b.target,b.anchor),ab());V=k}function Kb(a){let b,c,d,e;return{c(){b=document.createElement("button");u(b,"aria-label",c=a[4]?a[4]:null);u(b,"class",d=`${a[1]||""} shepherd-button ${a[2]?"shepherd-button-secondary":""}`);b.disabled=a[5];u(b,"tabindex","0")},m(c,d,k){c.insertBefore(b,d||null);b.innerHTML=a[3];k&&e();e=ka(b,"click",function(){Ya(a[0])&&a[0].apply(this,arguments)})},p(e,[h]){a=e;h&8&&(b.innerHTML=a[3]);h&16&&c!==(c=a[4]?a[4]:null)&&u(b,"aria-label",c);h&6&&d!==(d=`${a[1]||""} shepherd-button ${a[2]?
"shepherd-button-secondary":""}`)&&u(b,"class",d);h&32&&(b.disabled=a[5])},i:y,o:y,d(a){a&&z(b);e()}}}function Lb(a,b,c){let {config:d}=b,{step:e}=b,f,h,k,m,g,l;a.$set=a=>{"config"in a&&c(6,d=a.config);"step"in a&&c(7,e=a.step)};a.$$.update=()=>{if(a.$$.dirty&192){c(0,f=d.action?d.action.bind(e.tour):null);c(1,h=d.classes);c(2,k=d.secondary);c(3,m=d.text);c(4,g=d.label);if(d.disabled){var b=d.disabled;b=S(b)?b.call(e):b}else b=!1;c(5,l=b)}};return[f,h,k,m,g,l,d,e]}function cb(a,b,c){a=a.slice();a[2]=
b[c];return a}function db(a){let b,c,d=a[1],e=[];for(let b=0;b<d.length;b+=1)e[b]=eb(cb(a,d,b));let f=a=>v(e[a],1,1,()=>{e[a]=null});return{c(){for(let a=0;a<e.length;a+=1)e[a].c();b=document.createTextNode("")},m(a,d){for(let b=0;b<e.length;b+=1)e[b].m(a,d);a.insertBefore(b,d||null);c=!0},p(a,c){if(c&3){d=a[1];let h;for(h=0;h<d.length;h+=1){let f=cb(a,d,h);e[h]?(e[h].p(f,c),n(e[h],1)):(e[h]=eb(f),e[h].c(),n(e[h],1),e[h].m(b.parentNode,b))}M();for(h=d.length;h<e.length;h+=1)f(h);O()}},i(a){if(!c){for(a=
0;a<d.length;a+=1)n(e[a]);c=!0}},o(a){e=e.filter(Boolean);for(a=0;a<e.length;a+=1)v(e[a]);c=!1},d(a){var c=e;for(let b=0;b<c.length;b+=1)c[b]&&c[b].d(a);a&&z(b)}}}function eb(a){let b,c=new Mb({props:{config:a[2],step:a[0]}});return{c(){P(c.$$.fragment)},m(a,e){K(c,a,e);b=!0},p(a,b){let d={};b&2&&(d.config=a[2]);b&1&&(d.step=a[0]);c.$set(d)},i(a){b||(n(c.$$.fragment,a),b=!0)},o(a){v(c.$$.fragment,a);b=!1},d(a){L(c,a)}}}function Nb(a){let b,c,d=a[1]&&db(a);return{c(){b=document.createElement("footer");
d&&d.c();u(b,"class","shepherd-footer")},m(a,f){a.insertBefore(b,f||null);d&&d.m(b,null);c=!0},p(a,[c]){a[1]?d?(d.p(a,c),c&2&&n(d,1)):(d=db(a),d.c(),n(d,1),d.m(b,null)):d&&(M(),v(d,1,1,()=>{d=null}),O())},i(a){c||(n(d),c=!0)},o(a){v(d);c=!1},d(a){a&&z(b);d&&d.d()}}}function Ob(a,b,c){let {step:d}=b;a.$set=a=>{"step"in a&&c(0,d=a.step)};let e;a.$$.update=()=>{a.$$.dirty&1&&c(1,e=d.options.buttons)};return[d,e]}function Pb(a){let b,c,d,e;return{c(){b=document.createElement("button");c=document.createElement("span");
c.textContent="\u00d7";u(c,"aria-hidden","true");u(b,"aria-label",d=a[0].label?a[0].label:"Close Tour");u(b,"class","shepherd-cancel-icon");u(b,"type","button")},m(d,h,k){d.insertBefore(b,h||null);b.appendChild(c);k&&e();e=ka(b,"click",a[1])},p(a,[c]){c&1&&d!==(d=a[0].label?a[0].label:"Close Tour")&&u(b,"aria-label",d)},i:y,o:y,d(a){a&&z(b);e()}}}function Qb(a,b,c){let {cancelIcon:d}=b,{step:e}=b;a.$set=a=>{"cancelIcon"in a&&c(0,d=a.cancelIcon);"step"in a&&c(2,e=a.step)};return[d,a=>{a.preventDefault();
e.cancel()},e]}function Rb(a){let b;return{c(){b=document.createElement("h3");u(b,"id",a[1]);u(b,"class","shepherd-title")},m(c,d){c.insertBefore(b,d||null);a[3](b)},p(a,[d]){d&2&&u(b,"id",a[1])},i:y,o:y,d(c){c&&z(b);a[3](null)}}}function Sb(a,b,c){let {labelId:d}=b,{element:e}=b,{title:f}=b;la().$$.after_update.push(()=>{S(f)&&c(2,f=f());c(0,e.innerHTML=f,e)});a.$set=a=>{"labelId"in a&&c(1,d=a.labelId);"element"in a&&c(0,e=a.element);"title"in a&&c(2,f=a.title)};return[e,d,f,function(a){W[a?"unshift":
"push"](()=>{c(0,e=a)})}]}function fb(a){let b,c=new Tb({props:{labelId:a[0],title:a[2]}});return{c(){P(c.$$.fragment)},m(a,e){K(c,a,e);b=!0},p(a,b){let d={};b&1&&(d.labelId=a[0]);b&4&&(d.title=a[2]);c.$set(d)},i(a){b||(n(c.$$.fragment,a),b=!0)},o(a){v(c.$$.fragment,a);b=!1},d(a){L(c,a)}}}function gb(a){let b,c=new Ub({props:{cancelIcon:a[3],step:a[1]}});return{c(){P(c.$$.fragment)},m(a,e){K(c,a,e);b=!0},p(a,b){let d={};b&8&&(d.cancelIcon=a[3]);b&2&&(d.step=a[1]);c.$set(d)},i(a){b||(n(c.$$.fragment,
a),b=!0)},o(a){v(c.$$.fragment,a);b=!1},d(a){L(c,a)}}}function Vb(a){let b,c,d,e=a[2]&&fb(a),f=a[3]&&a[3].enabled&&gb(a);return{c(){b=document.createElement("header");e&&e.c();c=document.createTextNode(" ");f&&f.c();u(b,"class","shepherd-header")},m(a,k){a.insertBefore(b,k||null);e&&e.m(b,null);b.appendChild(c);f&&f.m(b,null);d=!0},p(a,[d]){a[2]?e?(e.p(a,d),d&4&&n(e,1)):(e=fb(a),e.c(),n(e,1),e.m(b,c)):e&&(M(),v(e,1,1,()=>{e=null}),O());a[3]&&a[3].enabled?f?(f.p(a,d),d&8&&n(f,1)):(f=gb(a),f.c(),n(f,
1),f.m(b,null)):f&&(M(),v(f,1,1,()=>{f=null}),O())},i(a){d||(n(e),n(f),d=!0)},o(a){v(e);v(f);d=!1},d(a){a&&z(b);e&&e.d();f&&f.d()}}}function Wb(a,b,c){let {labelId:d}=b,{step:e}=b,f,h;a.$set=a=>{"labelId"in a&&c(0,d=a.labelId);"step"in a&&c(1,e=a.step)};a.$$.update=()=>{a.$$.dirty&2&&(c(2,f=e.options.title),c(3,h=e.options.cancelIcon))};return[d,e,f,h]}function Xb(a){let b;return{c(){b=document.createElement("div");u(b,"class","shepherd-text");u(b,"id",a[1])},m(c,d){c.insertBefore(b,d||null);a[3](b)},
p(a,[d]){d&2&&u(b,"id",a[1])},i:y,o:y,d(c){c&&z(b);a[3](null)}}}function Yb(a,b,c){let {descriptionId:d}=b,{element:e}=b,{step:f}=b;la().$$.after_update.push(()=>{let {text:a}=f.options;S(a)&&(a=a.call(f));a instanceof HTMLElement?e.appendChild(a):c(0,e.innerHTML=a,e)});a.$set=a=>{"descriptionId"in a&&c(1,d=a.descriptionId);"element"in a&&c(0,e=a.element);"step"in a&&c(2,f=a.step)};return[e,d,f,function(a){W[a?"unshift":"push"](()=>{c(0,e=a)})}]}function hb(a){let b,c=new Zb({props:{labelId:a[1],
step:a[2]}});return{c(){P(c.$$.fragment)},m(a,e){K(c,a,e);b=!0},p(a,b){let d={};b&2&&(d.labelId=a[1]);b&4&&(d.step=a[2]);c.$set(d)},i(a){b||(n(c.$$.fragment,a),b=!0)},o(a){v(c.$$.fragment,a);b=!1},d(a){L(c,a)}}}function ib(a){let b,c=new $b({props:{descriptionId:a[0],step:a[2]}});return{c(){P(c.$$.fragment)},m(a,e){K(c,a,e);b=!0},p(a,b){let d={};b&1&&(d.descriptionId=a[0]);b&4&&(d.step=a[2]);c.$set(d)},i(a){b||(n(c.$$.fragment,a),b=!0)},o(a){v(c.$$.fragment,a);b=!1},d(a){L(c,a)}}}function jb(a){let b,
c=new ac({props:{step:a[2]}});return{c(){P(c.$$.fragment)},m(a,e){K(c,a,e);b=!0},p(a,b){let d={};b&4&&(d.step=a[2]);c.$set(d)},i(a){b||(n(c.$$.fragment,a),b=!0)},o(a){v(c.$$.fragment,a);b=!1},d(a){L(c,a)}}}function bc(a){let b,c=void 0!==a[2].options.title||a[2].options.cancelIcon&&a[2].options.cancelIcon.enabled,d,e=void 0!==a[2].options.text,f,h=Array.isArray(a[2].options.buttons)&&a[2].options.buttons.length,k,m=c&&hb(a),g=e&&ib(a),l=h&&jb(a);return{c(){b=document.createElement("div");m&&m.c();
d=document.createTextNode(" ");g&&g.c();f=document.createTextNode(" ");l&&l.c();u(b,"class","shepherd-content")},m(a,c){a.insertBefore(b,c||null);m&&m.m(b,null);b.appendChild(d);g&&g.m(b,null);b.appendChild(f);l&&l.m(b,null);k=!0},p(a,[k]){k&4&&(c=void 0!==a[2].options.title||a[2].options.cancelIcon&&a[2].options.cancelIcon.enabled);c?m?(m.p(a,k),k&4&&n(m,1)):(m=hb(a),m.c(),n(m,1),m.m(b,d)):m&&(M(),v(m,1,1,()=>{m=null}),O());k&4&&(e=void 0!==a[2].options.text);e?g?(g.p(a,k),k&4&&n(g,1)):(g=ib(a),
g.c(),n(g,1),g.m(b,f)):g&&(M(),v(g,1,1,()=>{g=null}),O());k&4&&(h=Array.isArray(a[2].options.buttons)&&a[2].options.buttons.length);h?l?(l.p(a,k),k&4&&n(l,1)):(l=jb(a),l.c(),n(l,1),l.m(b,null)):l&&(M(),v(l,1,1,()=>{l=null}),O())},i(a){k||(n(m),n(g),n(l),k=!0)},o(a){v(m);v(g);v(l);k=!1},d(a){a&&z(b);m&&m.d();g&&g.d();l&&l.d()}}}function cc(a,b,c){let {descriptionId:d}=b,{labelId:e}=b,{step:f}=b;a.$set=a=>{"descriptionId"in a&&c(0,d=a.descriptionId);"labelId"in a&&c(1,e=a.labelId);"step"in a&&c(2,f=
a.step)};return[d,e,f]}function kb(a){let b;return{c(){b=document.createElement("div");u(b,"class","shepherd-arrow");u(b,"data-popper-arrow","")},m(a,d){a.insertBefore(b,d||null)},d(a){a&&z(b)}}}function dc(a){let b,c,d,e,f=a[4].options.arrow&&a[4].options.attachTo&&a[4].options.attachTo.element&&a[4].options.attachTo.on&&kb(),h=new ec({props:{descriptionId:a[2],labelId:a[3],step:a[4]}}),k=[{"aria-describedby":void 0!==a[4].options.text?a[2]:null},{"aria-labelledby":a[4].options.title?a[3]:null},
a[1],{role:"dialog"},{tabindex:"0"}],m={};for(let a=0;a<k.length;a+=1)m=Ib(m,k[a]);return{c(){b=document.createElement("div");f&&f.c();c=document.createTextNode(" ");P(h.$$.fragment);$a(b,m);U(b,"shepherd-has-cancel-icon",a[5]);U(b,"shepherd-has-title",a[6]);U(b,"shepherd-element",!0)},m(g,k,m){g.insertBefore(b,k||null);f&&f.m(b,null);b.appendChild(c);K(h,b,null);a[17](b);d=!0;m&&e();e=ka(b,"keydown",a[7])},p(a,[d]){a[4].options.arrow&&a[4].options.attachTo&&a[4].options.attachTo.element&&a[4].options.attachTo.on?
f||(f=kb(),f.c(),f.m(b,c)):f&&(f.d(1),f=null);var e={};d&4&&(e.descriptionId=a[2]);d&8&&(e.labelId=a[3]);d&16&&(e.step=a[4]);h.$set(e);e=b;{d=[d&20&&{"aria-describedby":void 0!==a[4].options.text?a[2]:null},d&24&&{"aria-labelledby":a[4].options.title?a[3]:null},d&2&&a[1],{role:"dialog"},{tabindex:"0"}];let b={},c={},e={$$scope:1},f=k.length;for(;f--;){let a=k[f],r=d[f];if(r){for(g in a)g in r||(c[g]=1);for(let a in r)e[a]||(b[a]=r[a],e[a]=1);k[f]=r}else for(let b in a)e[b]=1}for(let a in c)a in b||
(b[a]=void 0);var g=b}$a(e,g);U(b,"shepherd-has-cancel-icon",a[5]);U(b,"shepherd-has-title",a[6]);U(b,"shepherd-element",!0)},i(a){d||(n(h.$$.fragment,a),d=!0)},o(a){v(h.$$.fragment,a);d=!1},d(c){c&&z(b);f&&f.d();L(h);a[17](null);e()}}}function lb(a){return a.split(" ").filter(a=>!!a.length)}function fc(a,b,c){function d(){e(w);w=p.options.classes;f(w)}function e(a){Z(a)&&(a=lb(a),a.length&&k.classList.remove(...a))}function f(a){Z(a)&&(a=lb(a),a.length&&k.classList.add(...a))}let {classPrefix:h}=
b,{element:k}=b,{descriptionId:m}=b,{firstFocusableElement:g}=b,{focusableElements:l}=b,{labelId:q}=b,{lastFocusableElement:t}=b,{step:p}=b,{dataStepId:B}=b,r,A,w;la().$$.on_mount.push(()=>{c(1,B={[`data-${h}shepherd-step-id`]:p.id});c(9,l=k.querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [tabindex="0"]'));c(8,g=l[0]);c(10,t=l[l.length-1])});la().$$.after_update.push(()=>{w!==p.options.classes&&d()});a.$set=a=>
{"classPrefix"in a&&c(11,h=a.classPrefix);"element"in a&&c(0,k=a.element);"descriptionId"in a&&c(2,m=a.descriptionId);"firstFocusableElement"in a&&c(8,g=a.firstFocusableElement);"focusableElements"in a&&c(9,l=a.focusableElements);"labelId"in a&&c(3,q=a.labelId);"lastFocusableElement"in a&&c(10,t=a.lastFocusableElement);"step"in a&&c(4,p=a.step);"dataStepId"in a&&c(1,B=a.dataStepId)};a.$$.update=()=>{a.$$.dirty&16&&(c(5,r=p.options&&p.options.cancelIcon&&p.options.cancelIcon.enabled),c(6,A=p.options&&
p.options.title))};return[k,B,m,q,p,r,A,a=>{const {tour:b}=p;switch(a.keyCode){case 9:if(0===l.length){a.preventDefault();break}a.shiftKey?document.activeElement===g&&(a.preventDefault(),t.focus()):document.activeElement===t&&(a.preventDefault(),g.focus());break;case 27:b.options.exitOnEsc&&p.cancel();break;case 37:b.options.keyboardNavigation&&b.back();break;case 39:b.options.keyboardNavigation&&b.next()}},g,l,t,h,()=>k,w,d,e,f,function(a){W[a?"unshift":"push"](()=>{c(0,k=a)})}]}function gc(a){a&&
({steps:a}=a,a.forEach(a=>{a.options&&!1===a.options.canClickTarget&&a.options.attachTo&&a.target instanceof HTMLElement&&a.target.classList.remove("shepherd-target-click-disabled")}))}function hc({width:a,height:b,x:c=0,y:d=0,r:e=0}){let {innerWidth:f,innerHeight:h}=window;return`M${f},${h}\
H0\
V0\
H${f}\
V${h}\
Z\
M${c+e},${d}\
a${e},${e},0,0,0-${e},${e}\
V${b+d-e}\
a${e},${e},0,0,0,${e},${e}\
H${a+c-e}\
a${e},${e},0,0,0,${e}-${e}\
V${d+e}\
a${e},${e},0,0,0-${e}-${e}\
Z`}function ic(a){let b,c,d,e;return{c(){b=Za("svg");c=Za("path");u(c,"d",a[2]);u(b,"class",d=`${a[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)},m(d,h,k){d.insertBefore(b,h||null);b.appendChild(c);a[17](b);k&&e();e=ka(b,"touchmove",a[3])},p(a,[e]){e&4&&u(c,"d",a[2]);e&2&&d!==(d=`${a[1]?"shepherd-modal-is-visible":""} shepherd-modal-overlay-container`)&&u(b,"class",d)},i:y,o:y,d(c){c&&z(b);a[17](null);e()}}}function mb(a){if(!a)return null;let b=a instanceof HTMLElement&&window.getComputedStyle(a).overflowY;
return"hidden"!==b&&"visible"!==b&&a.scrollHeight>=a.clientHeight?a:mb(a.parentElement)}function jc(a,b,c){function d(){c(4,q={width:0,height:0,x:0,y:0,r:0})}function e(){c(1,t=!1);m()}function f(a,b,d=0,e=0){if(a.getBoundingClientRect){var f=a.getBoundingClientRect();var g=f.y||f.top;f=f.bottom||g+f.height;if(b){var r=b.getBoundingClientRect();b=r.y||r.top;r=r.bottom||b+r.height;g=Math.max(g,b);f=Math.min(f,r)}g={y:g,height:Math.max(f-g,0)};let {y:h,height:k}=g,{x:l,width:m,left:p}=a.getBoundingClientRect();
c(4,q={width:m+2*d,height:k+2*d,x:(l||p)-d,y:h-d,r:e})}}function h(){c(1,t=!0)}function k(){window.addEventListener("touchmove",r,{passive:!1})}function m(){p&&(cancelAnimationFrame(p),p=void 0);window.removeEventListener("touchmove",r,{passive:!1})}function g(a){let {modalOverlayOpeningPadding:b,modalOverlayOpeningRadius:c}=a.options;if(a.target){let d=mb(a.target),e=()=>{p=void 0;f(a.target,d,b,c);p=requestAnimationFrame(e)};e();k()}else d()}let {element:l}=b,{openingProperties:q}=b;b=va();let t=
!1,p=void 0,B;d();let r=a=>{a.preventDefault()};a.$set=a=>{"element"in a&&c(0,l=a.element);"openingProperties"in a&&c(4,q=a.openingProperties)};a.$$.update=()=>{a.$$.dirty&16&&c(2,B=hc(q))};return[l,t,B,a=>{a.stopPropagation()},q,()=>l,d,e,f,function(a){m();a.tour.options.useModalOverlay?(g(a),h()):e()},h,p,b,r,k,m,g,function(a){W[a?"unshift":"push"](()=>{c(0,l=a)})}]}var qb=function(a){var b;if(b=!!a&&"object"===typeof a)b=Object.prototype.toString.call(a),b=!("[object RegExp]"===b||"[object Date]"===
b||a.$$typeof===kc);return b},kc="function"===typeof Symbol&&Symbol.for?Symbol.for("react.element"):60103;R.all=function(a,b){if(!Array.isArray(a))throw Error("first argument should be an array");return a.reduce(function(a,d){return R(a,d,b)},{})};var lc=R;class Aa{on(a,b,c,d=!1){void 0===this.bindings&&(this.bindings={});void 0===this.bindings[a]&&(this.bindings[a]=[]);this.bindings[a].push({handler:b,ctx:c,once:d});return this}once(a,b,c){return this.on(a,b,c,!0)}off(a,b){if(void 0===this.bindings||
void 0===this.bindings[a])return this;void 0===b?delete this.bindings[a]:this.bindings[a].forEach((c,d)=>{c.handler===b&&this.bindings[a].splice(d,1)});return this}trigger(a,...b){void 0!==this.bindings&&this.bindings[a]&&this.bindings[a].forEach((c,d)=>{let {ctx:e,handler:f,once:h}=c;f.apply(e||this,b);h&&this.bindings[a].splice(d,1)});return this}}var ha=["top","bottom","right","left"],Ta=ha.reduce(function(a,b){return a.concat([b+"-start",b+"-end"])},[]),Sa=[].concat(ha,["auto"]).reduce(function(a,
b){return a.concat([b,b+"-start",b+"-end"])},[]),vb="beforeRead read afterRead beforeMain main afterMain beforeWrite write afterWrite".split(" "),nb={placement:"bottom",modifiers:[],strategy:"absolute"},oa={passive:!0},yb={top:"auto",right:"auto",bottom:"auto",left:"auto"},zb={left:"right",right:"left",bottom:"top",top:"bottom"},Ab={start:"end",end:"start"},mc=function(a){void 0===a&&(a={});var b=a.defaultModifiers,c=void 0===b?[]:b;a=a.defaultOptions;var d=void 0===a?nb:a;return function(a,b,h){function e(){g.orderedModifiers.forEach(function(a){var b=
a.name,c=a.options;c=void 0===c?{}:c;a=a.effect;"function"===typeof a&&(b=a({state:g,name:b,instance:t,options:c}),l.push(b||function(){}))})}function f(){l.forEach(function(a){return a()});l=[]}void 0===h&&(h=d);var g={placement:"bottom",orderedModifiers:[],options:Object.assign({},nb,{},d),modifiersData:{},elements:{reference:a,popper:b},attributes:{},styles:{}},l=[],q=!1,t={state:g,setOptions:function(h){f();g.options=Object.assign({},d,{},g.options,{},h);g.scrollParents={reference:ba(a)?da(a):
a.contextElement?da(a.contextElement):[],popper:da(b)};h=ub(xb([].concat(c,g.options.modifiers)));g.orderedModifiers=h.filter(function(a){return a.enabled});e();return t.update()},forceUpdate:function(){if(!q){var a=g.elements,b=a.reference;a=a.popper;if(Ka(b,a))for(g.rects={reference:Ga(b,ea(a),"fixed"===g.options.strategy),popper:ra(a)},g.reset=!1,g.placement=g.options.placement,g.orderedModifiers.forEach(function(a){return g.modifiersData[a.name]=Object.assign({},a.data)}),b=0;b<g.orderedModifiers.length;b++)if(!0===
g.reset)g.reset=!1,b=-1;else{var c=g.orderedModifiers[b];a=c.fn;var d=c.options;d=void 0===d?{}:d;c=c.name;"function"===typeof a&&(g=a({state:g,options:d,name:c,instance:t})||g)}}},update:wb(function(){return new Promise(function(a){t.forceUpdate();a(g)})}),destroy:function(){f();q=!0}};if(!Ka(a,b))return t;t.setOptions(h).then(function(a){if(!q&&h.onFirstUpdate)h.onFirstUpdate(a)});return t}}({defaultModifiers:[{name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(a){var b=
a.state,c=a.instance;a=a.options;var d=a.scroll,e=void 0===d?!0:d;a=a.resize;var f=void 0===a?!0:a,h=x(b.elements.popper),k=[].concat(b.scrollParents.reference,b.scrollParents.popper);e&&k.forEach(function(a){a.addEventListener("scroll",c.update,oa)});f&&h.addEventListener("resize",c.update,oa);return function(){e&&k.forEach(function(a){a.removeEventListener("scroll",c.update,oa)});f&&h.removeEventListener("resize",c.update,oa)}},data:{}},{name:"popperOffsets",enabled:!0,phase:"read",fn:function(a){var b=
a.state;b.modifiersData[a.name]=La({reference:b.rects.reference,element:b.rects.popper,strategy:"absolute",placement:b.placement})},data:{}},{name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(a){var b=a.state,c=a.options;a=c.gpuAcceleration;a=void 0===a?!0:a;c=c.adaptive;c=void 0===c?!0:c;a={placement:D(b.placement),popper:b.elements.popper,popperRect:b.rects.popper,gpuAcceleration:a};null!=b.modifiersData.popperOffsets&&(b.styles.popper=Object.assign({},b.styles.popper,{},Ma(Object.assign({},
a,{offsets:b.modifiersData.popperOffsets,position:b.options.strategy,adaptive:c}))));null!=b.modifiersData.arrow&&(b.styles.arrow=Object.assign({},b.styles.arrow,{},Ma(Object.assign({},a,{offsets:b.modifiersData.arrow,position:"absolute",adaptive:!1}))));b.attributes.popper=Object.assign({},b.attributes.popper,{"data-popper-placement":b.placement})},data:{}},{name:"applyStyles",enabled:!0,phase:"write",fn:function(a){var b=a.state;Object.keys(b.elements).forEach(function(a){var c=b.styles[a]||{},
e=b.attributes[a]||{},f=b.elements[a];C(f)&&F(f)&&(Object.assign(f.style,c),Object.keys(e).forEach(function(a){var b=e[a];!1===b?f.removeAttribute(a):f.setAttribute(a,!0===b?"":b)}))})},effect:function(a){var b=a.state,c={popper:{position:b.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};Object.assign(b.elements.popper.style,c.popper);b.elements.arrow&&Object.assign(b.elements.arrow.style,c.arrow);return function(){Object.keys(b.elements).forEach(function(a){var d=
b.elements[a],f=b.attributes[a]||{};a=Object.keys(b.styles.hasOwnProperty(a)?b.styles[a]:c[a]).reduce(function(a,b){a[b]="";return a},{});C(d)&&F(d)&&(Object.assign(d.style,a),Object.keys(f).forEach(function(a){d.removeAttribute(a)}))})}},requires:["computeStyles"]},{name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(a){var b=a.state,c=a.name;a=a.options.offset;var d=void 0===a?[0,0]:a;a=Sa.reduce(function(a,c){var e=b.rects;var f=D(c);var h=0<=["left","top"].indexOf(f)?
-1:1,k="function"===typeof d?d(Object.assign({},e,{placement:c})):d;e=k[0];k=k[1];e=e||0;k=(k||0)*h;f=0<=["left","right"].indexOf(f)?{x:k,y:e}:{x:e,y:k};a[c]=f;return a},{});var e=a[b.placement],f=e.x;e=e.y;null!=b.modifiersData.popperOffsets&&(b.modifiersData.popperOffsets.x+=f,b.modifiersData.popperOffsets.y+=e);b.modifiersData[c]=a}},{name:"flip",enabled:!0,phase:"main",fn:function(a){var b=a.state,c=a.options;a=a.name;if(!b.modifiersData[a]._skip){var d=c.mainAxis;d=void 0===d?!0:d;var e=c.altAxis;
e=void 0===e?!0:e;var f=c.fallbackPlacements,h=c.padding,k=c.boundary,m=c.rootBoundary,g=c.altBoundary,l=c.flipVariations,q=void 0===l?!0:l,t=c.allowedAutoPlacements;c=b.options.placement;l=D(c);f=f||(l!==c&&q?Eb(c):[ja(c)]);var p=[c].concat(f).reduce(function(a,c){return a.concat("auto"===D(c)?Db(b,{placement:c,boundary:k,rootBoundary:m,padding:h,flipVariations:q,allowedAutoPlacements:t}):c)},[]);c=b.rects.reference;f=b.rects.popper;var n=new Map;l=!0;for(var r=p[0],A=0;A<p.length;A++){var w=p[A],
u=D(w),v="start"===w.split("-")[1],Q=0<=["top","bottom"].indexOf(u),x=Q?"width":"height",y=fa(b,{placement:w,boundary:k,rootBoundary:m,altBoundary:g,padding:h});v=Q?v?"right":"left":v?"bottom":"top";c[x]>f[x]&&(v=ja(v));x=ja(v);Q=[];d&&Q.push(0>=y[u]);e&&Q.push(0>=y[v],0>=y[x]);if(Q.every(function(a){return a})){r=w;l=!1;break}n.set(w,Q)}if(l)for(d=function(a){var b=p.find(function(b){if(b=n.get(b))return b.slice(0,a).every(function(a){return a})});if(b)return r=b,"break"},e=q?3:1;0<e&&"break"!==
d(e);e--);b.placement!==r&&(b.modifiersData[a]._skip=!0,b.placement=r,b.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}},{name:"preventOverflow",enabled:!0,phase:"main",fn:function(a){var b=a.state,c=a.options;a=a.name;var d=c.mainAxis,e=void 0===d?!0:d;d=c.altAxis;d=void 0===d?!1:d;var f=c.tether;f=void 0===f?!0:f;var h=c.tetherOffset,k=void 0===h?0:h;c=fa(b,{boundary:c.boundary,rootBoundary:c.rootBoundary,padding:c.padding,altBoundary:c.altBoundary});h=D(b.placement);var m=b.placement.split("-")[1],
g=!m,l=sa(h);h="x"===l?"y":"x";var q=b.modifiersData.popperOffsets,t=b.rects.reference,p=b.rects.popper,n="function"===typeof k?k(Object.assign({},b.rects,{placement:b.placement})):k;k={x:0,y:0};if(q){if(e){var r="y"===l?"top":"left",A="y"===l?"bottom":"right",w="y"===l?"height":"width";e=q[l];var u=q[l]+c[r],v=q[l]-c[A],x=f?-p[w]/2:0,y="start"===m?t[w]:p[w];m="start"===m?-p[w]:-t[w];p=b.elements.arrow;p=f&&p?ra(p):{width:0,height:0};var z=b.modifiersData["arrow#persistent"]?b.modifiersData["arrow#persistent"].padding:
{top:0,right:0,bottom:0,left:0};r=z[r];A=z[A];p=Math.max(0,Math.min(t[w],p[w]));y=g?t[w]/2-x-p-r-n:y-p-r-n;g=g?-t[w]/2+x+p+A+n:m+p+A+n;n=b.elements.arrow&&ea(b.elements.arrow);t=b.modifiersData.offset?b.modifiersData.offset[b.placement][l]:0;n=q[l]+y-t-(n?"y"===l?n.clientTop||0:n.clientLeft||0:0);g=q[l]+g-t;f=Math.max(f?Math.min(u,n):u,Math.min(e,f?Math.max(v,g):v));q[l]=f;k[l]=f-e}d&&(d=q[h],f=Math.max(d+c["x"===l?"top":"left"],Math.min(d,d-c["x"===l?"bottom":"right"])),q[h]=f,k[h]=f-d);b.modifiersData[a]=
k}},requiresIfExists:["offset"]},{name:"arrow",enabled:!0,phase:"main",fn:function(a){var b,c=a.state;a=a.name;var d=c.elements.arrow,e=c.modifiersData.popperOffsets,f=D(c.placement),h=sa(f);f=0<=["left","right"].indexOf(f)?"height":"width";if(d&&e){var k=c.modifiersData[a+"#persistent"].padding,m=ra(d),g="y"===h?"top":"left",l="y"===h?"bottom":"right",q=c.rects.reference[f]+c.rects.reference[h]-e[h]-c.rects.popper[f];e=e[h]-c.rects.reference[h];d=(d=ea(d))?"y"===h?d.clientHeight||0:d.clientWidth||
0:0;q=d/2-m[f]/2+(q/2-e/2);f=Math.max(k[g],Math.min(q,d-m[f]-k[l]));c.modifiersData[a]=(b={},b[h]=f,b.centerOffset=f-q,b)}},effect:function(a){var b=a.state,c=a.options;a=a.name;var d=c.element;d=void 0===d?"[data-popper-arrow]":d;c=c.padding;c=void 0===c?0:c;if(null!=d){if("string"===typeof d&&(d=b.elements.popper.querySelector(d),!d))return;Oa(b.elements.popper,d)&&(b.elements.arrow=d,b.modifiersData[a+"#persistent"]={padding:Qa("number"!==typeof c?c:Ra(c,ha))})}},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},
{name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(a){var b=a.state;a=a.name;var c=b.rects.reference,d=b.rects.popper,e=b.modifiersData.preventOverflow,f=fa(b,{elementContext:"reference"}),h=fa(b,{altBoundary:!0});c=Ua(f,c);d=Ua(h,d,e);e=Va(c);h=Va(d);b.modifiersData[a]={referenceClippingOffsets:c,popperEscapeOffsets:d,isReferenceHidden:e,hasPopperEscaped:h};b.attributes.popper=Object.assign({},b.attributes.popper,{"data-popper-reference-hidden":e,"data-popper-escaped":h})}}]});
let V,ia=[],W=[],ma=[],bb=[],Jb=Promise.resolve(),za=!1,xa=!1,ya=new Set,na=new Set,N;class I{$destroy(){L(this,1);this.$destroy=y}$on(a,b){let c=this.$$.callbacks[a]||(this.$$.callbacks[a]=[]);c.push(b);return()=>{let a=c.indexOf(b);-1!==a&&c.splice(a,1)}}$set(){}}class Mb extends I{constructor(a){super();H(this,a,Lb,Kb,G,{config:6,step:7})}}class ac extends I{constructor(a){super();H(this,a,Ob,Nb,G,{step:0})}}class Ub extends I{constructor(a){super();H(this,a,Qb,Pb,G,{cancelIcon:0,step:2})}}class Tb extends I{constructor(a){super();
H(this,a,Sb,Rb,G,{labelId:1,element:0,title:2})}}class Zb extends I{constructor(a){super();H(this,a,Wb,Vb,G,{labelId:0,step:1})}}class $b extends I{constructor(a){super();H(this,a,Yb,Xb,G,{descriptionId:1,element:0,step:2})}}class ec extends I{constructor(a){super();H(this,a,cc,bc,G,{descriptionId:0,labelId:1,step:2})}}class nc extends I{constructor(a){super();H(this,a,fc,dc,G,{classPrefix:11,element:0,descriptionId:2,firstFocusableElement:8,focusableElements:9,labelId:3,lastFocusableElement:10,step:4,
dataStepId:1,getElement:12})}get getElement(){return this.$$.ctx[12]}}(function(a,b){return b={exports:{}},a(b,b.exports),b.exports})(function(a,b){(function(){a.exports={polyfill:function(){function a(a,b){this.scrollLeft=a;this.scrollTop=b}function b(a){if(null===a||"object"!==typeof a||void 0===a.behavior||"auto"===a.behavior||"instant"===a.behavior)return!0;if("object"===typeof a&&"smooth"===a.behavior)return!1;throw new TypeError("behavior member of ScrollOptions "+a.behavior+" is not a valid value for enumeration ScrollBehavior.");
}function e(a,b){if("Y"===b)return a.clientHeight+u<a.scrollHeight;if("X"===b)return a.clientWidth+u<a.scrollWidth}function f(a,b){a=g.getComputedStyle(a,null)["overflow"+b];return"auto"===a||"scroll"===a}function h(a){var b=e(a,"Y")&&f(a,"Y");a=e(a,"X")&&f(a,"X");return b||a}function k(a){var b=(p()-a.startTime)/468;var c=.5*(1-Math.cos(Math.PI*(1<b?1:b)));b=a.startX+(a.x-a.startX)*c;c=a.startY+(a.y-a.startY)*c;a.method.call(a.scrollable,b,c);b===a.x&&c===a.y||g.requestAnimationFrame(k.bind(g,a))}
function m(b,c,d){var e=p();if(b===l.body){var f=g;var h=g.scrollX||g.pageXOffset;b=g.scrollY||g.pageYOffset;var r=n.scroll}else f=b,h=b.scrollLeft,b=b.scrollTop,r=a;k({scrollable:f,method:r,startTime:e,startX:h,startY:b,x:c,y:d})}var g=window,l=document;if(!("scrollBehavior"in l.documentElement.style&&!0!==g.__forceSmoothScrollPolyfill__)){var q=g.HTMLElement||g.Element,n={scroll:g.scroll||g.scrollTo,scrollBy:g.scrollBy,elementScroll:q.prototype.scroll||a,scrollIntoView:q.prototype.scrollIntoView},
p=g.performance&&g.performance.now?g.performance.now.bind(g.performance):Date.now,u=/MSIE |Trident\/|Edge\//.test(g.navigator.userAgent)?1:0;g.scroll=g.scrollTo=function(a,c){void 0!==a&&(!0===b(a)?n.scroll.call(g,void 0!==a.left?a.left:"object"!==typeof a?a:g.scrollX||g.pageXOffset,void 0!==a.top?a.top:void 0!==c?c:g.scrollY||g.pageYOffset):m.call(g,l.body,void 0!==a.left?~~a.left:g.scrollX||g.pageXOffset,void 0!==a.top?~~a.top:g.scrollY||g.pageYOffset))};g.scrollBy=function(a,c){void 0!==a&&(b(a)?
n.scrollBy.call(g,void 0!==a.left?a.left:"object"!==typeof a?a:0,void 0!==a.top?a.top:void 0!==c?c:0):m.call(g,l.body,~~a.left+(g.scrollX||g.pageXOffset),~~a.top+(g.scrollY||g.pageYOffset)))};q.prototype.scroll=q.prototype.scrollTo=function(a,c){if(void 0!==a)if(!0===b(a)){if("number"===typeof a&&void 0===c)throw new SyntaxError("Value could not be converted");n.elementScroll.call(this,void 0!==a.left?~~a.left:"object"!==typeof a?~~a:this.scrollLeft,void 0!==a.top?~~a.top:void 0!==c?~~c:this.scrollTop)}else c=
a.left,a=a.top,m.call(this,this,"undefined"===typeof c?this.scrollLeft:~~c,"undefined"===typeof a?this.scrollTop:~~a)};q.prototype.scrollBy=function(a,c){void 0!==a&&(!0===b(a)?n.elementScroll.call(this,void 0!==a.left?~~a.left+this.scrollLeft:~~a+this.scrollLeft,void 0!==a.top?~~a.top+this.scrollTop:~~c+this.scrollTop):this.scroll({left:~~a.left+this.scrollLeft,top:~~a.top+this.scrollTop,behavior:a.behavior}))};q.prototype.scrollIntoView=function(a){if(!0===b(a))n.scrollIntoView.call(this,void 0===
a?!0:a);else{for(a=this;a!==l.body&&!1===h(a);)a=a.parentNode||a.host;var c=a.getBoundingClientRect(),d=this.getBoundingClientRect();a!==l.body?(m.call(this,a,a.scrollLeft+d.left-c.left,a.scrollTop+d.top-c.top),"fixed"!==g.getComputedStyle(a).position&&g.scrollBy({left:c.left,top:c.top,behavior:"smooth"})):g.scrollBy({left:d.left,top:d.top,behavior:"smooth"})}}}}}})()}).polyfill();class Ba extends Aa{constructor(a,b={}){super(a,b);this.tour=a;this.classPrefix=this.tour.options?Wa(this.tour.options.classPrefix):
"";this.styles=a.styles;Ea(this);this._setOptions(b);return this}cancel(){this.tour.cancel();this.trigger("cancel")}complete(){this.tour.complete();this.trigger("complete")}destroy(){this.tooltip&&(this.tooltip.destroy(),this.tooltip=null);this.el instanceof HTMLElement&&this.el.parentNode&&(this.el.parentNode.removeChild(this.el),this.el=null);this.target&&this._updateStepTargetOnHide();this.trigger("destroy")}getTour(){return this.tour}hide(){this.tour.modal.hide();this.trigger("before-hide");this.el&&
(this.el.hidden=!0);this.target&&this._updateStepTargetOnHide();this.trigger("hide")}isCentered(){let a=ua(this);return!a.element||!a.on}isOpen(){return!(!this.el||this.el.hidden)}show(){if(S(this.options.beforeShowPromise)){let a=this.options.beforeShowPromise();if(void 0!==a)return a.then(()=>this._show())}this._show()}updateStepOptions(a){Object.assign(this.options,a);this.shepherdElementComponent&&this.shepherdElementComponent.$set({step:this})}_createTooltipContent(){this.shepherdElementComponent=
new nc({target:document.body,props:{classPrefix:this.classPrefix,descriptionId:`${this.id}-description`,labelId:`${this.id}-label`,step:this,styles:this.styles}});return this.shepherdElementComponent.getElement()}_scrollTo(a){let {element:b}=ua(this);S(this.options.scrollToHandler)?this.options.scrollToHandler(b):b instanceof HTMLElement&&"function"===typeof b.scrollIntoView&&b.scrollIntoView(a)}_getClassOptions(a){var b=this.tour&&this.tour.options&&this.tour.options.defaultStepOptions;b=b&&b.classes?
b.classes:"";a=[...(a.classes?a.classes:"").split(" "),...b.split(" ")];a=new Set(a);return Array.from(a).join(" ").trim()}_setOptions(a={}){let b=this.tour&&this.tour.options&&this.tour.options.defaultStepOptions;b=lc({},b||{});this.options=Object.assign({arrow:!0},b,a);let {when:c}=this.options;this.options.classes=this._getClassOptions(a);this.destroy();this.id=this.options.id||`step-${va()}`;c&&Object.keys(c).forEach(a=>{this.on(a,c[a],this)})}_setupElements(){void 0!==this.el&&this.destroy();
this.el=this._createTooltipContent();this.options.advanceOn&&sb(this);{this.tooltip&&this.tooltip.destroy();let a=ua(this),b=a.element,c=Hb(a,this);this.isCentered()&&(b=document.body,this.shepherdElementComponent.getElement().classList.add("shepherd-centered"));this.tooltip=mc(b,this.el,c);this.target=a.element}}_show(){this.trigger("before-show");this._setupElements();this.tour.modal||this.tour._setupModal();this.tour.modal.setupForStep(this);this._styleTargetElementForStep(this);this.el.hidden=
!1;this.options.scrollTo&&setTimeout(()=>{this._scrollTo(this.options.scrollTo)});this.el.hidden=!1;let a=this.shepherdElementComponent.getElement(),b=this.target||document.body;b.classList.add(`${this.classPrefix}shepherd-enabled`);b.classList.add(`${this.classPrefix}shepherd-target`);a.classList.add("shepherd-enabled");this.trigger("show")}_styleTargetElementForStep(a){let b=a.target;b&&(a.options.highlightClass&&b.classList.add(a.options.highlightClass),!1===a.options.canClickTarget&&b.classList.add("shepherd-target-click-disabled"))}_updateStepTargetOnHide(){this.options.highlightClass&&
this.target.classList.remove(this.options.highlightClass);this.target.classList.remove(`${this.classPrefix}shepherd-enabled`,`${this.classPrefix}shepherd-target`)}}class oc extends I{constructor(a){super();H(this,a,jc,ic,G,{element:0,openingProperties:4,getElement:5,closeModalOpening:6,hide:7,positionModalOpening:8,setupForStep:9,show:10})}get getElement(){return this.$$.ctx[5]}get closeModalOpening(){return this.$$.ctx[6]}get hide(){return this.$$.ctx[7]}get positionModalOpening(){return this.$$.ctx[8]}get setupForStep(){return this.$$.ctx[9]}get show(){return this.$$.ctx[10]}}
let X=new Aa;class pc extends Aa{constructor(a={}){super(a);Ea(this);this.options=Object.assign({},{exitOnEsc:!0,keyboardNavigation:!0},a);this.classPrefix=Wa(this.options.classPrefix);this.steps=[];this.addSteps(this.options.steps);"active cancel complete inactive show start".split(" ").map(a=>{(a=>{this.on(a,b=>{b=b||{};b.tour=this;X.trigger(a,b)})})(a)});this._setTourID();return this}addStep(a,b){a instanceof Ba?a.tour=this:a=new Ba(this,a);void 0!==b?this.steps.splice(b,0,a):this.steps.push(a);
return a}addSteps(a){Array.isArray(a)&&a.forEach(a=>{this.addStep(a)});return this}back(){let a=this.steps.indexOf(this.currentStep);this.show(a-1,!1)}cancel(){this.options.confirmCancel?window.confirm(this.options.confirmCancelMessage||"Are you sure you want to stop the tour?")&&this._done("cancel"):this._done("cancel")}complete(){this._done("complete")}getById(a){return this.steps.find(b=>b.id===a)}getCurrentStep(){return this.currentStep}hide(){let a=this.getCurrentStep();if(a)return a.hide()}isActive(){return X.activeTour===
this}next(){let a=this.steps.indexOf(this.currentStep);a===this.steps.length-1?this.complete():this.show(a+1,!0)}removeStep(a){let b=this.getCurrentStep();this.steps.some((b,d)=>{if(b.id===a)return b.isOpen()&&b.hide(),b.destroy(),this.steps.splice(d,1),!0});b&&b.id===a&&(this.currentStep=void 0,this.steps.length?this.show(0):this.cancel())}show(a=0,b=!0){if(a=Z(a)?this.getById(a):this.steps[a])this._updateStateBeforeShow(),S(a.options.showOn)&&!a.options.showOn()?this._skipStep(a,b):(this.trigger("show",
{step:a,previous:this.currentStep}),this.currentStep=a,a.show())}start(){this.trigger("start");this.focusedElBeforeOpen=document.activeElement;this.currentStep=null;this._setupModal();this._setupActiveTour();this.next()}_done(a){let b=this.steps.indexOf(this.currentStep);Array.isArray(this.steps)&&this.steps.forEach(a=>a.destroy());gc(this);this.trigger(a,{index:b});X.activeTour=null;this.trigger("inactive",{tour:this});this.modal&&this.modal.hide();"cancel"!==a&&"complete"!==a||!this.modal||(a=document.querySelector(".shepherd-modal-overlay-container"))&&
a.remove();this.focusedElBeforeOpen instanceof HTMLElement&&this.focusedElBeforeOpen.focus()}_setupActiveTour(){this.trigger("active",{tour:this});X.activeTour=this}_setupModal(){this.modal=new oc({target:this.options.modalContainer||document.body,props:{classPrefix:this.classPrefix,styles:this.styles}})}_skipStep(a,b){a=this.steps.indexOf(a);this.show(b?a+1:a-1,b)}_updateStateBeforeShow(){this.currentStep&&this.currentStep.hide();this.isActive()||this._setupActiveTour()}_setTourID(){this.id=`${this.options.tourName||
"tour"}--${va()}`}}Object.assign(X,{Tour:pc,Step:Ba});return X})
//# sourceMappingURL=shepherd.min.js.map
|
import _clone from 'lodash-es/clone';
import _keys from 'lodash-es/keys';
import _toPairs from 'lodash-es/toPairs';
import _union from 'lodash-es/union';
import _without from 'lodash-es/without';
import { debug } from '../index';
import { osmIsInterestingTag } from './tags';
import { dataDeprecated } from '../../data/index';
export function osmEntity(attrs) {
// For prototypal inheritance.
if (this instanceof osmEntity) return;
// Create the appropriate subtype.
if (attrs && attrs.type) {
return osmEntity[attrs.type].apply(this, arguments);
} else if (attrs && attrs.id) {
return osmEntity[osmEntity.id.type(attrs.id)].apply(this, arguments);
}
// Initialize a generic Entity (used only in tests).
return (new osmEntity()).initialize(arguments);
}
osmEntity.id = function(type) {
return osmEntity.id.fromOSM(type, osmEntity.id.next[type]--);
};
osmEntity.id.next = {
changeset: -1, node: -1, way: -1, relation: -1
};
osmEntity.id.fromOSM = function(type, id) {
return type[0] + id;
};
osmEntity.id.toOSM = function(id) {
return id.slice(1);
};
osmEntity.id.type = function(id) {
return { 'c': 'changeset', 'n': 'node', 'w': 'way', 'r': 'relation' }[id[0]];
};
// A function suitable for use as the second argument to d3.selection#data().
osmEntity.key = function(entity) {
return entity.id + 'v' + (entity.v || 0);
};
osmEntity.prototype = {
tags: {},
initialize: function(sources) {
for (var i = 0; i < sources.length; ++i) {
var source = sources[i];
for (var prop in source) {
if (Object.prototype.hasOwnProperty.call(source, prop)) {
if (source[prop] === undefined) {
delete this[prop];
} else {
this[prop] = source[prop];
}
}
}
}
if (!this.id && this.type) {
this.id = osmEntity.id(this.type);
}
if (!this.hasOwnProperty('visible')) {
this.visible = true;
}
if (debug) {
Object.freeze(this);
Object.freeze(this.tags);
if (this.loc) Object.freeze(this.loc);
if (this.nodes) Object.freeze(this.nodes);
if (this.members) Object.freeze(this.members);
}
return this;
},
copy: function(resolver, copies) {
if (copies[this.id])
return copies[this.id];
var copy = osmEntity(this, {id: undefined, user: undefined, version: undefined});
copies[this.id] = copy;
return copy;
},
osmId: function() {
return osmEntity.id.toOSM(this.id);
},
isNew: function() {
return this.osmId() < 0;
},
update: function(attrs) {
return osmEntity(this, attrs, {v: 1 + (this.v || 0)});
},
mergeTags: function(tags) {
var merged = _clone(this.tags), changed = false;
for (var k in tags) {
var t1 = merged[k],
t2 = tags[k];
if (!t1) {
changed = true;
merged[k] = t2;
} else if (t1 !== t2) {
changed = true;
merged[k] = _union(t1.split(/;\s*/), t2.split(/;\s*/)).join(';');
}
}
return changed ? this.update({tags: merged}) : this;
},
intersects: function(extent, resolver) {
return this.extent(resolver).intersects(extent);
},
isUsed: function(resolver) {
return _without(Object.keys(this.tags), 'area').length > 0 ||
resolver.parentRelations(this).length > 0;
},
hasInterestingTags: function() {
return _keys(this.tags).some(osmIsInterestingTag);
},
isHighwayIntersection: function() {
return false;
},
isDegenerate: function() {
return true;
},
deprecatedTags: function() {
var tags = _toPairs(this.tags);
var deprecated = {};
dataDeprecated.forEach(function(d) {
var match = _toPairs(d.old)[0];
tags.forEach(function(t) {
if (t[0] === match[0] &&
(t[1] === match[1] || match[1] === '*')) {
deprecated[t[0]] = t[1];
}
});
});
return deprecated;
}
};
|
'use strict';
module.exports = function enableAuthentication(server) {
// enable authentication
server.enableAuth();
};
|
'use strict';
var core = require('./src/core/bootstrap');
core.start()
.catch((err) => {
console.log(err);
});
|
'use strict';
var ndtutil = require('../ndtutil')
/**
* Alarm
* @param {object} env
* @return {P}
*/
module.exports = function(env){
return ndtutil.svc(env,'alarm')
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:44f9d14a36ef7f6c42f2c7bbac59a92b1dac5e546fe6d9b9febc62e5474b1c95
size 22242
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.13.2_A4.6_T2.8;
* @section: 11.13.2, 11.7.1;
* @assertion: The production x <<= y is the same as x = x << y;
* @description: Type(x) is different from Type(y) and both types vary between Boolean (primitive or object) and Undefined;
*/
//CHECK#1
x = true;
x <<= undefined;
if (x !== 1) {
$ERROR('#1: x = true; x <<= undefined; x === 1. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x <<= true;
if (x !== 0) {
$ERROR('#2: x = undefined; x <<= true; x === 0. Actual: ' + (x));
}
//CHECK#3
x = new Boolean(true);
x <<= undefined;
if (x !== 1) {
$ERROR('#3: x = new Boolean(true); x <<= undefined; x === 1. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x <<= new Boolean(true);
if (x !== 0) {
$ERROR('#4: x = undefined; x <<= new Boolean(true); x === 0. Actual: ' + (x));
}
|
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
async = require('async'),
jf = require('jsonfile'),
executing = false;
var config = require('../config.json');
var configM = require('./config.json');
jf.spaces = 2;
mongoose.connect(config.db.url ||
('mongodb://' + config.db.host + '/'+ config.db.name));
mongoose.model('User', new Schema(require('../models/User')) );
mongoose.model('Project', new Schema(require('../models/Project')) );
mongoose.model('Dashboard', new Schema(require('../models/Dashboard')) );
mongoose.model('Collection', new Schema(require('../models/Collection')) );
var hasCreated = { created_at: { $exists: true } };
var aggregation = [
{ $match: hasCreated },
{
$group: {
_id: {
year: { $year: "$created_at" },
month: { $month: "$created_at" },
//day: { $dayOfMonth: "$created_at" }
},
count: { $sum: 1 }
}
},
{ $project: { date: "$_id", count: 1, _id: 0 } },
{ $sort: { "date": 1 } }
];
var exec = {
users: function(done){
var User = mongoose.model('User');
User.aggregate(aggregation, function(err, users){
if (err) { return done(err); }
User.count(hasCreated, function(err, count){
done(err, {
total: count,
data: users
});
});
});
},
projects: function(done){
var Project = mongoose.model('Project');
Project.aggregate(aggregation, function(err, projects){
if (err) { return done(err); }
Project.count(hasCreated, function(err, count){
done(err, {
total: count,
data: projects
});
});
});
},
dashboards: function(done){
var Dashboard = mongoose.model('Dashboard');
Dashboard.aggregate(aggregation, function(err, dashboards){
if (err) { return done(err); }
Dashboard.count(hasCreated, function(err, count){
done(err, {
total: count,
data: dashboards
});
});
});
},
collections: function(done){
var Collection = mongoose.model('Collection');
Collection.aggregate(aggregation, function(err, collections){
if (err) { return done(err); }
Collection.count(hasCreated, function(err, count){
done(err, {
total: count,
data: collections
});
});
});
}
};
module.exports = function(done){
if (executing) return;
executing = true;
console.log('>>>>> Runing %s', new Date());
async.parallel(exec, function(err, data){
if (err){
return console.log(err);
console.log('Metrics NOT updated!');
}
/*
console.log(" %s Users", data.users.total);
console.log(" %s Projects", data.projects.total);
console.log(" %s Dashboards", data.dashboards.total);
console.log(" %s Collections", data.collections.total);
console.dir(data.users.data);
console.dir(data.projects.data);
console.dir(data.dashboards.data);
console.dir(data.collections.data);
*/
jf.writeFile('./' + configM.filename, data, function(err) {
if(err) {
console.log("Metrics NOT updated!");
console.log(err);
return done();
}
console.log('>>>>> Finished %s', new Date());
executing = false;
done && done();
});
});
};
|
describe('update element Function', function() {
var updateElement;
beforeEach(function() {
module('angular-stick-to');
inject(function(_updateElement_) {
updateElement = _updateElement_;
});
});
describe('when called with element in Case1', function() {
var element;
beforeEach(function() {
element = mock.createStickyElement({
primaryLimit: 50,
top: 100,
bottom: 110,
secondaryLimit: 150
});
});
[0, 5, 65].forEach(function(offset) {
describe('when has offset ' + offset, function() {
beforeEach(function() {
element.setSyntheticOffset(offset);
element.setSyntheticOffset.calls.reset();
});
it('should set 0 offset', function() {
updateElement(element);
expect(element.setSyntheticOffset).toHaveBeenCalledWith(0);
});
});
});
});
describe('when called with element in Case2', function() {
var element;
var expectedOffset;
beforeEach(function() {
element = mock.createStickyElement({
top: 50,
primaryLimit: 60,
bottom: 70,
secondaryLimit: 100
});
expectedOffset = element._primaryLimit - element._top;
});
[0, 5, 15, 65, 125].forEach(function(offset) {
describe('when has offset ' + offset, function() {
beforeEach(function() {
element.setSyntheticOffset(offset);
element.setSyntheticOffset.calls.reset();
});
it('should add expectedOffset to make element sticked to topLimit',
function() {
updateElement(element);
expect(element.setSyntheticOffset)
.toHaveBeenCalledWith(expectedOffset);
});
});
});
});
describe('when called with element in Case3', function() {
var element;
beforeEach(function() {
element = mock.createStickyElement({
primaryLimit: 50,
top: 65,
secondaryLimit: 70,
bottom: 81,
});
});
[0, 5, 15, 65, 125].forEach(function(offset) {
describe('when has offset ' + offset, function() {
beforeEach(function() {
element.setSyntheticOffset(offset);
element.setSyntheticOffset.calls.reset();
});
it('should set 0 offset', function() {
updateElement(element);
expect(element.setSyntheticOffset)
.toHaveBeenCalledWith(0);
});
});
});
});
describe('when called with element in Case4', function() {
var element;
var expectedOffset;
beforeEach(function() {
element = mock.createStickyElement({
top: 50,
primaryLimit: 60,
secondaryLimit: 65,
bottom: 80,
});
expectedOffset = element._secondaryLimit - element._bottom;
});
[0, 3, 5, 15, 65, 125].forEach(function(offset) {
describe('when has offset ' + offset, function() {
beforeEach(function() {
element.setSyntheticOffset(offset);
element.setSyntheticOffset.calls.reset();
});
it('should stick element to secondaryLimit', function() {
updateElement(element);
expect(element.setSyntheticOffset)
.toHaveBeenCalledWith(expectedOffset);
});
});
});
});
describe('when called with element in Case5', function() {
var element;
var expectedOffset;
beforeEach(function() {
element = mock.createStickyElement({
top: 50,
primaryLimit: 70,
bottom: 71,
secondaryLimit: 75
});
expectedOffset = element._secondaryLimit - element._bottom;
});
[0, 3, 5, 15, 65, 125].forEach(function(offset) {
describe('when has offset ' + offset, function() {
beforeEach(function() {
element.setSyntheticOffset(offset);
element.setSyntheticOffset.calls.reset();
});
it('should be sticked to bottom Limit', function() {
updateElement(element);
expect(element.setSyntheticOffset)
.toHaveBeenCalledWith(expectedOffset);
});
});
});
});
});
|
var System = require('../entities/systems/System');
/**
* Manages entities with a TimelineComponent
* @example-link http://code.gooengine.com/latest/visual-test/goo/timelinepack/TimelineComponent/TimelineComponent-vtest.html Working example
*/
function TimelineSystem() {
System.call(this, 'TimelineSystem', ['TimelineComponent']);
}
TimelineSystem.prototype = Object.create(System.prototype);
TimelineSystem.prototype.constructor = TimelineSystem;
TimelineSystem.prototype.process = function (entities, tpf) {
for (var i = 0; i < this._activeEntities.length; i++) {
var entity = this._activeEntities[i];
entity.timelineComponent.update(tpf);
}
};
/**
* Resumes updating the entities
*/
TimelineSystem.prototype.play = function () {
this.passive = false;
var entities = this._activeEntities;
for (var i = 0; i < entities.length; i++) {
var component = entities[i].timelineComponent;
if (component.autoStart) {
component.start();
}
}
};
/**
* Stops updating the entities
*/
TimelineSystem.prototype.pause = function () {
this.passive = true;
var entities = this._activeEntities;
for (var i = 0; i < entities.length; i++) {
var component = entities[i].timelineComponent;
component.pause();
}
};
/**
* Resumes updating the entities; an alias for `.play`
*/
TimelineSystem.prototype.resume = TimelineSystem.prototype.play;
/**
* Stop updating entities and resets the state machines to their initial state
*/
TimelineSystem.prototype.stop = function () {
this.passive = true;
var entities = this._activeEntities;
for (var i = 0; i < entities.length; i++) {
var component = entities[i].timelineComponent;
component.stop();
}
};
module.exports = TimelineSystem;
|
//>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");
/**
* Returns a `shoestring` object with the set of siblings of each element in the original set.
*
* @return shoestring
* @this shoestring
*/
shoestring.fn.next = function(){
//>>includeStart("development", pragmas.development);
if( arguments.length > 0 ){
shoestring.error( 'next-selector' );
}
//>>includeEnd("development");
var result = [];
// TODO need to implement map
this.each(function() {
var children, item, found;
// get the child nodes for this member of the set
children = shoestring( this.parentNode )[0].childNodes;
for( var i = 0; i < children.length; i++ ){
item = children.item( i );
// found the item we needed (found) which means current item value is
// the next node in the list, as long as it's viable grab it
// NOTE may need to be more permissive
if( found && item.nodeType === 1 ){
result.push( item );
break;
}
// find the current item and mark it as found
if( item === this ){
found = true;
}
}
});
return shoestring( result );
};
//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
|
/*
=========================================================
Name : InsertArg (ia)
GitHub : https://github.com/TimRohr22/Cauldron/tree/master/InsertArg
Roll20 Contact : timmaugh
---------------------------------------------------------
COMPONENTS
---------------------------------------------------------
Name : Core Engine Core Lib XRay
Version : 1.5.2 1.5.1 1.2
Last Update : 2/6/2020 12/2/2020 9/16/2020
=========================================================
*/
var API_Meta = API_Meta || {};
API_Meta.InsertArg = { offset: Number.MAX_SAFE_INTEGER, lineCount: -1 };
{
try { throw new Error(''); } catch (e) { API_Meta.InsertArg.offset = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - (17)); }
}
const ia = (() => {
// ==================================================
// VERSION
// ==================================================
const apiproject = 'InsertArg';
API_Meta[apiproject].version = '1.5.2';
const vd = new Date(1612647328500);
const versionInfo = () => {
log(`\u0166\u0166 ${apiproject} v${API_Meta[apiproject].version}, ${vd.getFullYear()}/${vd.getMonth() + 1}/${vd.getDate()} \u0166\u0166 -- offset ${API_Meta[apiproject].offset}`);
return;
};
const logsig = () => {
// initialize shared namespace for all signed projects, if needed
state.torii = state.torii || {};
// initialize siglogged check, if needed
state.torii.siglogged = state.torii.siglogged || false;
state.torii.sigtime = state.torii.sigtime || Date.now() - 3001;
if (!state.torii.siglogged || Date.now() - state.torii.sigtime > 3000) {
const logsig = '\n' +
' ‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗‗ ' + '\n' +
' ∖_______________________________________∕ ' + '\n' +
' ∖___________________________________∕ ' + '\n' +
' ___┃ ┃_______________┃ ┃___ ' + '\n' +
' ┃___ _______________ ___┃ ' + '\n' +
' ┃ ┃ ┃ ┃ ' + '\n' +
' ┃ ┃ ┃ ┃ ' + '\n' +
' ┃ ┃ ┃ ┃ ' + '\n' +
' ┃ ┃ ┃ ┃ ' + '\n' +
' ┃ ┃ ┃ ┃ ' + '\n' +
'______________┃ ┃_______________┃ ┃_______________' + '\n' +
' ⎞⎞⎛⎛ ⎞⎞⎛⎛ ' + '\n';
log(`${logsig}`);
state.torii.siglogged = true;
state.torii.sigtime = Date.now();
}
return;
};
// ==================================================
// TABLES AND TEMPLATES
// ==================================================
const elemSplitter = { outer: '⋄⋄', inner: '⋄' };
const htmlTable = {
"&": "&",
"{": "{",
"}": "}",
"|": "|",
",": ",",
"%": "%",
"?": "?",
"[": "[",
"]": "]",
"@": "@",
"~": "~",
"(": "(",
")": ")",
"<": "<",
">": ">",
};
const intCallTable = {
'--': '☰',
'{{': '〈〈',
'!!': '¡¡',
'}}': '〉〉'
}
const rowbg = ["#ffffff", "#dedede"];
const bgcolor = "#ce0f69";
const menutable = '<div style="width:100%;font-family:Arial, Calibri, Consolas, cursive; font-size:12px;"><div style="border-radius:10px;background-color:maincolor; overflow:hidden;"><div style="width:100%;overflow:hidden;"><div style="font-size: 1.8em; line-height:24px; color: maintextcolor;text-align:left;width:95%; margin:auto;padding:4px;">title</div></div>row<div style="line-height:10px;"> </div></div></div>';
const menurow = '<div style="background-color:altcolor;color:alttextcolor;border:solid maincolor_nooverride; border-width: 0px 1px;display:block;overflow:hidden;"><div style="width:95%;margin:4px auto; overflow: hidden;"><div style="float:left;width:100%;display:inline-block;font-weight:bold;font-size:1.25em;">title</div><div style="float:left;width:100%;display:inline-block;">rowsource</div></div></div>';
const menuelem = '<div style="background-color:altcolor;color:alttextcolor;border:solid maincolor; border-width: 0px 1px;display:block;overflow:hidden;"><div style="width:95%;margin:1px auto 0px; overflow: visible;"><div style="float:left;display:inline-block;">title</div><div style="float:right;display:inline-block;text-align:right;">rowsource</div></div></div>';
const msgtable = '<div style="width:100%;"><div style="border-radius:10px;border:2px solid #000000;background-color:__bg__; margin-right:16px; overflow:hidden;"><table style="width:100%; margin: 0 auto; border-collapse:collapse;font-size:12px;">__TABLE-ROWS__</table></div></div>';
const msg1header = '<tr style="border-bottom:1px solid #000000;font-weight:bold;text-align:center; background-color:__bg__; line-height: 22px;"><td>__cell1__</td></tr>';
const msg2header = '<tr style="border-bottom:1px solid #000000;font-weight:bold;text-align:center; background-color:__bg__; line-height: 22px;"><td>__cell1__</td><td style="border-left:1px solid #000000;">__cell2__</td></tr>';
const msg3header = '<tr style="border-bottom:1px solid #000000;font-weight:bold;text-align:center; background-color:__bg__; line-height: 22px;"><td>__cell1__</td><td style="border-left:1px solid #000000;">__cell2__</td><td style="border-left:1px solid #000000;">__cell3__</td></tr>';
const msg1row = '<tr style="background-color:__bg__;"><td style="padding:4px;__row-css__">__cell1__</td></tr>';
const msg2row = '<tr style="background-color:__bg__;font-weight:bold;"><td style="padding:1px 4px;">__cell1__</td><td style="border-left:1px solid #000000;text-align:center;padding:1px 4px;font-weight:normal;">__cell2__</td></tr>';
const msg3row = '<tr style="background-color:__bg__;font-weight:bold;"><td style="padding:1px 4px;">__cell1__</td><td style="border-left:1px solid #000000;text-align:center;padding:1px 4px;font-weight:normal;">__cell2__</td><td style="border-left:1px solid #000000;text-align:center;padding:1px 4px;font-weight:normal;">__cell3__</td></tr>';
// ==================================================
// UTILITIES
// ==================================================
const getTheSpeaker = function (msg) {
var characters = findObjs({ type: 'character' });
var speaking;
characters.forEach((chr) => { if (chr.get('name') === msg.who) speaking = chr; });
if (speaking) {
speaking.speakerType = "character";
speaking.localName = speaking.get("name");
} else {
speaking = getObj('player', msg.playerid);
speaking.speakerType = "player";
speaking.localName = speaking.get("displayname");
}
speaking.chatSpeaker = speaking.speakerType + '|' + speaking.id;
return speaking;
};
const getAllGMs = () => {
return findObjs({ type: 'player' }).filter(p => playerIsGM(p.id));
};
const getDefaultConfigObj = () => {
return { bg: bgcolor, css: "", store: 'InsertArg', label: 'Loaded Ability' };
};
const splitArgs = a => a.split("#");
const joinVals = a => [a.slice(0)[0], a.slice(1).join("#").trim()];
const escapeRegExp = (string) => { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); };
const getMapArgFuncRegex = (obj) => {
return new RegExp('^(' + Object.keys(obj).join("|") + '){{(.*(?=}}))}}');
// group 1: function from function{{arguments}}
// group 2: arguments from function{{arguments}}
};
const decodeUrlEncoding = (t) => {
return t.replace(/%([0-9A-Fa-f]{1,2})/g, (f, n) => { return String.fromCharCode(parseInt(n, 16)); });
};
const execCharSet = ["&", "!", "@", "#", "%", "?"];
const sheetElem = { attr: '@', abil: '%', macro: '#' };
const getAltColor = (primarycolor, fade = .35) => {
let pc = hexToRGB(`#${primarycolor.replace(/#/g, '')}`);
let sc = [0, 0, 0];
for (let i = 0; i < 3; i++) {
sc[i] = Math.floor(pc[i] + (fade * (255 - pc[i])));
}
return RGBToHex(sc[0], sc[1], sc[2]);
};
const RGBToHex = (r, g, b) => {
r = r.toString(16);
g = g.toString(16);
b = b.toString(16);
if (r.length === 1)
r = "0" + r;
if (g.length === 1)
g = "0" + g;
if (b.length === 1)
b = "0" + b;
return "#" + r + g + b;
};
const getTextColor = (h) => {
h = `#${h.replace(/#/g, '')}`;
let hc = hexToRGB(h);
return (((hc[0] * 299) + (hc[1] * 587) + (hc[2] * 114)) / 1000 >= 128) ? "#000000" : "#ffffff";
};
const hexToRGB = (h) => {
let r = 0, g = 0, b = 0;
// 3 digits
if (h.length === 4) {
r = "0x" + h[1] + h[1];
g = "0x" + h[2] + h[2];
b = "0x" + h[3] + h[3];
// 6 digits
} else if (h.length === 7) {
r = "0x" + h[1] + h[2];
g = "0x" + h[3] + h[4];
b = "0x" + h[5] + h[6];
}
return [+r, +g, +b];
};
const validateHexColor = (s, d = 'ff9747') => {
let colorRegX = /(^#?[0-9A-F]{6}$)|(^#?[0-9A-F]{3}$)/i;
return '#' + (colorRegX.test(s) ? s.replace('#', '') : d);
};
const htmlCoding = (s = "", encode = true) => {
if (typeof s !== "string") return undefined;
let searchfor = encode ? htmlTable : _.invert(htmlTable);
s = s.replace(new RegExp(Object.keys(searchfor)
.map((k) => { return escapeRegExp(k); })
.join("|"), 'gmi'), (r) => { return searchfor[r]; })
.replace(new RegExp(/\n/, 'gmi'), '<br><br>');
return s;
};
const internalCallCoding = (s = "", encode = true) => {
if (typeof s !== 'string') return undefined;
let searchfor = encode ? intCallTable : _.invert(intCallTable);
s = s.replace(new RegExp(Object.keys(searchfor)
.map(k => escapeRegExp(k))
.join("|"), 'gmi'), (r) => { return searchfor[r]; });
return s;
};
const displayIAConfig = (theSpeaker, cfgObj = getDefaultConfigObj()) => {
let clVersion = ialibcore.GetVrs();
let xrVersion = xray.GetVrs();
let msg = `<table style="width:100%;">\
<tr>\
<td style="font-weight:bold;">InsertArg</td>\
<td style="text-align:right;font-weight:bold;">v ${API_Meta[apiproject].version} </td>\
</tr>\
<tr>\
<td style="font-weight:bold;">Core Library</td>\
<td style="text-align:right;font-weight:bold;">v ${clVersion} </td>\
</tr>\
<tr>\
<td style="font-weight:bold;">Xray</td>\
<td style="text-align:right;font-weight:bold;">v ${xrVersion} </td>\
</tr>\
</table><br>\
<table style="width:100%;">\
<tr>\
<td> Logging is ${state.ia.logparser ? 'ON' : 'OFF'}</td>\
<td style="text-align:right;">${btnAPI({ bg: cfgObj.bg, label: 'TGL', api: `!ia --log`, css: cfgObj.css })} </td>\
</tr>\
<tr>\
<td> Make Help Handout</td>\
<td style="text-align:right;">${btnAPI({ bg: cfgObj.bg, label: 'Make', api: `!ia --handout#make{{!!doc#help}}`, css: cfgObj.css })} </td>\
</tr>\
<tr>\
<td> Make Global Config</td>\
<td style="text-align:right;">${btnAPI({ bg: cfgObj.bg, label: 'Make', api: `!ia --handout#make{{!!doc#config#global}}`, css: cfgObj.css })} </td>\
</tr>\
<tr>\
<td> Make My Config</td>\
<td style="text-align:right;">${btnAPI({ bg: cfgObj.bg, label: 'Make', api: `!ia --handout#make{{!!doc#config#${theSpeaker.localName}}}`, css: cfgObj.css })} </td>\
</tr>\
</table><br><br>\
INTERNAL FUNCTIONS:<br>`;
let rows = Object.keys(availFuncs).sort().map(f => {
let btn = Object.prototype.hasOwnProperty.call(availHelp, f) ? btnAPI({ bg: cfgObj.bg, label: 'Help', api: `!ia --help#${f}`, css: cfgObj.css }) : "";
return `<tr><td> ${f}</td><td style="text-align:right;">${btn} </td></tr>`;
}).join("");
msg += `<table style="width:100%;">${rows}</table><br>`;
msgbox({ c: msg, t: 'INSERTARG CONFIG', send: true, wto: theSpeaker.localName });
};
const base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function (e) {
var t = "";
var n, r, i, s, o, u, a;
var f = 0;
e = base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = (n & 3) << 4 | r >> 4;
u = (r & 15) << 2 | i >> 6;
a = i & 63;
if (isNaN(r)) {
u = a = 64
} else if (isNaN(i)) {
a = 64
}
t = t +
this._keyStr.charAt(s) +
this._keyStr.charAt(o) +
this._keyStr.charAt(u) +
this._keyStr.charAt(a)
}
return t
},
decode: function (e) {
var t = "";
var n, r, i;
var s, o, u, a;
var f = 0;
e = e.replace(/[^A-Za-z0-9+/=]/g, "");
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++));
o = this._keyStr.indexOf(e.charAt(f++));
u = this._keyStr.indexOf(e.charAt(f++));
a = this._keyStr.indexOf(e.charAt(f++));
n = s << 2 | o >> 4;
r = (o & 15) << 4 | u >> 2;
i = (u & 3) << 6 | a;
t = t + String.fromCharCode(n);
if (u !== 64) {
t = t + String.fromCharCode(r)
}
if (a !== 64) {
t = t + String.fromCharCode(i)
}
}
t = base64._utf8_decode(t);
return t
},
_utf8_encode: function (e) {
e = e.replace(/\r\n/g, "\n");
var t = "";
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r)
} else if (r > 127 && r < 2048) {
t +=
String.fromCharCode(r >> 6 | 192);
t +=
String.fromCharCode(r & 63 | 128)
} else {
t +=
String.fromCharCode(r >> 12 | 224);
t +=
String.fromCharCode(r >> 6 & 63 | 128);
t +=
String.fromCharCode(r & 63 | 128)
}
}
return t
},
_utf8_decode: function (e) {
var t = "";
var n = 0;
var r = c1 = c2 = 0;
while (n < e.length) {
r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
n++
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1);
t += String.fromCharCode(
(r & 31) << 6 | c2 & 63);
n += 2
} else {
c2 = e.charCodeAt(n + 1);
c3 = e.charCodeAt(n + 2);
t += String.fromCharCode(
(r & 15) << 12 | (c2 & 63)
<< 6 | c3 & 63);
n += 3
}
}
return t
}
};
const btnElem = ({ bg: btnbg = bgcolor, store: s = "InsertArg", label: btnlabel = "Loaded Ability", charname: cn = "not set", entity: e = "%", css: css = "" } = {}) => {
if (e.length === 1) e = htmlTable[e] || e;
btnbg = validateHexColor(btnbg);
return `<a style="background-color: ${btnbg}; color: ${getTextColor(btnbg)}; ${css}" href="! ${e}{${cn}|${s}}">${btnlabel}</a>`;
};
const btnAPI = ({ bg: btnbg = bgcolor, api: api = "", label: btnlabel = "Run API", css: css = "", r20style: r20style = false } = {}) => {
btnbg = validateHexColor(btnbg);
api = htmlCoding(api, true);
r20style = ['t', 'true', 'y', 'yes', true].includes(r20style) ? true : false;
return `<a style="background-color: ${btnbg}; color: ${getTextColor(btnbg)};${r20style ? 'padding: 5px;display:inline-block;border 1px solid white;' : ''}${css}" href="${api}">${btnlabel}</a>`;
};
const charFromAmbig = (info) => { // find a character where info is an identifying piece of information (id, name, or token id)
let character;
character = findObjs({ type: 'character', id: info })[0] ||
findObjs({ type: 'character' }).filter(c => c.get('name') === info)[0] ||
findObjs({ type: 'character', id: (getObj("graphic", info) || { get: () => { return "" } }).get("represents") })[0];
return character;
};
const playerFromAmbig = (info) => { // find a player where info is an identifying piece of information (id or name)
let player;
player = findObjs({ type: 'player', id: info })[0] ||
findObjs({ type: 'player' }).filter(p => p.get('displayname') === info)[0];
return player;
};
const abilFromAmbig = (info, character = '') => { // find an abil where info is an identifying piece of information for the ability (id or character|name)
let abil = findObjs({ type: 'ability', id: info })[0];
if (abil) return abil;
let c, n;
if (info.indexOf("|") > -1) {
[c, n] = info.split("|");
} else {
c = character;
n = info;
}
if (!c || !n) return abil;
c = charFromAmbig(c);
if (!c) return abil;
abil = findObjs({ type: 'ability', characterid: c.id }).filter(a => a.get('name') === n)[0] ||
findObjs({ type: 'ability', characterid: c.id }).filter(a => a.id === n)[0];
return abil;
};
const attrFromAmbig = (info, character = '') => { // find an attr where info is an identifying piece of information for the attribute (id or character|name)
let attr = findObjs({ type: 'attribute', id: info })[0];
if (attr) return attr;
let c, n;
if (info.indexOf("|") > -1) {
[c, n] = info.split("|");
} else {
c = character;
n = info;
}
if (!c || !n) return attr;
c = charFromAmbig(c);
if (!c) return attr;
attr = findObjs({ type: 'attribute', characterid: c.id }).filter(a => a.get('name') === n)[0] ||
findObjs({ type: 'attribute', characterid: c.id }).filter(a => a.id === n)[0];
return attr;
};
const repeatingFromAmbig = (info, character = '', s = '', sfxn = '') => {
let obj = findObjs({ type: 'attribute', id: info })[0];
if (obj) return obj;
let c, n;
if (info.indexOf("|") > -1) {
[c, n] = info.split("|");
} else {
c = character;
n = info;
}
if (!c || !n) return obj;
c = charFromAmbig(c);
if (!c) return obj;
obj = findObjs({ type: 'attribute', characterid: c.id }).filter(a => a.get('name') === n)[0] ||
findObjs({ type: 'attribute', characterid: c.id }).filter(a => a.id === n)[0];
if (obj) return obj;
if (s && sfxn) { // if we have a section and a naming suffix, test if what we have is the name of an element group from this section
obj = findObjs({ type: 'attribute', characterid: c.id })
.filter(a => new RegExp(`^repeating_${s}_.*?_${sfxn}$`).test(a.get('name')))
.filter(a => a.get('current') === n)[0];
}
return obj;
};
const macroFromAmbig = (info) => {
let mac = findObjs({ type: 'macro', id: info })[0];
if (mac) return mac;
mac = findObjs({ type: 'macro' }).filter(m => m.get('name') === info)[0];
return mac;
};
const tokenFromAmbig = (info) => {
let token = findObjs({ type: 'graphic', subtype: 'token', id: info })[0];
if (token) return token;
token = findObjs({ type: 'graphic', subtype: 'token' }).filter(t => t.get('name') === info)[0];
return token;
};
const msgbox = ({ c: c = "chat message", t: t = "title", btn: b = "buttons", send: send = false, sendas: sas = "API", wto: wto = "" }) => {
let tbl = msgtable.replace("__bg__", rowbg[0]);
let hdr = msg1header.replace("__bg__", rowbg[1]).replace("__cell1__", t);
let row = msg1row.replace("__bg__", rowbg[0]).replace("__cell1__", c);
let btn = b !== "buttons" ? msg1row.replace("__bg__", rowbg[0]).replace("__cell1__", b).replace("__row-css__", "text-align:right;margin:4px 4px 8px;") : "";
let msg = tbl.replace("__TABLE-ROWS__", hdr + row + btn);
if (wto) msg = `/w "${wto}" ${msg}`;
if (["t", "true", "y", "yes", true].includes(send)) {
sendChat(sas, msg);
} else {
return msg;
}
};
const getHelpArg = () => { return 'ArgOption'; };
const applyFormatOptions = (f, l, prop = 'label') => {
// expects f to be a pipe-separated list of formatting options in the form of fo[#(options)]
// list is an array of objects in the form of {nameObj, execObj, label, execName, execText, rlbl}
// prop is the property in the object to format
let insertcheck;
Object.keys(Object.fromEntries(f.split("|").map(fo => [fo, true]))).forEach(fo => {
switch (fo) {
case 'su': // space before uppercase
l = l.map(a => Object.assign(a, { [prop]: a[prop].replace(/((?<!\b)[A-Z])/g, ' $1') }));
break;
case '_s': // replace underscore with space
l = l.map(a => Object.assign(a, { [prop]: a[prop].replace(/((?<!\b)_(?!\b))/g, ' ') }))
.map(a => Object.assign(a, { [prop]: a[prop].replace(/_/g, ' ') }));
break;
case 'ss': // remove extra white-space
l = l.map(a => Object.assign(a, { [prop]: a[prop].replace(/\s+/g, ' ') }));
break;
case 'uc': // to uppercase
l = l.map(a => Object.assign(a, { [prop]: a[prop].toUpperCase() }));
break;
case 'lc': // to lowercase
l = l.map(a => Object.assign(a, { [prop]: a[prop].toLowerCase() }));
break;
case 'tc': // to titlecase
l = l.map(a => Object.assign(a, { [prop]: a[prop].replace(/((?<=\b(?<![^\s]'))[a-z])/g, l => l.toUpperCase()) }));
break;
case 'o+': // sort ascending (order)
l = l.sort((a, b) => (a[prop] > b[prop]) ? 1 : -1);
break;
case 'o-': // sort descending (order)
l = l.sort((a, b) => (a[prop] > b[prop]) ? -1 : 1);
break;
case 'n':
l = l.map(a => Object.assign(a, { [prop]: ia.RunInternal("nest")({ s: a[prop] }).ret }));
break;
default:
// case fr
if (/fr#.+/.test(fo)) { // find#replace
[, frmtsearch, frmtreplace = ''] = fo.split("#");
frmtsearch = checkTicks(frmtsearch);
frmtreplace = checkTicks(frmtreplace);
l = l.map(a => Object.assign(a, { [prop]: a[prop].replace(new RegExp(escapeRegExp(frmtsearch), 'g'), frmtreplace) }));
}
// case ^t or t^
insertcheck = /^(\^t|t\^)#(.+)/.exec(fo);
// group 1: type from type#insert
// group 2: insert from type#insert
if (insertcheck) { // insert around text
let ipre = insertcheck[1] === '^t' ? checkTicks(insertcheck[2]) : '';
let ipost = insertcheck[1] === 't^' ? checkTicks(insertcheck[2]) : '';
l = l.map(a => Object.assign(a, { [prop]: `${ipre}${a[prop]}${ipost}` }));
}
// case rslv
if (/^rslv#.+/.test(fo)) { // resolve; like find/replace, except searches for the "find" as @{find}
[, frmtsearch, frmtreplace = ''] = fo.split("#");
frmtsearch = `@{${checkTicks(frmtsearch)}}`;
frmtreplace = checkTicks(frmtreplace);
l = l.map(a => Object.assign(a, { [prop]: a[prop].replace(new RegExp(escapeRegExp(frmtsearch), 'g'), frmtreplace) }));
}
break;
}
});
return l;
};
const applyFilterOptions = (f, l, prop = 'execName', xprop = 'execText') => {
// expects l to be an array of objects in the form of {nameObj, execObj, label, execName, execText, rlbl}
if (f) {
let topx;
let filters = f.split("|").map(f => f.split("#")).map(f => { return { filter: f[0], cond: checkTicks(f.slice(1).join("#")) || "" }; });
filters.forEach(f => {
switch (f.filter) {
case 'x': // only executable values
l = l.filter(a => typeof a[xprop] === 'string' && a[xprop].length && execCharSet.includes(a[xprop].charAt(0))); // test for the presence of an executing character
break;
case '^f': // starts with
l = l.filter(a => a[prop].startsWith(f.cond));
break;
case 'f^': // ends with
l = l.filter(a => new RegExp(`${escapeRegExp(f.cond)}$`).test(a[prop]));
break;
case '^f^': // contains
l = l.filter(a => new RegExp(`${escapeRegExp(f.cond)}`).test(a[prop]));
break;
case '-^f': // does not start with
l = l.filter(a => !a[prop].startsWith(f.cond));
break;
case '-f^': // does not end with
l = l.filter(a => !(new RegExp(`${escapeRegExp(f.cond)}$`).test(a[prop])));
break;
case '-^f^': // does not contain
l = l.filter(a => !(new RegExp(`${escapeRegExp(f.cond)}`).test(a[prop])));
break;
case '-s': // token status markers do not include
l = l.filter(a => !a.nameObj.get('statusmarkers').split(",").includes(f.cond));
break;
case 's': // token status markers include
l = l.filter(a => a.nameObj.get('statusmarkers').split(",").includes(f.cond));
break;
case 'top':
topx = parseInt(f.cond);
if (isNaN(topx) || topx === 0) break;
l = topx > 0 ? l.slice(0, topx) : l.slice(topx);
break;
default:
break;
}
});
}
return l;
};
const buildOutputOptions = ({ p: p, op: op, list: list, bg: bg, css: css, character: character = { get: () => { return '' } }, elem: elem = 'attr', v: v = 'current', theSpeaker: theSpeaker, d: d }) => {
let retObj = { ret: "", safe: true };
v = elem === 'abil' ? 'action' : v;
let q2 = "", prop = 'l', mArg = 'whisper';
let msg = '';
switch (op.charAt(0)) {
case "b": // buttons
if (op.length > 1) q2 = op.slice(1);
switch (q2) {
case 'c': // card output button
case 'C': // card outputbutton, set to chat
if (q2 === 'C') mArg = 'chat';
if (!Object.prototype.hasOwnProperty.call(list[0], "cardapi")) {
ia.MsgBox({ c: `buildOutputOptions: Card output is currently only intended for repeating sections.`, t: 'NOT A REPEATING SOURCE', send: true, wto: theSpeaker.localName });
return retObj;
}
retObj.ret = list.map(a => {
return ia.BtnAPI({ bg: bg, api: ia.InternalCallCoding(`!ia --${mArg} --show#${a.cardapi || ''}`, true), label: a.label, charid: character.id, entity: sheetElem[elem], css: css })
}).join(d);
break;
case 'ec': // card output for external labels (elem output)
case 'ce':
case 'eC':
case 'Ce':
if (['Ce','eC'].includes(q2)) mArg = 'chat';
if (!Object.prototype.hasOwnProperty.call(list[0], "cardapi")) {
ia.MsgBox({ c: `buildOutputOptions: Card output is currently only intended for repeating sections.`, t: 'NOT A REPEATING SOURCE', send: true, wto: theSpeaker.localName });
return retObj;
}
retObj.ret = list.map(a => {
return a.label + ia.ElemSplitter.inner + ia.BtnAPI({ bg: bg, api: ia.InternalCallCoding(`!ia --${mArg} --show#${a.cardapi || ''}`, true), label: a.rlbl, charid: character.id, entity: sheetElem[elem], css: css })
}).join(ia.ElemSplitter.outer);
break;
case 'R': // read the action text in a msgbox
case 'r':
if (q2 === 'R') mArg = 'chat';
retObj.ret = list.map(a => ia.BtnAPI({ bg: bg, api: ia.InternalCallCoding(`!ia --${mArg} --show#msgbox{{!!c#get${elem}{{!!a#${a.execObj.id} !!h#true !!v#${v}}} !!t#${a.label} !!send#true !!sendas#getme{{!!r#cs}}}}`,true), label: a.label, charid: character.id, entity: sheetElem[elem], css: css }))
.join(d);
break;
case 'e': // spread the return out over multiple table elements
retObj.ret = list.map(a => { return a.label + ia.ElemSplitter.inner + ia.BtnElem({ bg: bg, store: a.execName, label: a.rlbl, charname: character.get('name'), entity: sheetElem[elem], css: css }) })
.join(ia.ElemSplitter.outer);
break;
case 'er': // both 'e' and 'r', reading the action text in a msgbox and spreading the return over multiple table elements
case 're':
case 'eR': // same, but chat output (not whisper)
case 'Re':
if (['Re', 'eR'].includes(q2)) mArg = 'chat';
retObj.ret = list.map(a => { return a.label + ia.ElemSplitter.inner + ia.BtnAPI({ bg: bg, api: ia.InternalCallCoding(`!ia --${mArg} --show#msgbox{{!!c#get${elem}{{!!a#${a.execObj.id} !!h#true !!v#${v}}} !!t#${a.label} !!send#true !!sendas#getme{{!!r#cs}}}}`,true), label: a.rlbl, charid: character.id, entity: sheetElem[elem], css: css }) })
.join(ia.ElemSplitter.outer);
break;
case "":
default:
retObj.ret = list.map(a => ia.BtnElem({ bg: bg, store: a.execName, label: a.label, charname: character.get('name'), entity: sheetElem[elem], css: css }))
.join(d);
break;
}
break;
case "c": // card output (whisper or chat determined by mapArg)
list.map(l => {
if (!Object.prototype.hasOwnProperty.call(l, "sublist")) {
Object.assign(l, { sublist: [['', 'Name', l.label], ['', 'Description(fw)', l.execText]] }); // if we don't have the sublist, build it just with the stuff we do have
}
msg = l.sublist.slice(1).map((a, i) => {
if (a[1].endsWith('(fw)')) { // allow full-width elements
return `<tr><td style="vertical-align:top;font-weight: bold;" colspan = "1">${htmlCoding(a[1].slice(0, -4)).replace(/\s/g, ' ')}</td></tr><tr><td style="vertical-align:top;" colspan = "3">${typeof a[2] !== 'string' ? a[2] : htmlCoding(a[2])}</td></tr>`;
} else {
return `<tr><td style="vertical-align:top;width:1%; white-space: nowrap;font-weight: bold;">${htmlCoding(a[1]).replace(/\s/g, ' ')}</td><td> </td><td style="vertical-align:top;">${typeof a[2] !== 'string' ? a[2] : htmlCoding(a[2])}</td></tr>`;
}
}).join("");
msg = `<table style="width:96%;">${msg}</table>`;
retObj.ret += msgbox({ c: msg, t: l.sublist[0][2].toUpperCase(), send: false }) + '<br>';
});
break;
case "q": // query
case "n": // nested query
if (op.length > 1) q2 = op.slice(1);
switch (q2) {
case 'l': // list of labels
list = list.map(a => a.label.replace(/,/g, '')).join("|");
break;
case 'v': // list of values
list = list.map(a => a.execText).join("|");
break;
case 'ln': // label, value (or character name)
list = list.map(a => [a.label.replace(/,/g, ''), a.execName]);
prop = 'a'; // change the property to which we will feed the list to be 'a' since we have built an array
break;
case 'lv': // label, value
default:
list = list.map(a => [a.label.replace(/,/g, ''), a.execText]);
prop = 'a'; // change the property to which we will feed the list to be 'a' since we have built an array
}
retObj = ia.RunInternal("query")({ p: p, [prop]: list, n: (op.charAt(0) === "n") ? 'true' : 'false', theSpeaker: theSpeaker });
break;
case "v": // produce list of the values
list = list.map(a => a.execText).join(d);
retObj.ret = list;
break;
case "l": // produce list of the labels
if (op.length > 1) q2 = op.slice(1);
switch (q2) {
case 've':
list = list.map(a => { return a.label + ia.ElemSplitter.inner + a.execText; }).join(ia.ElemSplitter.outer);
retObj.ret = list;
break;
default:
list = list.map(a => a.label).join(d);
retObj.ret = list;
break;
}
break;
default:
list = list.map(a => a.label).join(d);
retObj.ret = list;
break;
}
return retObj;
}
const checkTicks = (s) => {
let special = {
"`br`": "<br>",
"`hr`": "<hr>"
}
if (typeof s !== 'string') return s;
return special[s] || (s.indexOf("`") === 0 && s.charAt(s.length - 1) === "`" ? s.slice(1, s.length - 1) : s);
};
// ==================================================
// AVAIL INTERNAL FUNCTIONS, HELP, and MENUS
// ==================================================
// each function should be built using destructuring assignment, which will provide immediate !!arg availability to each parameter
// each function should return an object of { ret:the text constructed, safe: whether it's safe to chat }
// once built, enter it in the library object availFuncs to make it available to users (below functions)
const nest = ({
s: s = "", // string to perform the replace on
}) => {
let retObj = { ret: "", safe: true };
let nestrx = new RegExp(/[@%]{[^}]*?}|([,|}])/, 'gm');
// group 1s: all } , | that are not part of an ability or attribute
if (s) {
retObj.ret = s.replace(nestrx, (match) => { return htmlTable[match]; });
}
return retObj;
};
const query = ({
p: p = "Select", // prompt for query
l: l = "", // pre-built list of options
a: a, // array a [label, return]
n: n = "false", // whether to make this a nested query
m: m, // message object
theSpeaker: theSpeaker, // the Speaker object
cfgObj: cfgObj, // config object
}) => {
let retObj = { ret: "", safe: true };
n = ["true", "t", "yes", "y"].includes(n.toLowerCase());
let list = "";
if (l) { // user supplied a list, so use it
list = l;
} else if (Array.isArray(a) && a.length) { // user supplied an array of [label, return], so build from there
list = a.map(e => e.join(",")).join("|");
} else {
ia.MsgBox({ c: `query: You must supply either a list (l) or an array (a) of elements in the form of [label, return].`, t: 'NO QUERY SOURCE', send: true, wto: theSpeaker.localName });
return retObj;
}
retObj.ret = n ? nest({ s: `?{${p}|${list}}` }).ret : `?{${p}|${list}}`;
return retObj;
};
const getrow = ({
r: r = "row", // menu element to retrieve; menu entry must have that element available
c: color = '', // color override for the row
f: f, // fade override
t: t = 'Section', // row heading
s: s = '', // source for the row content
theSpeaker: theSpeaker
}) => {
let retObj = { ret: "", safe: true };
state.ia[theSpeaker.localName] = state.ia[theSpeaker.localName] || {};
state.ia[theSpeaker.localName].menu = state.ia[theSpeaker.localName].menu || // menu in the state variable is there, or...
Object.assign({ tbl: "", row: "", elem: "", menu: "default", color: "#4b688b", fade: .5 }, availMenus.default || { row: "", menu: "" }); // get defaults, defaulting to empty string if the default menu isn't present
let ms = Object.assign({}, state.ia[theSpeaker.localName].menu);
let maintextcolor = getTextColor(ms.color);
r = ['e', 'elem'].includes(r) ? 'elem' : 'row';
if (!Object.prototype.hasOwnProperty.call(ms, r)) r = "row"; // if the menu doesn't offer that menu element, default to row
// get the color (check for override)
if (color) color = validateHexColor(color, '#ffffff'); // if user supplied a color override, validate it using white as a default
else color = validateHexColor(ms.color);
let mcno = validateHexColor(ms.color); // set color for maincolor_nooverride
// get the fade
if (f) f = (isNaN(Number(f)) || Number(f) > 1 || Number(f) < 0) ? .5 : Number(f); // if provided and it's not a number, or it's a number outside of the 0-1 range, make it .5
else f = (isNaN(Number(ms.fade)) || Number(ms.fade) > 1 || Number(ms.fade) < 0) ? .5 : Number(ms.fade); // if not provided, put the same tests to the menu in state
// fade the color for altcolor
altcolor = getAltColor(color, f);
// get text color
let alttextcolor = getTextColor(altcolor);
// there is still the possibility that the specified menu does not have an "r" element,
// so we have to account for creating a default, if necessary
switch (r) {
case 'elem':
if (new RegExp(`${escapeRegExp(elemSplitter.outer)}$`).test(s)) {
s = base64.decode(s.slice(0, elemSplitter.outer.length * -1));
}
// s.split(elemSplitter.outer).map(e => e.split(elemSplitter.inner)).forEach(fe => { log(`LABEL: ${fe[0]}`); log(`BUTTON: ${fe[1]}`); });
retObj.ret = s.split(elemSplitter.outer).map(e => e.split(elemSplitter.inner))
.map(e => {
return (availMenus[ms.menu][r] || availMenus.default.row || "") // get the row (or default)
.replace(/\bmaincolor_nooverride\b/g, mcno) // replace maincolor_nooverride references
.replace(/\bmaincolor\b/g, color) // replace maincolor references
.replace(/\bmaintextcolor\b/g, maintextcolor) // replace maintextcolor references
.replace(/\baltcolor\b/g, altcolor) // replace rowbgcolor references
.replace(/\balttextcolor\b/g, alttextcolor) // replace rowtextcolor references
.replace(/\btitle\b/, e[0]) // replace the title
.replace(/\browsource\b/, e[1]) // finally, insert the source into the row
})
.join("");
break;
case 'row':
default:
retObj.ret = (availMenus[ms.menu][r] || availMenus.default.row) // get the row (or default)
.replace(/\bmaincolor_nooverride\b/g, mcno) // replace maincolor_nooverride references
.replace(/\bmaincolor\b/g, color) // replace maincolor references
.replace(/\bmaintextcolor\b/g, maintextcolor) // replace maintextcolor references
.replace(/\baltcolor\b/g, altcolor) // replace rowbgcolor references
.replace(/\balttextcolor\b/g, alttextcolor) // replace rowtextcolor references
.replace(/\btitle\b/, checkTicks(t)) // replace the title
.replace(/\browsource\b/, checkTicks(s)); // finally, insert the source into the row
break;
}
return retObj;
};
const msgboxwrapper = ({ c: c = "chat message", t: t = "title", btn: btn = "buttons", theSpeaker: theSpeaker }) => {
return { ret: msgbox({ c: c, t: t, btn: btn, send: false, sendas: theSpeaker.chatSpeaker }), safe: true };
};
// ----------- AVAILABLE LIBRARIES -----------
const availFuncs = { // library of available functions as prop:func
query: query,
nest: nest,
getrow: getrow,
msgbox: msgboxwrapper
};
const availHelp = {
query: {
msg: 'Turns a list of options (l) into a query using prompt argument (p). Alternatively, produces a nested query by including the argument "n". \
For internal calls, supports an array object passed to "a" instead of a list.',
args: [
['p', 'prompt for query (or nested query) output; default: Select'],
['l', 'list of options to use as query rows; can be pipe-separated labels, or a series of pipe-seperated (label),(value) options'],
['n', 'whether to nest the query, replacing the three characters: } , | with their html entities only where they are not involved in an attribute or ability lookup'],
]
},
nest: {
msg: 'Renders existing text (s) so that it does not break a bounding query; replaces three characters ( } , | ) where they are not involved in an attribute or ability lookup.',
args: [
['s', 'the string on which to perform the replacement operation']
]
},
getrow: {
msg: 'Retrieves a row from the designated menu (or default menu if none was specified in the first argument).',
args: [
['r', 'menu element to retrieve; menu entry must have that element available; default: row\
default menu includes options for "row" and "elem", though other menus might provide more'],
['c', 'color override for the row; obviates fade arg (f) for this row'],
['f', 'a number between 0 and 1 representing how much to fade the overall theme color designated for the menu; \
default: (none), but input that does not interpret to a value between 0 and 1 will be treated as .5'],
['t', 'title text for the row'],
['s', 'source text for the row contents']
]
},
msgbox: {
msg: 'Outputs a message box to chat (like what you are reading, now) with a title (t), message (c), and button elements (btn), if desired.',
args: [
['c', 'chat contents; in other words, the message portion of the message box'],
['t', 'title for the message box'],
['btn', 'secondary text area; putting buttons here will keep them visually separated from your message text']
]
}
}; // library of available help text as an object of { msg: string, args: [ [prop, explanation], [prop, explanation]] }
const availMenus = { // library of available menus
default: { tbl: menutable, row: menurow, color: '#4b688b', fade: .5, elem: menuelem }
};
const runInternal = (f, lib = "availFuncs") => {
let libObj = {
availFuncs: availFuncs
};
return libObj[lib][f];
};
const registerRule = (...r) => { // pass in a list of functions to get them registered to the availFuncs library
r.forEach(f => {
if (f.name) {
if (availFuncs[f.name]) {
log(`IA Function Registration: Name collision detected for ${f.name}. Last one loaded will win.`);
delete availHelp[f.name];
}
availFuncs[f.name] = f;
}
});
};
const registerMenu = (m) => { // pass in a schema object
if (availMenus[m.name]) log(`IA Menu Registration: Name collision detected for ${m.name}. Last one loaded will win.`);
availMenus[m.name] = m;
};
const registerHelp = (h) => {
Object.keys(h).forEach(f => {
if (availHelp[h[f]]) log(`IA Help Registration: Name collision detected for ${f}. Last one loaded will win.`);
availHelp[f] = h[f];
});
};
// ==================================================
// FIRST ARGUMENT FUNCTIONS (MAPARG)
// ==================================================
// these functions are for special values provided to the first argument
// each function should be built using destructuring assignment, which will provide immediate !!arg availability to each parameter
// each function should return an object in the form of { ret: compiled text, safe: true/false, suspend: true/false }
// once built, enter it in the library object mapArgFuncs to make it available to users
const processHandout = ({ args: args, m: m, theSpeaker: theSpeaker, cfgObj: cfgObj }) => {
let retObj = { ret: "", safe: true, suspend: true };
// available functions to the handout process
const rename = ({ // !ia --handout#rename{{...}}
oldn: oldn, // old handout name, if provided
oldid: oldid, // old handout id, if provided
nn: nn = "", // new handout name
cfgObj: cfgObj, // config settings
} = {}) => {
let api = `http://journal.roll20.net/handout/`;
if (!nn) { // no new name provided
msgbox({ c: "Unable to rename: no new name provided.", t: "ERROR", send: true });
} else {
let ho,
btn = "",
msg = "";
if (findObjs({ type: 'handout', name: nn }).length > 0) { // handout with new name already exists
msg = "Handout already exists with the new name.";
} else if (oldn) { // user provided old handout name
ho = findObjs({ type: 'handout', name: oldn });
if (ho.length < 1) {
msg = "No handout found with that name.";
} else if (ho.length > 1) {
msg = "Multiple handouts have that name. You're going to have to figure this out on your own.";
btn = ho.reduce((a, v, i) => { return a + btnAPI({ bg: cfgObj.bg, api: api + v.id, label: `(${i + 1}) ${v.get('name').replace(/iaconfig-/i, "")}`, css: cfgObj.css, r20style: true }) + ' ' }, "");
}
} else if (oldid) { // user provided old handout id
ho = findObjs({ type: 'handout', id: oldid });
if (ho.length < 1) {
msg = "No handout found with that id.";
}
}
if (msg) { // if there is a message (an error), output it and exit
msgbox({ c: msg, t: "ERROR", send: true, btn: btn, wto: theSpeaker.localName });
return retObj;
}
ho[0].set({ name: nn }); // if we get this far, it's safe to rename the handout
handleConfig(ho[0], { name: oldn }); // the rename won't trigger the event, so we have to call this manually
msgbox({ c: "Config file renamed successfully. Config contents are written asynchronously to state, so this button may still appear under the previous/default configuration.", t: "CONFIG RENAMED", btn: btnAPI({ bg: cfgObj.bg, css: cfgObj.css, api: api + ho[0].id, label: 'Open', r20style: true }), send: true, wto: theSpeaker.localName });
}
return retObj;
};
const make = ({ // !ia --handout#make{{!!doc#...}}
theSpeaker: theSpeaker,
cfgObj: cfgObj,
doc: doc = "",
} = {}) => {
if (!doc) return retObj;
let docarg;
let apicmd;
let api;
[doc, docarg = ''] = doc.split("#"); // doc will have "help", or "config", etc.; docarg will have the next segment -- currently only 2 #-separated segments allowed; docarg will be split by pipes, if necessary
docarg = docarg.split("|");
if (doc === "help") { // !ia --handout#make{{!!doc#help#(overwrite)}}
let helpho = findObjs({ type: "handout", name: `IA Help` })[0];
if ((!docarg.length || !['t', 'true'].includes(docarg[0])) && helpho) { // help handout already exists, and the overwrite command was not provided
apicmd = '!ia --handout#make{{!!doc#help#true}}';
msgbox({ c: "Help handout already exists (IA Help). Overwrite?", t: "HELP EXISTS", btn: btnAPI({ bg: cfgObj.bg, css: cfgObj.css, api: apicmd, label: 'Yes' }), send: true, wto: theSpeaker.localName });
return retObj;
}
let helptemplate = `<h2>__helpheader__</h2<h4>type: __type__</h4><br><h3>Usage</h3>__msg__<h3>__argheader__</h3><table style="width: 100%;">__argrows__</table><br>`;
let helpentries = Object.keys(availHelp).sort((a, b) => a > b ? 1 : -1)
.map(a => {
return {
origname: a,
dispname: availFuncs[a] ? a : a.replace(getHelpArg(), ''),
type: availFuncs[a] ? 'function' : a.indexOf(getHelpArg()) > -1 ? 'arg options' : 'unknown',
msg: availHelp[a].msg,
argtype: availFuncs[a] ? 'ARGUMENTS' : a.indexOf(getHelpArg()) > -1 ? 'OPTIONS' : 'unknown',
args: availHelp[a].args.map(o => {
let h = /gethelp\(([^)]+)\)/g.exec(o[1]);
if (h) return `<tr><td style="width:30px;">${o[0]}</td><td><span style="font-style:italic;">see help entry for <span style="font-style:italic;">${h[1].replace(getHelpArg(),'')}</span></td>`;
return `<tr><td style="width:30px;">${o[0]}</td><td>${o[1]}</td>`;
})
.join("")
};
});
let helpoutput = helpentries.map(h => helptemplate.replace('__helpheader__', h.dispname).replace('__type__', h.type).replace('__msg__', h.msg).replace('__argheader__', h.argtype).replace('__argrows__', h.args));
if (!helpho) helpho = createObj('handout', { name: 'IA Help', inplayerjournals: 'all', archived: false });
helpho.set({ notes: helpoutput });
api = `http://journal.roll20.net/handout/${helpho.id}`;
btn = btnAPI({ bg: cfgObj.bg, api: api, label: `Open`, css: cfgObj.css, r20style: true });
msgbox({ c: "Help handout named 'IA Help' created.", t: "HANDOUT CREATED", btn: btn, send: true, wto: theSpeaker.localName });
return retObj;
} else { // !ia --handout#make{{!!doc#config#player|character|...}}
if (doc === 'config') {
if (!docarg.length) {
msgbox({ c: "No config document specified.", t: "INVALID STRUCTURE", send: true, wto: theSpeaker.localName });
return retObj;
}
let hoObj, defcfg, corp, cby, btn = [];
docarg.forEach(c => {
if (c !== 'global') {
if (charFromAmbig(c)) {
corp = charFromAmbig(c);
cby = corp.get('controlledby');
corp = corp.get('name');
}
else if (playerFromAmbig(c)) {
corp = playerFromAmbig(c);
cby = corp.id;
corp = corp.get('displayname');
}
else {
corp = c;
cby = '';
}
} else {
corp = 'global';
cby = getAllGMs().map(g => g.id).join(",");
}
if (corp === 'global' && !playerIsGM(m.playerid)) {
msgbox({ c: "You must be a GM to create the global config.", t: "GM RIGHTS REQUIRED", send: true, wto: theSpeaker.localName });
} else {
hoObj = findObjs({ type: "handout", name: `IAConfig-${corp}` })[0] || { fail: true };
if (Object.prototype.hasOwnProperty.call(hoObj, "fail")) { // only write the handout if one doesn't exist
defcfg = `<pre>${htmlCoding('<!-- BEGIN CONFIG -->')}\n`;
defcfg += htmlCoding(`--bg#${bgcolor}`) + `\n`;
defcfg += htmlCoding(`--css#padding:4px;`) + `\n`;
defcfg += `${htmlCoding('<!-- END CONFIG -->')}</pre>`;
hoObj = createObj("handout", { name: `IAConfig-${corp}`, inplayerjournals: 'all', controlledby: cby });
hoObj.set('notes', defcfg);
api = `http://journal.roll20.net/handout/${hoObj.id}`;
btn.push(btnAPI({ bg: cfgObj.bg, api: api, label: corp, css: cfgObj.css, r20style: true }));
handleConfig(hoObj, { name: hoObj.get('name') }); // get it into state
}
}
});
if (btn.length) {
msgbox({ c: "The following config files were created. Click any to open.", t: "HANDOUT CREATED", btn: btn.join(' '), send: true, wto: theSpeaker.localName });
}
}
}
return retObj;
};
// available function library, mapping the text supplied to the internal function
const funcTable = {
rename: rename,
make: make,
};
let funcregex = getMapArgFuncRegex(funcTable);
// group 1: function from function{{arguments}}
// group 2: arguments from function{{arguments}}
let f = funcregex.exec(args);
if (f) {
retObj = funcTable[f[1]]({
...(Object.fromEntries((f[2] || "").split("!!") // this turns anything provided with a !! prefix into an available parameter for the receiving function
.filter((p) => { return p !== ""; })
.map(splitArgs)
.map(joinVals))),
theSpeaker: theSpeaker,
m: m,
cfgObj: cfgObj,
});
} else {
msgbox({ c: 'Unrecognized or poorly formatted mapArg command.', t: "ERROR", send: true, wto: theSpeaker.localName });
}
return retObj;
};
const runHelp = ({ args: f, m: m, theSpeaker: theSpeaker, cfgObj: cfgObj }) => {
let retObj = { ret: "", safe: true, suspend: true };
let { msg: msg = "No help specified", args: fargs = [["n/a", "No arguments specified"]] } = availHelp[f] || {}; // destructuring assignment of the help object, if present (empty object if not)
let rows = fargs.map(a => `<tr><td style="vertical-align:top;"> ${a[0]}</td><td> </td><td>${a[1]}</td></tr>`).join("");
rows = rows.replace(/gethelp\(([^)]+)\)/g, ((m,g) => btnAPI({ bg: cfgObj.bg, label: 'Help', api: `!ia --help#${g}`, css: cfgObj.css })));
let tbl = `<table style="width:100%;">${rows}</table>`;
let subhdr;
if (availFuncs[f]) { // if we detect f as a function
subhdr = 'ARGUMENTS';
} else { // if it's not a function, treat it as options for an argument
subhdr = 'OPTIONS';
f = f.replace(getHelpArg(), '').toUpperCase();
}
msg += `<br><br>${subhdr}:<br>${tbl}`;
msgbox({ c: msg, t: `HELP: ${f}`, send: true, wto: theSpeaker.localName });
return retObj;
};
const processmenu = ({ args: args, m: m, theSpeaker: theSpeaker, cfgObj: cfgObj }) => {
let retObj = ({ ret: "", safe: true, suspend: true }); // suspend first set to true until we know we have a menu
let [menu, color, fade] = args.split("|"); // we're not guaranteed to get all three arguments, so the rest of the code will have to build in defaults if we don't
menu = menu || 'default';
if (!Object.prototype.hasOwnProperty.call(availMenus, menu)) {
if (Object.prototype.hasOwnProperty.call(availMenus, 'default')) {
menu = 'default';
msgbox({ c: `menu: Couldn't find a menu named ${menu}, using default menu instead.`, t: 'USING DEFAULT MENU', send: true, wto: theSpeaker.localName });
} else {
msgbox({ c: `menu: Couldn't find a menu named ${menu}; no default menu available.`, t: 'NO DEFAULT MENU', send: true, wto: theSpeaker.localName });
return retObj;
}
}
color = validateHexColor(color || '', '4b688b');
fade = (isNaN(Number(fade)) || Number(fade) > 1 || Number(fade) < 0) ? .5 : Number(fade); // if it's not a number, or it's a number outside of the 0-1 range, make it .5
// we should not have valid (if defaulted) menu, color, and fade
state.ia[theSpeaker.localName] = state.ia[theSpeaker.localName] || {};
state.ia[theSpeaker.localName].menu = state.ia[theSpeaker.localName].menu || {};
Object.assign(state.ia[theSpeaker.localName].menu, availMenus[menu]);
Object.assign(state.ia[theSpeaker.localName].menu, { menu, color, fade });
let textcolor = getTextColor(color);
let altcolor = getAltColor(color);
let alttextcolor = getTextColor(altcolor);
retObj.ret = availMenus[menu].tbl // return the table structure
.replace(/\bmaincolor\b/g, color)
.replace(/\bmaintextcolor\b/g, textcolor)
.replace(/\baltcolor\b/g, altcolor)
.replace(/\balttextcolor\b/g, alttextcolor);
retObj.suspend = false; // let the process continue
return retObj;
};
const processLog = ({ args: args, m: m, theSpeaker: theSpeaker, cfgObj: cfgObj }) => {
let retObj = { ret: "", safe: true, suspend: true };
state.ia = state.ia || {};
state.ia.logparser = state.ia.logparser || false;
state.ia.logparser = state.ia.logparser ? false : true;
log(`INSERTARG: Event logging ${state.ia.logparser ? 'initiated' : 'terminated'} by ${theSpeaker.localName}`);
msgbox({ c: `Logging has been turned ${state.ia.logparser ? 'ON. Go to your console in your browser or in your script library to see the logged events of a call to InsertArg.' : 'OFF.'}`, t: `LOGGING`, send: true, wto: theSpeaker.localName });
return retObj;
}
// ------------- FIRST ARG FUNCTION LIBRARY --------------
const mapArgFuncs = {
handout: processHandout,
help: runHelp,
menu: processmenu,
log: processLog
};
// ==================================================
// HANDLE CONFIG
// ==================================================
const horx = /^iaconfig-(.+)$/i; //group 1: forName from iaconfig-forName
const handleCharNameChange = (character, prev) => {
// this listens for a character name change, and checks whether there is a configuration file that needs to be managed
let oldrx = new RegExp(`\\s*(iaconfig-)(${escapeRegExp(prev.name).replace(/\s/g, `\\s`)})$`);
// group 1: iaconfig- from iaconfig-prevname
// group 2: prevName from iaconfig-prevname
let newrx = new RegExp(`\\s*(iaconfig-)(${escapeRegExp(character.get('name')).replace(/\s/g, `\\s`)})$`);
// group 1: iaconfig- from iaconfig-characterame
// group 2: charactername from iaconfig-charactername
let oldhos = findObjs({ type: "handout" }).filter(h => oldrx.test(h.get('name')));
if (oldhos.length === 0) return; // no config handouts found
oldhos.forEach(h => log(h.get('name')));
state.ia[character.get('name')] = state.ia[character.get('name')] || {};
state.ia[character.get('name')].cfgObj = state.ia[character.get('name')].cfgObj || {};
Object.assign(state.ia[character.get('name')], state.ia[prev.name] || { cfgObj: Object.assign({}, state.ia.global.cfgObj) });
let cfgObj = {};
Object.assign(cfgObj, state.ia[character.get('name')].cfgObj);
let msg = "",
btn = "",
api = "",
newhos = findObjs({ type: "handout" }).filter(h => newrx.test(h.get('name')));
if (newhos.length + oldhos.length > 1) { // detect conflicts
msg = `That character has multiple script configurations, either under ${character.get('name')} or under ${prev.name}. You should only keep one, and it should be named IAConfig-${character.get('name')}. Open handouts for comparison?<br>`;
api = `http://journal.roll20.net/handout/`;
btn = oldhos.reduce((a, v, i) => { return a + btnAPI({ bg: cfgObj.bg, api: api + v.id, label: `(${i + 1}) ${v.get('name').replace(/iaconfig-/i, "").replace(/\s/g, ' ')}`, css: cfgObj.css, r20style: true }) + ' ' }, "");
btn = newhos.reduce((a, v, i) => { return a + btnAPI({ bg: cfgObj.bg, api: api + v.id, label: `(${i + 1}) ${v.get('name').replace(/iaconfig-/i, "").replace(/\s/g, ' ')}`, css: cfgObj.css, r20style: true }) + ' ' }, btn);
} else { // only get here if there is a config for the old name but not the new (ie, no collision)
let o = oldrx.exec(oldhos[0].get('name'));
msg = `${character.get('name')} had an InsertArgs script configuration as ${prev.name}. Do you want to rename the config to match the new name?<br>`;
api = `!ia --handout#rename{{!!oldid#${oldhos[0].id} !!nn#${o[1] + character.get('name')}}}`;
btn = btnAPI({ bg: cfgObj.bg, api: api, label: "Rename", css: "min-width: 25px;" + cfgObj.css });
}
msgbox({ c: msg, t: "MANAGE CONFIG FILE", btn: btn, send: true, wto: character.get('name') });
}
const handleConfig = (cfgho, prev) => {
// listens for handout changes, detects config handouts, and copies those into the state variable for the appropriate speaker
// calls cfgIntoState, which calls parseConfig
// 4 cases to manage: config file named to non-config, non-config named to config, config named to another config, or changes to notes
let honame = cfgho.get('name');
if (!(horx.test(honame) || horx.test(prev.name) )) return; // if this wasn't a config template at some point in the change, we don't care
let honamepart;
if (honame !== prev.name) { // name was changed
if (horx.test(prev.name)) { // if the old name is a config file
handleConfigDestroy({ get: (p) => { if (p === "name") return prev.name; else return ""; } }); // call our garbage collection to remove it from state
}
if (horx.test(honame)) { // if the new name is a config file
honamepart = horx.exec(honame)[1]; // get the character name portion
cfgho.get('notes', (notes) => { cfgIntoState({ charname: honamepart, notes: notes }) }); // baseline the config in state and parse the config handout
}
} else { // names match, so either the notes were changed or this is the initialization
honamepart = horx.exec(honame)[1]; // extract the character name portion, convert to lowercase
cfgho.get('notes', (notes) => { cfgIntoState({ charname: honamepart, notes: notes }) });
}
};
const cfgIntoState = ({ charname: c, notes: n }) => {
state.ia[c] = state.ia[c] || {}; // initialize the speaker's object in the state
state.ia[c].cfgObj = state.ia[c].cfgObj || {}; // initialize the config object in the speaker's state
Object.assign(state.ia[c].cfgObj, state.ia.global.cfgObj); // baseline the cfgObj to the global configuration
Object.assign(state.ia[c].cfgObj, parseConfig(n)); // parseConfig returns an object of properties to apply to the cfgObj
};
const parseConfig = (notes) => {
let cfgObj = Object.assign({}, state.ia.global.cfgObj || getDefaultConfigObj()); // make local copy of the global settings; this will be the starting point for further configurations
notes = notes.replace(new RegExp(/&|<|>|\\\\/, 'gi'), (e) => { return { "&": "&", "<": "<", ">": ">", "\\": "\\" }[e]; }); // decode specific html entities that the handouts encode
// get config components into the cfgObj
let m = /(<!--\sBEGIN\sCONFIG\s-->.*?<!--\sEND\sCONFIG\s-->)/gmis.exec(notes);
// group 1: config section delimted by config tags
if (m) {
let settings = ["css", "bg"], // settings available in the config section
sdata; // to hold the data from each setting read out of the config
settings.map(s => {
sdata = new RegExp(`^--${s}#(.*?)(?=\r\n|\r|\n)`, 'gmis').exec(m[1]);
//group 1: user input for the setting from --setting#user input
if (sdata) {
cfgObj[s] = sdata[1];
}
});
}
return cfgObj;
};
const handleConfigDestroy = (cfgho) => {
// listens for a handout deletion
// if a config handout is deleted, revert the associated state configuration to blank/starting value
let honame = cfgho.get('name');
if (!horx.test(honame)) return; // if this isn't a config template, we don't care
let honamepart = horx.exec(honame)[1].toLowerCase(); // extract the character name portion, convert to lowercase
if (honamepart !== "global") { // if this is an individual config, delete it from state
state.ia[honamepart] = state.ia[honamepart] || {};
state.ia[honamepart].cfgObj;
} else { // if this is the global config, reassign the global
state.ia.global = state.ia.global || {};
state.ia.global.cfgObj = state.ia.global.cfgObj || {};
state.ia.global.cfgObj = getDefaultConfigObj();
}
let duphos = findObjs({ type: 'handout', name: cfgho.get('name') }); // see if there is another config of that same name we should load, now
if (duphos.length > 0) {
let replacecfg = duphos[0];
replacecfg.get('notes', (notes) => { cfgIntoState({ charname: honamepart, notes: notes }) });
}
};
const getIndivConfig = (theSpeaker, statesource) => {
if (!statesource) statesource = state.ia[theSpeaker.localName] || state.ia.global;
return Object.assign(getDefaultConfigObj(), statesource.cfgObj);
};
// ==================================================
// HANDLE INPUT
// ==================================================
const handleInput = (msg_orig) => {
if (msg_orig.type !== "api") return;
let apicatch = "";
if (/^!(?:ia|insertarg|insertargs)(?:\s|$)/.test(msg_orig.content)) apicatch = 'ia';
if (apicatch === "") return;
let theSpeaker = getTheSpeaker(msg_orig);
let args = msg_orig.content.split(/\s+--/)
.slice(1) // get rid of api handle
.map(splitArgs) // split each arg (foo:bar becomes [foo, bar])
.map(joinVals); // if the value included a # (the delimiter), join the parts that were inadvertently separated
// get the player or character's configuration (if present), or the global
let cfgObj = getIndivConfig(theSpeaker), // copy the settings for this run (either from the speaker's state or the global configuration)
cmdline = "",
safechat = true,
retObj = {};
if (!args.length) { // if there are no arguments, display the config
displayIAConfig(theSpeaker, cfgObj);
return;
}
let mapArg = args.shift(); // assign the first arg to mapArg
if (!['button', 'chat', 'load', 'menu', 'whisper', ...Object.keys(mapArgFuncs)].includes(mapArg[0])) { // test for recognized first argument
msgbox({ c: `First argument must come from this list:<br>button, chat, load, menu, whisper, ${Object.keys(mapArgFuncs).join(", ")}<br>Use a # to include an ability source for the command line.`, t: "UNRECOGNIZED ARGUMENT", send: true, wto: theSpeaker.localName });
return;
}
let cmdSrc, allowedPlayers;
if (mapArg[1] !== "" && !Object.keys(mapArgFuncs).includes(mapArg[0])) { // value of mapArg is either (source) or character|(source)
cmdSrc = abilFromAmbig(mapArg[1]) || macroFromAmbig(mapArg[1].replace(/^macro\|/, '')); // get either the ability or macro source
if (!cmdSrc && theSpeaker.speakerType === 'character') cmdSrc = abilFromAmbig(`${theSpeaker.id}|${mapArg[1]}`); // if the value was a object name (rather than id) and the speaker is a character, look for that combination
if (!cmdSrc) {
msgbox({ c: `Could not find ${mapArg[1]}.`, t: "UNKNOWN SOURCE", send: true, wto: theSpeaker.localName });
return;
}
if (cmdSrc.get('type') === 'ability') {
allowedPlayers = getObj('character', cmdSrc.get('characterid')).get('controlledby');
} else {
allowedPlayers = cmdSrc.get('visibleto');
}
if (!allowedPlayers.split(/\s*,\s*/).includes(msg_orig.playerid) && !allowedPlayers.split(/\s*,\s*/).includes('all') && !playerIsGM(msg_orig.playerid)) {
msgbox({ c: `You don't have rights to that source object.`, t: "ERROR", send: true, wto: theSpeaker.localName });
return;
}
cmdline = cmdSrc.get('action'); // works for both abilities and macros
} else { // empty mapArg
cmdline = 'show';
}
// CONFIG OBJECT ARGUMENTS
args.filter((a) => { return Object.keys(cfgObj).includes(a[0].toLowerCase()) && !["table", "row"].includes(a[0].toLowerCase()); }) // deal with only the args recognized as part of the cfgObj, but not table & row
.map((a) => {
cfgObj[a[0].toLowerCase()] = a[1];
});
cfgObj.bg = validateHexColor(cfgObj.bg);
// FIRST ARGUMENT FUNCTIONS
if (Object.prototype.hasOwnProperty.call(mapArgFuncs, mapArg[0].toLowerCase())) { // test if mapArg has an associated function in mapArgFuncs
retObj = mapArgFuncs[mapArg[0]]({ // call the associated function with destructuring assignment on the receiving end
args: mapArg[1], // parsing handled on receiving end (minimizes having to enter them individually in 2 places)
theSpeaker: theSpeaker,
m: msg_orig,
cfgObj: cfgObj,
});
if (retObj.suspend === true) return; // should this end further processing?
cmdline = retObj.ret || cmdline;
safechat = !retObj.safe ? false : safechat; // trip safechat if necessary
}
// HOOK ARGUMENTS
args.filter( a => !Object.keys(cfgObj).includes(a[0].toLowerCase())) // deal with only the custom hooks (not part of cfgObj)
.map( a => {
retObj = cmdLineParser({ cmd: decodeUrlEncoding(a[1]), funcObj: availFuncs, m: msg_orig, cfgObj: cfgObj, theSpeaker: theSpeaker }); // recursive parser to detect and condense internal functions
cmdline = replaceEngine(cmdline, retObj, a); // insert the replacement text as specified into the cmdline around/in the hook
return;
});
// OUTPUT RESULTS
safechat = !/(?:@|\?){/gm.test(cmdline);
cmdline = internalCallCoding(cmdline, false);
// if user wants to ouput to the chat but it's not safe to chat, change to button
if (['chat','whisper','menu',...Object.keys(mapArgFuncs)].includes(mapArg[0]) && !safechat) mapArg[0] = "button";
if (!['button','load'].includes(mapArg[0])) {
sendChat(mapArg[0] === "whisper" ? `API` : theSpeaker.chatSpeaker, (['whisper', 'menu'].includes(mapArg[0]) ? `/w "${theSpeaker.localName}" ` : "") + cmdline);
}
else {
let outputStore;
if (/^macro\|/i.test(cfgObj.store)) { // user intends this to be a macro (useful for when chatting as a character, but intends to store a macro)
outputstore = macroFromAmbig(cfgObj.store.replace(/^macro\|/, '')) || createObj('macro', { name: cfgObj.store.replace(/^macro\|/, ''), playerid: msg_orig.playerid, visibleto: msg_orig.playerid });
} else { // user did not explicitly call for a macro
outputStore = abilFromAmbig(cfgObj.store) || macroFromAmbig(cfgObj.store); // get either the ability or macro source object
if (!outputStore && theSpeaker.speakerType === 'character') outputStore = abilFromAmbig(`${theSpeaker.id}|${cfgObj.store}`);
if (!outputStore) { // we need to create the object
if (theSpeaker.speakerType === 'character') outputStore = createObj('ability', { name: cfgObj.store, characterid: theSpeaker.id });
else outputStore = createObj('macro', { name: cfgObj.store, playerid: msg_orig.playerid, visibleto: msg_orig.playerid });
}
}
outputStore.set({ action: cmdline });
if (mapArg[0] === "button") {
sendChat("API", `/w "${theSpeaker.localName}" ${btnElem({ ...cfgObj, charname: theSpeaker.localName })}`);
} else {
msgbox({ c: `${outputStore.get('name')} is loaded and ready.`, t: 'COMMAND LOADED', btn: btnElem({ ...cfgObj, charname: theSpeaker.localName }), send: true, wto: theSpeaker.localName });
}
}
};
const replaceEngine = (cmdline, retObj, a) => {
let hookrx = /^(?<before>\^\^\+\+|\+\+\^\^|\^\^|\+\+)?(?<hook>.+?)(?<after>\^\^\+\+|\+\+\^\^|\^\^|\+\+)?$/g;
// before: ^^, ++, ^^++, or ++^^ at the beginning of [before][hook][after]
// hook : everything between [before] and [after] in [before][hook][after]
// after : ^^, ++, ^^++, or ++^^ at the end of [before][hook][after]
let delimrx = /^(.+?)\|([^|].*$|\|$)/g;
// group 1: hook from hook|delim
// group 2: delim from hook|delim
let d = "", hook = "", reparray, pos = 0;
h = hookrx.exec(a[0]); // gets the sets of info
hookrx.lastIndex = 0;
h.breakout = { // break the sets down further
before: h.groups.before && h.groups.before.indexOf("^") > -1,
after: h.groups.after && h.groups.after.indexOf("^") > -1,
lazy: h.groups.before && h.groups.before.indexOf("+") > -1,
greedy: h.groups.after && h.groups.after.indexOf("+") > -1,
hook: h.groups.hook,
};
if (h.breakout.before) h.breakout.after = undefined;
hook = h.breakout.hook || "";
if (h.breakout.lazy && delimrx.test(hook)) {
delimrx.lastIndex = 0;
[, hook, d] = delimrx.exec(h.breakout.hook);
delimrx.lastIndex = 0;
}
d = (d.indexOf("`") === 0 && d.charAt(d.length - 1) === "`" ? d.slice(1, d.length - 1) : d);
if (hook === 'cmd') hook = cmdline;
if (h.breakout.lazy) { // LAZY
reparray = retObj.ret.split(d);
if (h.breakout.before) { // lazy + before
cmdline = cmdline.replace(new RegExp(escapeRegExp(hook), 'g'), (m => [reparray.shift() || "", m].join("")));
} else if (h.breakout.after) { // lazy + after
cmdline = cmdline.replace(new RegExp(escapeRegExp(hook), 'g'), (m => [m, reparray.shift() || ""].join("")));
} else { // lazy + replace
cmdline = cmdline.replace(new RegExp(escapeRegExp(hook), 'g'), (m => reparray.shift() || m));
}
} else if (h.breakout.greedy) { // GREEDY
if (h.breakout.before) { // greedy + before
pos = cmdline.indexOf(hook);
if (pos > -1) cmdline = [cmdline.slice(0, pos), retObj.ret, cmdline.slice(pos)].join("");
} else if (h.breakout.after) { // greedy + after
pos = cmdline.indexOf(hook);
if (pos > -1) {
pos += hook.length;
cmdline = [cmdline.slice(0, pos), retObj.ret, cmdline.slice(pos)].join("");
}
} else { // greedy + replace
cmdline = cmdline.replace(hook, retObj.ret);
}
} else { // NEITHER GREEDY NOR LAZY
if (h.breakout.before) { // before
cmdline = cmdline.replace(new RegExp(escapeRegExp(hook), 'g'), (m => [retObj.ret, m].join("")));
} else if (h.breakout.after) { // after
cmdline = cmdline.replace(new RegExp(escapeRegExp(hook), 'g'), (m => [m, retObj.ret].join("")));
} else { // replace
cmdline = cmdline.replace(new RegExp(escapeRegExp(hook), 'g'), retObj.ret);
}
}
return cmdline;
};
const cmdLineParser = ({
cmd: cmd, // command line to process
funcObj: obj, // library object of functions to detect/run
m: m, // message object from chat
cfgObj: cfgObj, // config object
theSpeaker: theSpeaker // the speaker from chat message
} = {}) => {
let indent = 0,
index = 0,
safe = true;
const nestlog = (stmt, ilvl = indent) => {
if (state.ia && state.ia.logparser === true) {
let l = `PARSER: ${Array(ilvl + 1).join("==")}${stmt}`;
// l = l.indexOf(":") ? '<span style="color:yellow;">' + l.slice(0, l.indexOf(":")) + ':</span>' + l.slice(l.indexOf(":") + 1) : l;
log(l);
};
};
const getFuncRegex = (obj, e = false) => {
return new RegExp(`^${e ? '`' : ''}(${Object.keys(obj).join("|")}){{(?=}}|!!)`, 'i');
// group 1: func from func{{arg*}}
// if escaped, a tick (`) must preceed the func
};
let funcrx = getFuncRegex(obj),
efuncrx = getFuncRegex(obj, true),
textrx = /^(.*?)(?:}}|\s+!!|$)/, // group 1: e from e !! --OR-- e}} --OR-- e{end of string}
flagrx = /^\s*!!([^\s)]+)(?=\s|}})/, // group 1: flag from !!flag
keyrx = /^\s*!!([^\s#)]+)#[^\s]+/; // group 1: key from !!key#anything
const firstOf = (...args) => {
let ret;
args.find(f => ret = f(), ret);
return ret;
};
const zeroOrMore = (f) => {
let ret = "";
let i = 0;
for (; ;) {
indent++;
temp = f();
indent--;
if (!temp) {
nestlog(`ZERO: Has built: ${ret}`);
return ret;
}
ret += temp;
}
};
const val = () => {
let bt = index;
let loccmd = cmd.slice(index);
nestlog(`VAL RECEIVES: ${loccmd}`);
indent++;
let ret = firstOf(func, efunc, text);
indent--;
if (bt === 0) {
if (cmd.slice(index).length) {
nestlog(`VAL: Is getting the rest: ${cmd.slice(index)}`);
}
ret = ret + cmd.slice(index); // if this is the top level recursion and there is still something to grab, grab it
}
return ret;
};
const func = () => {
let loccmd = cmd.slice(index);
let f = funcrx.exec(loccmd);
if (f) {
nestlog(`FUNC DETECTS: ${f[1]}`)
let lp = /{{/.exec(loccmd).index;
index += lp + 2;
indent++;
let params = zeroOrMore(arg).trimLeft();
indent--;
if (cmd.charAt(index) === '}' &&
index + 1 < cmd.length &&
cmd.charAt(index + 1) === '}') {
nestlog(`FUNC: Running ${f[1]}{{${params}}}`);
let retObj = obj[f[1]]({
...(Object.fromEntries((params || "")
.split("!!")
.filter(p => p !== "")
.map(a => a.split("#"))
.map(a => [a.slice(0)[0], a.slice(1).join("#").trim()]))),
m: m,
cfgObj: cfgObj,
theSpeaker: theSpeaker
});
index++;
index++;
nestlog(`FUNC: Returning ${retObj.ret}`);
if (!retObj.safe) safe = false;
return retObj.ret;
}
}
return null;
};
const efunc = () => {
let bt = index;
let loccmd = cmd.slice(index);
let f = efuncrx.exec(loccmd);
if (f) {
nestlog(`EFUNC DETECTS: ${f[1]}`)
let lp = /{{/.exec(loccmd).index;
let pos = lp + 1,
pairs = 1,
obraced = 0,
cbraced = 0;
while (pairs !== 0 && pos < loccmd.length) {
pos++;
if (loccmd.charAt(pos) === '{') {
if (obraced === pos - 1) {
pairs++;
obraced = 0;
} else {
obraced = pos;
}
} else if (loccmd.charAt(pos) === '}')
if (cbraced === pos - 1) {
pairs--;
cbraced = 0;
} else {
cbraced = pos;
}
}
index += pos + 2;
let ret = cmd.slice(bt + 2, index);
nestlog(`EFUNC: Returning ${ret}`);
return ret;
}
return null;
};
const text = () => {
let loccmd = cmd.slice(index);
let tb = textrx.exec(loccmd);
if (tb) {
nestlog(`TEXT DETECTS: ${tb[1]}`);
index += tb[1].length;
return tb[1];
}
return null;
};
const arg = () => {
nestlog(`ARG RECEIVES: ${cmd.slice(index)}`);
indent++;
let ret = firstOf(key, flag);
indent--;
if (ret) return ret;
nestlog(`ARG: Returning null.`);
return null;
};
const key = () => {
let loccmd = cmd.slice(index);
let k = keyrx.exec(loccmd);
if (k) {
nestlog(`KEY DETECTS: ${k[1]}`, indent);
let hindex = loccmd.indexOf("#");
index += hindex + 1;
indent++;
let ret = ' !!' + k[1] + '#' + val();
indent--;
return ret;
}
return null;
};
const flag = () => {
let loccmd = cmd.slice(index);
let f = flagrx.exec(loccmd);
if (f) {
nestlog(`FLAG DETECTS: ${f[1]}`);
let offset = loccmd.indexOf(f[1]) + f[1].length;
index += offset;
return ` !!${f[1]}#true`;
}
return null;
};
return { ret: val(cmd), safe: safe };
};
const registerEventHandlers = () => {
on('chat:message', handleInput);
on("change:handout", handleConfig);
on("destroy:handout", handleConfigDestroy);
on("change:character:name", handleCharNameChange)
};
on('ready', () => {
versionInfo();
logsig();
registerEventHandlers();
delete state.ia;
state.ia = {
global: {
cfgObj: {}
}
};
Object.assign(state.ia.global.cfgObj, getDefaultConfigObj()); // explicitly write the defaults, because if there is a global config it will overwrite in a moment
let cfgglobal = findObjs({ type: "handout" }).filter((h) => { return /^iaconfig-global$/gi.test(h.get('name')) })[0];
if (cfgglobal) {
cfgglobal.get('notes', (notes) => {
if (notes) {
Object.assign(state.ia.global.cfgObj, parseConfig(notes)); // by this time, we've asynchronously obtained the notes, so pass them to the parsing function and assign the result to the state
}
findObjs({ type: "handout" }) // now that the global configuration is in state, process the rest of the config handouts
.filter((h) => { return /^iaconfig-(.+)$/gi.test(h.get('name')); }) // get only the handouts
.filter((h) => { return !/^iaconfig-global$/gi.test(h.get('name')) }) // filter to remove the global
.forEach(h => handleConfig(h, h));
});
} else {
findObjs({ type: "handout" }) // now that the global configuration is in state, process the rest of the config handouts
.filter((h) => { return /^iaconfig-(.+)$/gi.test(h.get('name')); }) // get only the handouts
.filter((h) => { return !/^iaconfig-global$/gi.test(h.get('name')) }) // filter to remove the global
.forEach(h => handleConfig(h, { name: h.get('name') }));
}
});
return {
// public interface
RegisterRule: registerRule,
RegisterMenu: registerMenu,
RegisterHelp: registerHelp,
RunInternal: runInternal,
BtnElem: btnElem,
BtnAPI: btnAPI,
MsgBox: msgbox,
CharFromAmbig: charFromAmbig,
AttrFromAmbig: attrFromAmbig,
AbilFromAmbig: abilFromAmbig,
PlayerFromAmbig: playerFromAmbig,
MacroFromAmbig: macroFromAmbig,
TokenFromAmbig: tokenFromAmbig,
RepeatingFromAmbig: repeatingFromAmbig,
ElemSplitter: elemSplitter,
GetIndivConfig: getIndivConfig,
HTMLCoding: htmlCoding,
Base64: base64,
CMDLineParser: cmdLineParser,
GetHelpArg: getHelpArg,
BuildOutputOptions: buildOutputOptions,
ApplyFilterOptions: applyFilterOptions,
ApplyFormatOptions: applyFormatOptions,
CheckTicks: checkTicks,
InternalCallCoding: internalCallCoding
};
})();
const ialibcore = (() => {
// ==================================================
// VERSION
// ==================================================
const vrs = '1.5.1';
const versionInfo = () => {
const vd = new Date(1606968110464);
log('\u0166\u0166 InsertArg Core Lib v' + vrs + ', ' + vd.getFullYear() + '/' + (vd.getMonth() + 1) + '/' + vd.getDate() + ' \u0166\u0166');
return;
};
const getVrs = () => { return vrs; };
// ==================================================
// UTILITIES
// ==================================================
const deepCopy = (inObject) => { // preserve complex arrays/objects
let outObject, value, key;
if (typeof inObject !== "object" || inObject === null) {
return inObject // Return the value if inObject is not an object
}
// Create an array or object to hold the values
outObject = Array.isArray(inObject) ? [] : {}
for (key in inObject) {
value = inObject[key]
// Recursively (deep) copy for nested objects, including arrays
outObject[key] = deepCopy(value)
}
return outObject
};
const escapeRegExp = (string) => { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); };
// ==================================================
// LIBRARY FUNCTIONS
// ==================================================
const puttext = ({
m: m, // message object (included only because it is being passed and we don't want to output it with the rest)
theSpeaker: theSpeaker, // speaker object (included only because it is being passed and we don't want to output it with the rest)
cfgObj: cfgObj, // config object (included only because it is being passed and we don't want to output it with the rest)
...t // everything else the user passes will go here
}) => {
let retObj = { ret: "", safe: true };
retObj.ret += Object.keys(t).reduce((a, v) => a + ia.CheckTicks(t[v]), "");
return retObj;
};
const getattr = ({
a: a, // attribute id or (character)|(attribute)
v: v = "current", // value wanted (current or max)
h: h = 'false', // whether to encode html characters
theSpeaker: theSpeaker // speaker object
}) => {
let retObj = { ret: "", safe: true };
['m', 'max'].includes(v) ? v = 'max' : v = 'current';
let attr = ia.AttrFromAmbig(a, theSpeaker.id);
if (!attr) {
ia.MsgBox({ c: `getattr: No attribute found for ${a}.`, t: 'NO ATTRIBUTE', send: true, wto: theSpeaker.localName });
return retObj;
}
retObj.ret = ['t', 'true', 'y', 'yes'].includes(h) ? ia.HTMLCoding(attr.get(v)) : attr.get(v);
return retObj;
};
const getabil = ({
a: a, // ability id, or (character)|(ability)
h: h = 'false', // whether to encode html characters
theSpeaker: theSpeaker // speaker object
}) => {
let retObj = { ret: "", safe: true };
let abil = ia.AbilFromAmbig(a, theSpeaker.id);
if (!abil) {
ia.MsgBox({ c: `getabil: No ability found for ${a}.`, t: 'NO ABILITY', send: true, wto: theSpeaker.localName });
return retObj;
}
retObj.ret = ['t', 'true', 'y', 'yes'].includes(h) ? ia.HTMLCoding(abil.get('action')) : abil.get('action');
return retObj;
};
const getmacro = ({
a: a, // macro id or name
h: h = 'false', // whether to encode html characters
theSpeaker: theSpeaker // speaker object
}) => {
let retObj = { ret: "", safe: true };
let mac = ia.macroFromAmbig(a, theSpeaker);
if (!mac) {
ia.MsgBox({ c: `getmacro: No macro found for ${a}.`, t: 'NO MACRO', send: true, wto: theSpeaker.localName });
return retObj;
}
retObj.ret = ['t', 'true', 'y', 'yes'].includes(h) ? ia.HTMLCoding(mac.get('action')) : mac.get('action');
return retObj;
};
const getme = ({
r: r = 'id', // what to return (id or name)
frmt: frmt = '', // formatting options
theSpeaker: theSpeaker // speaker object
}) => {
if (['n', 'name'].includes(r)) r = 'localName';
else if (['c', 'cs'].includes(r)) r = 'chatSpeaker';
else r = 'id';
let formattedme = ia.ApplyFormatOptions(frmt, [{ name: theSpeaker[r] }], 'name')[0].name;
return { ret: formattedme, safe: true };
};
const puttargets = ({
n: n = 1, // number of targets
l: l = "Target", // label for each targeting iteration
r: r = "token_id", // what to return in the targeting call
d: d = " " // delimiter (default is space)
}) => {
d = ia.CheckTicks(d); // check for opening/closing tick marks
let ret = (Array(Number(n)).fill(0)
.reduce((a, v, i) => {
let iter = n > 1 ? ` ${i + 1}` : ``;
return a + `@{target|${l}${iter}|${r}}${d}`;
}, ""))
.replace(new RegExp(`${escapeRegExp(d)}$`), '');
return { ret: ret, safe: false };
};
const getselected = ({
r: r = "id", // what to return (token_id, represents, name)
m: m, // msg object
d: d = " " // delimiter (default is space)
}) => {
let retObj = { ret: "", safe: true };
d = ia.CheckTicks(d); // check for opening/closing tick marks
if (['name', 'n'].includes(r)) r = 'name';
if (['rep', 'r', 'represents'].includes(r)) r = 'represents';
if (!['name', 'represents'].includes(r)) r = 'id';
if (m.selected) retObj.ret = m.selected
.map(t => getObj('graphic', t._id))
.filter(t => (r === 'represents') ? t.get('represents') : true)
.map(t => r === 'id' ? t.id : t.get(r))
.join(d);
return retObj;
};
const getsections = ({
c: c, // character (id, name, or token)
d: d = " ", // delimiter (default is space)
theSpeaker: theSpeaker, // speaker object
f: f = "", // filters
frmt: frmt = '' // formatting options
}) => {
let retObj = { ret: "", safe: true };
d = ia.CheckTicks(d); // check for opening/closing tick marks
let character = ia.CharFromAmbig(c);
if (!character) {
ia.MsgBox({ c: `getsections: No character found for ${c}.`, t: 'NO CHARACTER', send: true, wto: theSpeaker.localName });
return retObj;
}
let sectionRX = new RegExp(`repeating_([^_]*?)_.*$`);
// group 1: section from repeating_section_attributeID_suffix
let sections = findObjs({ type: 'attribute', characterid: character.id }).filter(r => sectionRX.test(r.get('name')));
if (sections.length < 1) {
retObj.ret = msgOutput({ c: `getsections: No repeating sections on the sheet for ${c}.`, t: "NO REPEATING SECTIONS", send: true, wto: theSpeaker.localName });
return retObj;
}
let uniquekeys = [...new Set(sections.map(a => sectionRX.exec(a.get('name'))[1]))]; // extract section (group 1 of the regex), then get an array of unique values
uniquekeys = uniquekeys.map(k => { return { key: k }; });
// ---------------- FILTER CONDITIONS ----------------
if (f) uniquekeys = ia.ApplyFilterOptions(f, uniquekeys, 'key'); // apply filter conditions
// -------------- END FILTER CONDITIONS --------------
// --------------- FORMATTING OPTIONS ----------------
uniquekeys = ia.ApplyFormatOptions(frmt, uniquekeys, 'label');
// ------------- END FORMATTING OPTIONS --------------
retObj.ret = uniquekeys.map(k => k.key).join(d);
return retObj;
};
const getrepeating = ({
s: s = "", // repeating section
sfxn: sfxn = "", // suffix denoting name attribute for a given entry in a repeating section
sfxa: sfxa = "", // suffix denoting action attribute for a given entry in a repeating section
sfxrlbl: sfxrlbl = '', // suffix denoting the roll label when used with elem output
sfxlist: sfxlist = '', // list of sub-attributes to include in card output
l: l = '', // list of repeating attribute group ids and/or names (from sfxn)
c: c, // character (id, name, or token)
d: d = " ", // delimiter (default is space)
op: op = "l", // how to output (b: button, q: query, n: nested query, a: label list (action name), v: value list (action value), [default]/[none]: label list (naming attribute value)
p: p = "Select", // query prompt
v: v = "c", // attribute value to retrieve (c: current, m: max)
bg: bg, // background color for api button
theSpeaker: theSpeaker, // speaker object
css: css = "", // free input css for api button
f: f = "", // filter conditions
ef: ef = "", // filter conditions (executable)
frmt: frmt = "", // pipe-delimited list of formatting options
efrmt: efrmt = "", // pipe-delimited list of formatting options for executing text (use carefully!)
rlbl: rlbl = '', // label for a repeating button set (for iterative output)
emptyok: emptyok, // whether to have output messages for no sfxn returns
cfgObj: cfgObj // configuration settings
}) => {
let retObj = { ret: "", safe: true };
['true', 't', 'y', 'yes', true].includes(emptyok) ? emptyok = true : emptyok = false;
d = ia.CheckTicks(d); // check for opening/closing tick marks
let character = ia.CharFromAmbig(c);
if (!character) {
ia.MsgBox({ c: `getrepeating: No character found for ${c}.`, t: 'NO CHARACTER', send: true, wto: theSpeaker.localName });
return retObj;
}
bg = bg ? bg : cfgObj.bg;
css = `${cfgObj.css}${css}`;
rlbl = ia.CheckTicks(rlbl);
['m', 'max'].includes(v) ? v = 'max' : v = 'current';
let list = [], largs = [], ldelim = '';
let fullrx = /^repeating_([^_]*?)_([^_]*?)_(.+)$/;
// group 1: section from repeating_section_repID_suffix
// group 2: repID from repeating_section_repID_suffix
// group 3: suffix from repeating_section_repID_suffix
if (l) {
if (l.indexOf("|") > -1) { // there are multiple items
let rxresult = /^(.*?)\|([^|].*$)/.exec(l);
// group 1: every thing before the last of the first set of appearing pipes
// group 2: the remaining list after the same pipe
ldelim = rxresult[1]; // characters before first pipe are the internal delimiter
largs = rxresult[2].split(ldelim); // list after the first pipe is rejoined on pipes, then split on the delimiter
if (!ldelim || !largs.length) {
ia.MsgBox({ c: `getrepeating: A delimiter must precede a valid list (l).`, t: 'NO DELIMITER OR NO LIST', send: true, wto: theSpeaker.localName });
return retObj;
}
} else { // no pipe means single entry, so everything goes into largs
largs.push(l);
}
if (!s) {
let listresult = fullrx.exec(largs[0]);
if (listresult) {
s = listresult[1];
}
}
}
let nameRX = new RegExp(`^repeating_${s}_(?:[^_]*?)_(.+)$`, 'g');
// group 1: suffix from repeating_section_repID_suffix
if (s && !sfxn) { // if we have a section and a character but no sfxn, see if we can identify one
let attrsfx = findObjs({ type: 'attribute', characterid: character.id }) // get all attributes for this character
.filter(r => nameRX.test(r.get('name'))) // filter for the section
.map(r => {
nameRX.lastIndex = 0;
return nameRX.exec(r.get('name'))[1]; // isolate the suffix portion of the name of each attribute
})
.filter(r => /name/g.test(r)); // filter where that suffix contains 'name'
if (attrsfx.length) sfxn = attrsfx[0]; // if we found anything, assign sfxn to it
}
if (!(s && sfxn && (sfxa || ['bc', 'bC', 'c'].includes(op)))) { // before we go any further, we have to have a section, naming suffix, and either an action suffix or an output that doesn't need an action suffix
ia.MsgBox({
c: `getrepeating: You must supply values for section (s) and the naming suffix (sfxn). If your output (op) parameter is something other than \
a card ('c') or a card-producing button ('bc' or 'bC'), you must also provide the returned action suffix (sfxa)`, t: 'MISSING PARAMETERS', send: true, wto: theSpeaker.localName
});
return retObj;
}
let repRX = new RegExp(`^repeating_${s}_([^_]*?)_${sfxn}$`, 'g');
// group 1: repID from repeating_section_repID_suffix
let repid, locrlbl = '', sublist = [];
if (!l) { // no list provided, so get all non-repeating attributes
list = findObjs({ type: 'attribute', characterid: character.id }) // this will hold an array of objects in the form of {nameObj, execObj, label, execName, execText, rlbl, sublist}
.filter(r => repRX.test(r.get('name')));
} else { // list provided, so parse the list
list = largs.map(a => ia.RepeatingFromAmbig(a, character.id, s, sfxn)) // return an object
.filter(r => r)
.filter(r => r.get('name').match(new RegExp(`repeating_${s}_([^_]*?)_${sfxn}`)));
}
let cardapi = '';
list = list.map(a => {
repRX.lastIndex = 0;
repid = repRX.exec(a.get('name'))[1];
// get the attribute object for the action/exec attribute
let aObj = findObjs({ type: 'attribute', characterid: character.id }).filter(ao => ao.get('name') === `repeating_${s}_${repid}_${sfxa}`)[0] || { id: '', get: () => { return 'not found'; } };
// get the attribute object for the sfxrlbl, if one is provided
if (!rlbl) {
if (sfxrlbl) {
locrlbl = (findObjs({ type: 'attribute', characterid: character.id }).filter(a => new RegExp(`^repeating_${s}_${repid}_${sfxrlbl}$`).test(a.get('name')))[0] || { get: () => { return 'Roll' } }).get('current');
} else locrlbl = 'Roll';
} else locrlbl = rlbl;
sublist = [[sfxn, 'Name', getAttrByName(character.id, `repeating_${s}_${repid}_${sfxn}`)]];
if (sfxlist) {
sublist.push(...sfxlist.split("|")
.map(a => a.split(" "))
.map(a => [a[0], a.slice(1).join(" ") || a[0]])
.map(a => [a[0], a[1], getAttrByName(character.id, `repeating_${s}_${repid}_${a[0]}`) || 'NA']));
}
cardapi = `getrepeating{{!!c#${character.id} !!s#${s} !!sfxn#${sfxn} !!l#${a.get('current')} !!op#c${rlbl ? ` !!rlbl#${rlbl}` : ''}${sfxrlbl ? ` !!sfxrlbl#${sfxrlbl}` : ''}${sfxlist ? ` !!sfxlist#${sfxlist}` : ''}${v !== 'c' ? ` !!v#${v}` : ''}${frmt ? ` !!frmt#${frmt}` : ''}}}`;
return { nameObj: a, execObj: aObj, label: a.get('current'), execName: aObj.get('name'), execText: aObj.get(v), rlbl: locrlbl || 'Roll', sublist: sublist, cardapi: cardapi };
});
// we should now have an array of objects of the form {nameObj, execObj, label, execName, execText, rlbl, sublist, cardapi}
// test to make sure there was actually an attribute for sfxn & sfxa
if (!list.length) {
if (!emptyok) ia.MsgBox({ c: `getrepeating: No attributes found with that naming suffix (sfxn).`, t: 'NO ATTRIBUTE', send: true, wto: theSpeaker.localName });
return retObj;
} else if (!['bc', 'bC', 'c'].includes(op) && list.filter(a => a.execObj.id).length) {
if (!emptyok) ia.MsgBox({ c: `getrepeating: No attributes found with that action suffix (sfxa).`, t: 'NO ATTRIBUTE', send: true, wto: theSpeaker.localName });
return retObj;
}
// ---------------- FILTER CONDITIONS ----------------
list = ia.ApplyFilterOptions(f, list, 'label'); // apply filter conditions
list = ia.ApplyFilterOptions(ef, list, 'execText');
// -------------- END FILTER CONDITIONS --------------
// --------------- FORMATTING OPTIONS ----------------
list = ia.ApplyFormatOptions(frmt, list, 'label');
list = ia.ApplyFormatOptions(efrmt, list, 'execText');
// ------------- END FORMATTING OPTIONS --------------
if (!list.length) { // no entries means there were no attributes found from any of the options
if (!emptyok) ia.MsgBox({ c: `getrepeating: No attributes found for ${c} with the given filters.`, t: 'NO ATTRIBUTE', send: true, wto: theSpeaker.localName });
return retObj;
}
op = op.length ? op : 'l'; // make sure there is at least 1 character in op
let templist = deepCopy(list); // preserve the list while the retObj is written
retObj = ia.BuildOutputOptions({ p: p, op: op, list: list, bg: bg, css: css, character: character, elem: 'attr', v: v, theSpeaker: theSpeaker, d: d });
retObj.objarray = templist; // in case another function needs the array of objects
return retObj;
};
const getattrs = ({
c: c = "", // character (id, name, or token)
v: v = "current", // value wanted (current or max)
l: l = "", // list of attribute ids and/or names
d: d = " ", // delimiter (default: space)
op: op = "l", // how to output (b: button, q: query, n: nested query, v: attribute values, l: attribute labels (names), [default]/[none]: l)
p: p = "Select", // query prompt
bg: bg, // background color for api button
theSpeaker: theSpeaker, // speaker object
css: css = "", // free input css for api button
f: f = "", // filter conditions (label)
ef: ef = "", // filter conditions (executable)
frmt: frmt = "", // pipe-delimited list of formatting options
efrmt: efrmt = "", // pipe-delimited list of formatting options for executing text (use carefully!)
rlbl: rlbl = 'Roll', // label for a repeating button set (for iterative output)
emptyok: emptyok, // whether to have output messages for no sfxn returns
cfgObj: cfgObj // configuration settings
}) => {
let retObj = { ret: "", safe: true };
d = ia.CheckTicks(d); // check for opening/closing tick marks
['m', 'max'].includes(v) ? v = 'max' : v = 'current';
if (!c) {
ia.MsgBox({ c: `getattrs: You must supply a character (c) which could be a character name, id, or token id (if the token represents a character).`, t: 'NO CHARACTER', send: true, wto: theSpeaker.localName });
return retObj;
}
let character = ia.CharFromAmbig(c);
if (!character) {
ia.MsgBox({ c: `getattrs: No character found for ${c}.`, t: 'NO CHARACTER', send: true, wto: theSpeaker.localName });
return retObj;
}
bg = bg ? bg : cfgObj.bg;
css = `${cfgObj.css}${css}`;
rlbl = ia.CheckTicks(rlbl);
if (!rlbl) rlbl = 'Roll';
let list = []; // this will hold an array of objects in the form of {nameObj, execObj, label, execName, execText, rlbl}
let ldelim = "", largs = [];
if (!l) { // no list provided, so get all non-repeating attributes
list = findObjs({ type: 'attribute', characterid: character.id })
.filter(a => !a.get('name').startsWith('repeating_'))
.map(a => { return { nameObj: a, execObj: a, label: a.get('name'), execName: a.get('name'), execText: a.get(v), rlbl: rlbl }; });
} else { // list provided
if (l.indexOf("|") > -1) { // there are multiple items
let rxresult = /^(.*?)\|([^|].*$)/.exec(l);
// group 1: every thing before the last of the first set of appearing pipes
// group 2: the remaining list after the same pipe
ldelim = rxresult[1]; // characters before first pipe are the internal delimiter
largs = rxresult[2].split(ldelim); // list after the first pipe is rejoined on pipes, then split on the delimiter
if (!ldelim || !largs.length) {
ia.MsgBox({ c: `getattrs: A delimiter must precede a valid list (l).`, t: 'NO DELIMITER OR NO LIST', send: true, wto: theSpeaker.localName });
return retObj;
}
} else { // no pipe means single entry, so everything goes into largs
largs.push(l);
}
list = largs.map(a => a.split(" ")) // if there is a space, we have a label, too
.map(a => { return { nameObj: ia.AttrFromAmbig(a[0], character.id), label: a.slice(1).join(" ") || "" }; }) // join everything after the first space, return an object in the form of {nameObj, label}
.filter(a => a.nameObj) // filter for where we didn't find an object
.map(a => { return { nameObj: a.nameObj, execObj: a.nameObj, label: a.label || a.nameObj.get('name'), execName: a.nameObj.get('name'), execText: a.nameObj.get(v), rlbl: rlbl }; }); // expand each entry into all of the properties we need
}
// ---------------- FILTER CONDITIONS ----------------
list = ia.ApplyFilterOptions(f, list);
list = ia.ApplyFilterOptions(ef, list, 'execText');
// -------------- END FILTER CONDITIONS --------------
// --------------- FORMATTING OPTIONS ----------------
list = ia.ApplyFormatOptions(frmt, list);
list = ia.ApplyFormatOptions(efrmt, list, 'execText');
// ------------- END FORMATTING OPTIONS --------------
if (!list.length) { // no entries means there were no attributes found from any of the options
if (!emptyok) ia.MsgBox({ c: `getattrs: No attribute found for ${c} with the given parameters.`, t: 'NO ATTRIBUTE', send: true, wto: theSpeaker.localName });
return retObj;
}
op = op.length ? op : 'l'; // make sure there is at least 1 character in op
let templist = deepCopy(list); // preserve the list while the retObj is written
retObj = ia.BuildOutputOptions({ p: p, op: op, list: list, bg: bg, css: css, character: character, elem: 'attr', v: v, theSpeaker: theSpeaker, d: d });
retObj.objarray = templist; // in case another function needs the array of objects
return retObj;
};
const getabils = ({
c: c = "", // character (id, name, or token)
l: l = "", // list of abilities ids and/or names
d: d = " ", // delimiter (default: space)
op: op = "l", // how to output (b: button, q: query, n: nested query, a: action name, x: action value, [default]/[none]: delimited list)
p: p = "Select", // query prompt
bg: bg, // background color for api button
theSpeaker: theSpeaker, // speaker object
css: css = "", // free input css for api button
f: f = "", // filter conditions
ef: ef = "", // filter conditions (executable)
frmt: frmt = "", // pipe-delimited list of formatting options
efrmt: efrmt = "", // pipe-delimited list of formatting options for executing text (use carefully!)
rlbl: rlbl = 'Roll', // label for a repeating button set (for iterative output)
emptyok: emptyok, // whether to have output messages for no sfxn returns
cfgObj: cfgObj // configuration settings
}) => {
let retObj = { ret: "", safe: true };
let abil;
d = ia.CheckTicks(d); // check for opening/closing tick marks
if (!c) {
ia.MsgBox({ c: `getabilities: You must supply a character (c) which could be a character name, id, or token id (if the token represents a character).`, t: 'NO CHARACTER', send: true, wto: theSpeaker.localName });
return retObj;
}
let character = ia.CharFromAmbig(c);
if (!character) {
ia.MsgBox({ c: `getabilities: No character found for ${c}.`, t: 'NO CHARACTER', send: true, wto: theSpeaker.localName });
return retObj;
}
bg = bg ? bg : cfgObj.bg;
css = `${cfgObj.css}${css}`;
rlbl = ia.CheckTicks(rlbl);
if (!rlbl) rlbl = 'Roll';
let list = []; // this will hold an array of objects in the form of {nameObj, execObj, label, execName, execText, rlbl}
let v = 'action';
let ldelim = "", largs = [];
if (!l) { // no list provided, so get all abilities
list = findObjs({ type: 'ability', characterid: character.id })
.map(a => { return { nameObj: a, execObj: a, label: a.get('name'), execName: a.get('name'), execText: a.get(v), rlbl: rlbl }; });
} else { // list provided
if (l.indexOf("|") > -1) { // there are multiple items
let rxresult = /^(.+?)\|([^|].*$)/.exec(l);
// group 1: every thing before the last of the first set of appearing pipes
// group 2: the remaining list after the same pipe
ldelim = rxresult[1]; // characters before first pipe are the internal delimiter
largs = rxresult[2].split(ldelim); // list after the first pipe is rejoined on pipes, then split on the delimiter
if (!ldelim || !largs.length) {
ia.MsgBox({ c: `getabilities: A delimiter must precede a valid list (l).`, t: 'NO DELIMITER OR NO LIST', send: true, wto: theSpeaker.localName });
return retObj;
}
} else { // no pipe means single entry, so everything goes into largs
largs.push(l);
}
list = largs.map(a => a.split(" ")) // if there is a space, we have a label, too
.map(a => { return { nameObj: ia.AttrFromAmbig(a[0], character.id), label: a.slice(1).join(" ") }; }) // join everything after the first space, return an object in the form of {nameObj, label}
.filter(a => a.nameObj) // filter for where we didn't find an object
.map(a => { return { nameObj: a.nameObj, execObj: a.nameObj, label: a.label || a.get('name'), execName: a.nameObj.get('name'), execText: a.nameObj.get(v), rlbl: rlbl }; }); // expand each entry into all of the properties we need
}
// ---------------- FILTER CONDITIONS ----------------
list = ia.ApplyFilterOptions(f, list);
list = ia.ApplyFilterOptions(ef, list, 'execText');
// -------------- END FILTER CONDITIONS --------------
// --------------- FORMATTING OPTIONS ----------------
list = ia.ApplyFormatOptions(frmt, list);
list = ia.ApplyFormatOptions(efrmt, list, 'execText');
// ------------- END FORMATTING OPTIONS --------------
if (!list.length) { // no entries means there were no abilities found from any of the options
if (!emptyok) ia.MsgBox({ c: `getabilities: No ability found for ${character.get('name')} with the given parameters.`, t: 'NO ABILITY', send: true, wto: theSpeaker.localName });
return retObj;
}
op = op.length ? op : 'l'; // make sure there is at least 1 character in op
let templist = deepCopy(list); // preserve the list while the retObj is written
retObj = ia.BuildOutputOptions({ p: p, op: op, list: list, bg: bg, css: css, character: character, elem: 'abil', v: v, theSpeaker: theSpeaker, d: d });
retObj.objarray = templist; // in case another function needs the array of objects
return retObj;
};
const gettokens = ({
l: l = '', // list of tokens to retrieve
v: v = 'id', // value to return (id, cid, name)
pg: pg = '', // page id to draw tokens from
rep: rep = 'false', // whether the tokens should be limited to only those represent characters
lyr: lyr = 'objects', // pipe separated list for layer for tokens, default: token
d: d = ' ', // delimiter (default: space)
p: p = 'Select', // prompt for query output
op: op = "l", // how to output the retrieved tokens
f: f = '', // filter options
frmt: frmt = '', // format options
rlbl: rlbl,
bg: bg = '',
css: css = '',
m: m, // message object
theSpeaker: theSpeaker, // the speaker object
cfgObj: cfgObj // config object
}) => {
let retObj = { ret: "", safe: true };
d = ia.CheckTicks(d); // check for opening/closing tick marks
bg = bg ? bg : cfgObj.bg;
css = `${cfgObj.css}${css}`;
rep = ['true', 't', 'yes', 'y', true].includes(rep) ? true : false;
if (!pg) pg = Campaign().get("playerpageid");
lyr = lyr.split("|");
if (lyr.includes('gmlayer') && !playerIsGM(m.playerid)) {
ia.MsgBox({ c: `gettokens: GMLayer is only accessible by GMs.`, t: 'ACCESS RESTRICTED', send: true, wto: theSpeaker.localName });
return retObj;
}
let list = []; // this will hold an array of objects in the form of {nameObj, execObj, label, execName, execText, rlbl}
v = ['n', 'name'].includes(v) ? 'name' : 'id';
let ldelim = "", largs = [];
if (!l) { // no list provided, so get all tokens
list = findObjs({ type: 'graphic', subtype: 'token' })
.map(t => { return { nameObj: t, execObj: t.get('represents') ? ia.CharFromAmbig(t.get('represents')) : undefined }; })
.map(t => { // expand each entry into all of the properties we need
return {
nameObj: t.nameObj,
execObj: t.execObj,
label: t.nameObj.get('name'),
execName: t.execObj ? t.execObj.get('name') : "",
execText: t.nameObj.id,
rlbl: rlbl
};
});
} else { // list provided
if (l.indexOf("|") > -1) { // there are multiple items
let rxresult = /^(.+?)\|([^|].*$)/.exec(l);
// group 1: every thing before the last of the first set of appearing pipes
// group 2: the remaining list after the same pipe
ldelim = rxresult[1]; // characters before first pipe are the internal delimiter
largs = rxresult[2].split(ldelim); // list after the first pipe is rejoined on pipes, then split on the delimiter
if (!ldelim || !largs.length) {
ia.MsgBox({ c: `gettokens: A delimiter must precede a valid list (l).`, t: 'NO DELIMITER OR NO LIST', send: true, wto: theSpeaker.localName });
return retObj;
}
} else { // no pipe means single entry, so everything goes into largs
largs.push(l);
}
list = largs.map(a => a.split(" ")) // if there is a space, we have a label, too
.map(t => { return { nameObj: ia.TokenFromAmbig(t[0]), label: t.slice(1).join(" ") }; }) // join everything after the first space, return an object in the form of {nameObj, label}
.filter(t => t.nameObj) // filter for where we didn't find an object
.map(t => { // expand each entry into all of the properties we need
return {
nameObj: t.nameObj,
execObj: t.get('represents') ? ia.CharFromAmbig(t.get('represents')) : undefined,
label: t.label || t.get('name'),
execName: t.get('represents') ? getObj('character', t.get('represents')).get('name') : '',
execText: t.id,
rlbl: rlbl
};
})
.filter(t => t.nameObj.get('pageid') === pg && t.nameObj.get('layer') === lyr); // filter for page & map
}
log([...new Set(list.map(a => a.nameObj.get('layer')))].join(", "));
list = list.filter(t => t.nameObj.get('pageid') === pg) // fitler for page
.filter(t => lyr.includes(t.nameObj.get('layer'))); // filter for layer
list = rep ? list.filter(t => t.execObj) : list; // filter for representing a character, if rep is true
// ---------------- FILTER CONDITIONS ----------------
list = ia.ApplyFilterOptions(f, list, 'execText');
// -------------- END FILTER CONDITIONS --------------
// --------------- FORMATTING OPTIONS ----------------
list = ia.ApplyFormatOptions(frmt, list, 'execText');
// ------------- END FORMATTING OPTIONS --------------
if (!list.length) { // no entries means there were no abilities found from any of the options
ia.MsgBox({ c: `gettokens: No tokens found for the given parameters.`, t: 'NO TOKENS', send: true, wto: theSpeaker.localName });
return retObj;
}
op = op.length ? op : 'l'; // make sure there is at least 1 character in op
let templist = deepCopy(list); // preserve the list while the retObj is written
retObj = ia.BuildOutputOptions({ p: p, op: op, list: list, bg: bg, css: css, elem: 'abil', v: v, theSpeaker: theSpeaker, d: d });
retObj.objarray = templist; // in case another function needs the array of objects
return retObj;
};
// ==================================================
// HELP OBJECT
// ==================================================
const formatHelp = ['frmt', `gethelp(format${ia.GetHelpArg()})`];
const filterHelp = ['f', `gethelp(filter${ia.GetHelpArg()})`];
const delimHelp = ['d', 'delimiter between each output value; enclose with tick marks to include leading/trailing space; default: (space)'];
const emptyokHelp = ['emptyok', 'whether to suppress error messages for empty sections (yes, y, true, and t map to true); default: false'];
const outputHelp = ['op', `gethelp(output${ia.GetHelpArg()})`];
const help = {
[`output${ia.GetHelpArg()}`]: {
msg: 'Use output (op) options for how to return the retrieved items. Default option is \'l\' (list).',
args: [
['b', 'buttons<br>repeating elements structured as (label: sfxn, action: sfxa); standard attributes (label: name, action: current or max)<br>abilities (label: name, action: action)'],
['be', 'as \'b\', except intended for individual elem rows for menu with external labels; utilizes the rlbl property for the button label'],
['br/bR', 'buttons to read the contents of the attribute in chat; if the \'r\' is capitalized, button readout will be spoken; if lowercase, it will be whispered'],
['bre/ber/bRe/beR', 'as \'br\', except intended for individual elem rows for menu with external labels; utilizes the rlbl property for the button labels'],
['bc/bC', 'buttons to output cards in chat; if the \'c\' is capitalized, button readout will be spoken; if lowercase, it will be whispered'],
['bce/bec/bCe/beC', 'as \'bc\', except intended for individual elem rows for menu with external labels; utilizes the rlbl property for the button labels'],
['c/C', 'card output for repeating section (lowercase: whisper; uppercase: chat); name suffix is included automatically, but other sub-attributes can be included in the sfxlist argument of getrepeating'],
['q', 'query producing (label,return) pairs; uses prompt argument (p) for query interrogative; can be refined with further letters as follows; defaults to \'qlv\''],
['ql', 'query producing (label) list; uses prompt argument (p) for query interrogative<br>\
repeating (label: sfxn)<br>\
standard attributes (label: name)<br>\
abilities (label: name)<br>\
tokens (label: name)'],
['qv', 'query producing (return) list; uses prompt argument (p) for query interrogative<br>\
repeating (return: sfxa)<br>\
standard attributes (return: current or max)<br>\
abilities (return: action)<br>\
tokens (return: id)'],
['qln', 'query producing (label,return) pairs; uses prompt argument (p) for query interrogative<br>\
repeating (label: sfxn, return: sfxa name)<br>\
standard attributes (label: name, return: name)<br>\
abilities (label: name, return: name)<br>\
tokens (label: name, return: character name)'],
['qlv', '(alias of q); query producing (label,return) pairs; uses prompt argument (p) for query interrogative<br>\
repeating (label: sfxn, return: sfxa value)<br>\
standard attributes (label: name, return: current or max)<br>\
abilities (label: name, return: action)<br>\
tokens (label: name, return: id)'],
['n', 'as query (including all secondary options), except with nested output (html entity replacement as per nest function)'],
['l', 'list of names of the sheet objects\' name elements<br>repeating: sfxn sub sttribute name<br>standard attributes: name<br>abilities: name'],
['a', 'list of names of the sheet objects\' action elements (differs from \'l\' only for repeating sections<br>repeating: sfxa sub sttribute name<br>standard attributes: name<br>abilities: name'],
['v', 'list of values for the sheet objects\' action elements<br>repeating: sfxa sub sttribute current or max<br>standard attributes: current or max<br>abilities: action'],
['lve', 'a list/value output arranged for spreading across elem rows of a table']
]
},
[`format${ia.GetHelpArg()}`]: {
msg: 'Use formatting options to structure or modify either your label (frmt) or your returned executable value (efrmt). Formatting options are passed using the \'frmt\' and \'efrmt\' parameters, if the internal function accepts them; multiple formatting options can be passed as a pipe-separated list where each element is constructed as:<br>(format)[#(option)]<br><br>\
Formatting options are applied in left to right order to each returned value. The following frmt parameter would first insert drop everything to lowercase, then do a replace operation to remove text, then format the result as title case:<br>!!frmt#lc|fr#roll_formula#``|tc',
args: [
['lc', 'lowercase'],
['uc', 'uppercase'],
['tc', 'titlecase'],
['su', 'insert space before uppercase letters'],
['_s', 'change underscore to space'],
['o+', 'sort ascending'],
['o-', 'sort descending'],
['^t', 'insert before value; requires a # (pound/hash) and then the text to insert'],
['t^', 'insert after value; requires a # (pound/hash) and then the text to insert'],
['fr', 'find and replace; requires a # followed by the search text followed by # and then the replacemnet text; enclose strings with leading/trailing spaces in tick marks (`)'],
['rslv', 'special find/replace that encloses the find text in @{} before replacing it; helpful with resolution of roll template parts that might otherwise break'],
['n', 'format the text for nested output, replacing the three characters: } , | with their html entities only where they are not involved in an attribute or ability lookup']
]
},
[`filter${ia.GetHelpArg()}`]: {
msg: 'Enter filters for the returned values to restrict the returned items according to your specifications. Filters are passed using the \'f\' parameter to filter on the name or label of the object, or using the \'ef\' parameter to filter on the executable (action) text; multiple filters can be passed as a pipe-separated list where each element is constructed as:<br>(filter type)#(test condition)<br>\
...and the filter type is drawn from the following list...',
args: [
['x', 'executable; tests the first character for the presence of an executing character:<br>@ % ? & !'],
['^f', 'begins with'],
['f^', 'ends with'],
['^f^', 'contains'],
['-^f', 'does not begin with'],
['-f^', 'does not end with'],
['-^f^', 'does not contain'],
['top', 'limit returns to top x returns, where x is a number; negative numbers represent bottom x returns'],
['s', 'token status markers includes'],
['-s', 'token status markers do not include']
]
},
puttext: {
msg: 'Places any number of elements in the command line, in order, at the given hook. \
Elements can be simple text or internal functions. Use this when you need to use \
an internal function AFTER including other text and/or to establish the presence of hooks \
for future replacement operations. Text that begins or ends with a space should be contained \
within paired tick marks (`). Since the tick marks will be removed, if you actually need your \
text enclosed by ticks, you will have to double them up at the start and end.',
args: [
['(any)', 'text or internal function; enclose text that includes leading/trailing space with ticks (`)']
]
},
getattr: {
msg: 'This function returns either the current or max value for a given attribute.',
args: [
['a', 'attribute id, or (character identifier)|(attribute name)'],
['v', 'value you wish to return; default: current; m or max for max'],
['h', 'encode for html entitites (preserves output); "t", "true", "y", "yes" map to true; default: false']
]
},
getabil: {
msg: 'This function returns the action text for a given ability.',
args: [
['a', 'ability id, or (character)|(ability name)']
]
},
getmacro: {
msg: 'This function returns the action text for a given macro.',
args: [
['a', 'macro id or name']
]
},
puttargets: {
msg: 'This function inserts a number of targeting constructions (ie, @{target|label|return}) into the command line. Label includes a positional index that counts up from 1.',
args: [
['n', 'number of targets; default: 1'],
['l', 'text label for each targeting construction; default: Target'],
['r', 'data point to return; default: token_id'],
delimHelp
]
},
getselected: {
msg: 'This function gets a list of the ids of the selected items at the time of the InsertArg call.',
args: [
['r', 'what to return from the selected tokens (id, name, or represents, etc.); default: id'],
delimHelp
]
},
getme: {
msg: 'Gets the id or name of the current speaker (player or character), or the chat speaker output (ie, Player|Name)',
args: [
['r', 'what to return; default: id; "n" and "name" return name, "c" and "cs" return chat speaker, anything else returns the id'],
formatHelp
]
},
getsections: {
msg: 'For a given character, gets the a list of unique section names for repeating elements.',
args: [
['c', 'character identifier (id, name, or token id)'],
delimHelp,
formatHelp,
filterHelp
]
},
getrepeating: {
msg: 'For a given character, gets a list of repeating attributes within a given section, using a given sub-attribute as the naming element, and sampling across a sub-attribute supplied to be the action/data element.',
args: [
['c', 'character identifier (id, name, or token id)'],
delimHelp,
['s', 'section name (as returned from getsection); "section" from repeating_section_id_subattr'],
['sfxn', 'name portion of the sub-attribute responsible for naming an attribute set from the section; "subattr" from repeating_section_is_subattr<br>if left blank, getrepeating will look for a sub-attribute with the text "name" in the current value'],
['sfxa', 'name portion of the sub-attribute you wish to return (for instance, the roll formula); "subattr" from repeating_section_id_subattr'],
['sfxrlbl', 'name portion of the sub-attribute you wish to use for button labels if using elem menu output, overwritten by explicit declaration of rlbl'],
['sfxlist', 'pipe-separated list of sub-attribute suffixes to include as part of a card; naming suffix is included automatically; if you want a full-width field, append \'(fw)\' to your field label'],
['l', 'list of repeating attributes to retrieve; repeating attributes can be referred to by name, id, or contents of the naming sub-attribute (i.e., what you would call the entry in the repeating list), \
with or without a character reference and pipe preceding each (leaving off the character reference will use the speaking character, if available); unlike other list (l) arguments, does NOT take a label option\
if more than one item is included, the list argument must be formatted as<br>\
(list delimiter)|(attribute)(list delimiter)(attribute 2)...<br>\
for instance, the following line would list the repeating attributes named Fireball and Inferno (the current value of the naming sub-attribute), using the delimiter of a pipe<br>\
!!l#||Fireball|Inferno<br><br>\
if left empty, all repeating attributes for the character will be retrieved; whatever is retrieved can be filtered by use of the f arg'],
['v', 'value to retrieve (current or max); default: current; anything other than "m" or "max" maps to current'],
['p', 'prompt for query (or nested query) output; default: Select'],
['bg', 'css background-color for api button output to override that designated by any config handout; default: (detected from speaker handout, global handout, or default config)'],
['css', 'free css input for api button to override that designated by any config handout; default: (detected from speaker handout, global handout, or default config)'],
['rlbl', 'label for buttons where the name of the attribute will be outside of the button (for menu construction); default: Roll'],
emptyokHelp,
outputHelp,
formatHelp,
filterHelp,
]
},
getattrs: {
msg: 'For a given character, gets a list of non-repeating attributes.',
args: [
['c', 'character identifier (id, name, or token id)'],
delimHelp,
['v', 'value to retrieve (current or max); default: current; anything other than "m" or "max" maps to current'],
['l', 'list of attributes to retrieve; attributes may be referred to by id or name; each attribute may be followed by a space and then a label to use instead of the attribute name;<br>\
if more than one item is included, the list argument must be formatted as<br>\
(list delimiter)|(attribute)(list delimiter)(attribute 2)...<br>\
for instance, the following line would list attributes named STR and DEX, renamed to Strength and Dexterity, using the delimiter of a pipe<br>\
!!l#||STR Strength|DEX Dexterity<br><br>\
if left empty, all non-repeating attributes for the character will be retrieved; whatever is retrieved can be filtered by use of the f arg'],
['p', 'prompt for query (or nested query) output; default: Select'],
['bg', 'css background-color for api button output to override that designated by any config handout; default: (detected from speaker handout, global handout, or default config)'],
['css', 'free css input for api button to override that designated by any config handout; default: (detected from speaker handout, global handout, or default config)'],
emptyokHelp,
outputHelp,
formatHelp,
filterHelp,
['rlbl', 'standard label for buttons if output is separated into repeating element; default: Roll']
]
},
getabils: {
msg: 'For a given character, gets a list of abilities.',
args: [
['c', 'character identifier (id, name, or token id)'],
delimHelp,
['l', 'list of abilities to retrieve; abilities may be referred to by id or name; each ability may be followed by a space and then a label to use instead of the ability\'s name;<br>\
list argument must be formatted as<br>\
(list delimiter)|(abilities)(list delimiter)(abilities 2)...<br>\
for instance, the following line would list abilities named STR and DEX, renamed to Strength and Dexterity, using the delimiter of a pipe<br>\
!!l#||STR Strength|DEX Dexterity<br><br>\
if left empty, all abilities for the character will be retrieved; whatever is retrieved can be filtered by use of the f arg'],
['p', 'prompt for query (or nested query) output; default: Select'],
['bg', 'css background-color for api button output to override that designated by any config handout; default: (detected from speaker handout, global handout, or default config)'],
['css', 'free css input for api button to override that designated by any config handout; default: (detected from speaker handout, global handout, or default config)'],
emptyokHelp,
outputHelp,
formatHelp,
filterHelp,
['rlbl', 'standard label for buttons if output is separated into repeating element; default: Roll']
]
},
gettokens: {
msg: 'Retrieves tokens matching the given parameters.',
args: [
['l', 'list of tokens to retrieve'],
['v', 'value to return for simple list output (id, name); default: id'],
['pg', 'page id to draw tokens from'],
['rep', 'whether the tokens should be limited to only those represent characters; default: false'],
['lyr', 'pipe-separated layer for tokens, default: token'],
delimHelp,
outputHelp,
filterHelp,
formatHelp,
['rlbl', 'standard label for buttons if output is separated into repeating element; default: Roll']
]
}
};
on('ready', () => {
versionInfo;
try {
ia.RegisterRule(puttext, getattr, getabil, getmacro, puttargets, getselected, getme, getsections, getrepeating, getattrs, getabils, gettokens);
ia.RegisterHelp(help);
} catch (error) {
log(error);
}
});
return {
GetVrs: getVrs
};
})();
const xray = (() => {
// ==================================================
// VERSION
// ==================================================
const vrs = '1.2';
const versionInfo = () => {
const vd = new Date(1600308742949);
log('\u0166\u0166 XRAY v' + vrs + ', ' + vd.getFullYear() + '/' + (vd.getMonth() + 1) + '/' + vd.getDate() + ' \u0166\u0166');
return;
};
const getVrs = () => { return vrs; };
// ==================================================
// TABLES AND TEMPLATES
// ==================================================
const attrValTable = { current: "current", c: "current", max: "max", m: "max", name: "name", n: "name", a: "action", action: "action" };
const execCharSet = ["&", "!", "@", "#", "%"];
const btnElem = { attr: '@', abil: '%', attribute: '@', ability: '%', macro: '#' };
const htmlTable = {
"&": "&",
"{": "{",
"}": "}",
"|": "|",
",": ",",
"%": "%",
"?": "?",
"[": "[",
"]": "]",
"@": "@",
"~": "~",
"(": "(",
")": ")",
"<": "<",
">": ">",
};
const rowbg = ["#ffffff", "#dedede"];
const msgtable = '<div style="width:100%;"><div style="border-radius:10px;border:2px solid #000000;background-color:__bg__; margin-right:16px; overflow:hidden;"><table style="width:100%; margin: 0 auto; border-collapse:collapse;font-size:12px;">__TABLE-ROWS__</table></div></div>';
const msg1header = '<tr style="border-bottom:1px solid #000000;font-weight:bold;text-align:center; background-color:__bg__; line-height: 22px;"><td colspan = "__colspan__">__cell1__</td></tr>';
const msg2header = '<tr style="border-bottom:1px solid #000000;font-weight:bold;text-align:center; background-color:__bg__; line-height: 22px;"><td>__cell1__</td><td style="border-left:1px solid #000000;">__cell2__</td></tr>';
const msg3header = '<tr style="border-bottom:1px solid #000000;font-weight:bold;text-align:center; background-color:__bg__; line-height: 22px;"><td>__cell1__</td><td style="border-left:1px solid #000000;">__cell2__</td><td style="border-left:1px solid #000000;">__cell3__</td></tr>';
const msg1row = '<tr style="background-color:__bg__;"><td style="padding:4px;"><div style="__row-css__">__cell1__</div></td></tr>';
const msg2row = '<tr style="background-color:__bg__;font-weight:bold;"><td style="padding:1px 4px;">__cell1__</td><td style="border-left:1px solid #000000;text-align:center;padding:1px 4px;font-weight:normal;">__cell2__</td></tr>';
const msg3row = '<tr style="background-color:__bg__;font-weight:bold;"><td style="padding:1px 4px;">__cell1__</td><td style="border-left:1px solid #000000;text-align:center;padding:1px 4px;font-weight:normal;">__cell2__</td><td style="border-left:1px solid #000000;text-align:center;padding:1px 4px;font-weight:normal;">__cell3__</td></tr>';
// ==================================================
// UTILITIES
// ==================================================
const getTheSpeaker = function (msg) {
var characters = findObjs({ type: 'character' });
var speaking;
characters.forEach((chr) => { if (chr.get('name') === msg.who) speaking = chr; });
if (speaking) {
speaking.speakerType = "character";
speaking.localName = speaking.get("name");
} else {
speaking = getObj('player', msg.playerid);
speaking.speakerType = "player";
speaking.localName = speaking.get("displayname");
}
speaking.chatSpeaker = speaking.speakerType + '|' + speaking.id;
return speaking;
};
const escapeRegExp = (string) => { return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); };
const htmlCoding = (s = "", encode = true) => {
if (typeof s !== "string") return undefined;
let searchfor = encode ? htmlTable : _invert(htmlTable);
s = s.replace(new RegExp(Object.keys(searchfor)
.map((k) => { return escapeRegExp(k); })
.join("|"), 'gmi'), (r) => { return searchfor[r]; })
.replace(new RegExp(/\n/, 'gmi'), '<br><br>');
return s;
};
const repeatingOrdinal = (character_id, section = '', attr_name = '') => {
if (!section && !attr_name) return;
let ordrx, match;
if (attr_name) {
ordrx = /^repeating_([^_]+)_([^_]+)_.*$/;
// group 1: section from repeating_section_repID_suffix
// group 2: repID from repeating_section_repID_suffix
if (!ordrx.test(attr_name)) return; // the supplied attribute name isn't a repeating attribute at all
ordrx.lastIndex = 0;
match = ordrx.exec(attr_name);
section = match[1];
// group 1: section from repeating_section_repID_suffix
}
let sectionrx = new RegExp(`repeating_${section}_([^_]+)_.*$`);
let createOrderKeys = findObjs({ type: 'attribute', characterid: character_id })
.filter(a => sectionrx.test(a.get('name')))
.map(a => sectionrx.exec(a.get('name'))[1]);
let sortOrderKeys = (findObjs({ type: 'attribute', characterid: character_id, name: `_reporder_repeating_${section}` })[0] || { get: () => { return ''; } })
.get('current')
.split(/\s*,\s*/)
.filter(a => createOrderKeys.includes(a));
sortOrderKeys.push(...createOrderKeys.filter(a => !sortOrderKeys.includes(a)));
return attr_name ? sortOrderKeys.indexOf(match[2]) : sortOrderKeys;
};
const xraysheet = ({
// for a given character, returns a list of the repeating sections, an entry for basic attributes, and one for abilities
character: character, // character
css: css = "", // free input css for api button
bg: bg = "", // background color for api button
theSpeaker: theSpeaker,
cfgObj: cfgObj
} = {}) => {
let msg = '', btn = '';
bg = !bg ? cfgObj.bg : bg;
css = !css ? cfgObj.css : css;
let sectionRX = /^repeating_([^_]+?)_.+$/g;
// group 1: section from repeating_section_attributeID_suffix
let sections = findObjs({ type: 'attribute', characterid: character.id })
.filter(a => { // filter where the regex matches
sectionRX.lastIndex = 0;
return sectionRX.test(a.get('name'));
})
.map(a => { // extract section (group 1 of the regex)
sectionRX.lastIndex = 0;
return sectionRX.exec(a.get('name'))[1];
});
let uniquekeys = [...new Set(sections)]; // get an array of unique values
let retval = "",
sectiontable = msgtable.replace("__bg__", rowbg[0]),
sectionheader = msg1header.replace("__colspan__", '2').replace("__bg__", rowbg[1]).replace("__cell1__", `XRAY: ${character.get('name').toUpperCase()}`) + msg2header.replace("__bg__", rowbg[1]).replace("__cell1__", "GROUP").replace("__cell2__", "XRAY"),
rowtemplate = msg2row;
let apixray = `!xray --${character.id}#__section__ --0#25`;
let btnabil = findObjs({ type: 'ability', characterid: character.id }).length ? ia.BtnAPI({ bg: bg, api: apixray.replace('__section__', 'ability'), label: "XRay", charid: character.id, css: css }) : 'NA';
let btnattr = findObjs({ type: 'attribute', characterid: character.id }).filter(a => !a.get('name').startsWith('repeating')).length ? ia.BtnAPI({ bg: bg, api: apixray.replace('__section__', 'attribute'), label: "XRay", charid: character.id, css: css }) : 'NA';
sectionheader += rowtemplate.replace("__bg__", rowbg[0]).replace("__cell1__", 'Abilities').replace("__cell2__", btnabil);
sectionheader += rowtemplate.replace("__bg__", rowbg[1]).replace("__cell1__", 'Attributes').replace("__cell2__", btnattr);
let attrrows = uniquekeys.reduce((a, val, i) => {
retval = val;
if (typeof retval === "string" && retval !== "") {
apixray = `!xray --${character.id}#${val} --?{At position...|0}`;
retval = ia.BtnAPI({ bg: bg, api: apixray, label: "XRay", charid: character.id, css: css });
}
return a + rowtemplate.replace("__bg__", rowbg[(i % 2)]).replace("__cell1__", val).replace("__cell2__", retval);
}, sectionheader);
sendChat('API', `/w ${theSpeaker.localName} ${sectiontable.replace("__TABLE-ROWS__", attrrows)}`);
return;
};
const xraysection = ({
// provides a cross-section view of a given element of a repeating series at position "pos"
// for instance, all of the sub-attributes of a spell in a repeating section "spells"
s: s = "", // section
v: v = "c", // attribute value to retrieve (c: current, m: max, n: name)
character: character, // character object (should be identified by now)
css: css = "", // free input css for api button
bg: bg = "", // background color for api button
pos: pos = 0, // position of element to check in repeating list
cfgObj: cfgObj, // configuration settings
theSpeaker: theSpeaker, // speaker object from the message
} = {}) => {
if (!bg) bg = cfgObj.bg;
if (!css) css = cfgObj.css;
let uniquekeys = repeatingOrdinal(character.id, s); // get ordered list of unique keys
if (!uniquekeys.length) {
ia.MsgBox({ c: `xray: No elements in ${s}.`, t: `NO RETURN`, send: true, wto: theSpeaker.localName });
return;
}
/*
let sectionRX = new RegExp(`repeating_${s}_([^_]*?)_.*$`);
// group 1: attributeID from repeating_section_attributeID_suffix
let attrsinrep = findObjs({ type: 'attribute', characterid: character.id }).filter(r => sectionRX.test(r.get('name')));
if (!attrsinrep.length) {
ia.MsgBox({ c: `xray: No elements in ${s}.`, t: `NO RETURN`, send: true, wto: theSpeaker.localName });
return;
}
let uniquekeys = [...new Set(attrsinrep.map(a => sectionRX.exec(a.get('name'))[1]))]; // extract attributeID (group 1 of the regex), then get an array of unique values
*/
pos = Number(pos);
if (isNaN(pos)) {
ia.MsgBox({ c: `xray: Argument 'pos' not recognized as number.`, t: `INVALID POSITION`, send: true, wto: theSpeaker.localName });
return;
}
if (pos >= uniquekeys.length || pos < 0) {
ia.MsgBox({ c: `Argument 'pos' out of scope. Min value is 0. Max value for this character is ${uniquekeys.length - 1}.`, t: `INVALID POSITION`, send: true, wto: theSpeaker.localName });
return;
}
let suffixRX = new RegExp(`^repeating_${s}_${uniquekeys[pos]}_(.*)$`);
// group 1: suffix from repeating_section_attributeID_suffix
let attrs = findObjs({ type: 'attribute', characterid: character.id }).filter(r => suffixRX.test(r.get('name')));
let nameguessRX = new RegExp(`^repeating_${s}_${uniquekeys[pos]}_(.*?name.*)$`);
// group 1: suffix that contains 'name'
let attr_nameguess = attrs.filter(r => nameguessRX.test(r.get('name'))).map(r => nameguessRX.exec(r.get('name'))[1])[0] || ""; // filter where the word 'name' is in the suffix, [1] is the group bearing the suffix, [0] is to grab the first attribute that matches
let retval = "",
menufor = "",
menuapi = "",
infoapi = "",
infobtn = "",
attrsuffix = "",
attrtable = msgtable.replace("__bg__", rowbg[0]),
attrheader = msg1header.replace("__colspan__", '3').replace("__bg__", rowbg[1]).replace("__cell1__", `XRAY: ${character.get('name').toUpperCase()}: ${s.toUpperCase()}<br><table style="width:98%;margin:auto;"><tr><td style="text-align:left;">repeating_${s}_${uniquekeys[pos]}</td><td style="text-align:right;">POS: ${pos}</td></tr></table>`) + msg3header.replace("__bg__", rowbg[1]).replace("__cell1__", "SUFFIX").replace("__cell2__", "MENU").replace("__cell3__", (attrValTable[v] || attrValTable.c).toUpperCase()),
rowtemplate = msg3row,
attrrows = attrs.reduce((a, val, i) => {
retval = val.get(attrValTable[v] || attrValTable.c);
menufor = "";
menuapi = "";
if (typeof retval === "string" && retval !== "") {
if (execCharSet.includes(retval.charAt(0))) { // look for executable statements, if found, we will construct 3 buttons
retval = ia.BtnAPI({ bg: bg, api: `!xray --read --${character.id}#${val.get('name')}`, label: "View", charid: character.id, css: css }) + " " +
ia.BtnElem({ bg: bg, store: val.get('name'), label: "Exec", charname: character.get('name'), entity: btnElem.attr, css: css });
menuapi = `!ia --whisper --show#msgbox{{!!c#The following elements were found in ${s}. This list can be further refined. !!t#ELEMENTS !!btn#getrepeating{{!!s#${s} !!sfxn#?{Naming attribute|${attr_nameguess}} !!sfxa#${suffixRX.exec(val.get('name'))[1]} !!c#${character.id} !!op#b !!f#n}} !!send#true !!wto#${theSpeaker.localName}}}`;
menufor = ia.BtnAPI({ bg: bg, api: menuapi, label: "Build", charid: character.id, css: css });
} else { // just text, so encode it so it doesn't break the output
retval = htmlCoding(retval, true);
}
}
attrsuffix = suffixRX.exec(val.get('name'))[1];
infoapi = `!ia --whisper --show#msgbox{{!!c#puttext{{!!a#repeating_${s}_${uniquekeys[pos]}_${attrsuffix} !!b#\`br\` !!c#repeating_${s}_$${pos}_${attrsuffix} !!d#\`br\` !!e#${val.id}}} !!t#ATTRIBUTE INFO !!send#true !!wto#${theSpeaker.localName}}}`;
infobtn = ia.BtnAPI({ bg: bg, api: infoapi, label: "Info", charid: character.id, css: css });
return a + rowtemplate.replace("__bg__", rowbg[(i % 2)]).replace("__cell1__", `<table style="width:100%;"><tr><td style="text-align:left;">${suffixRX.exec(val.get('name'))[1]}</td><td style="text-align:right;">${infobtn}</td></tr></table>`).replace("__cell2__", menufor).replace("__cell3__", retval);
}, attrheader);
let apixray = pos === 0 ? '' : `!xray --${character.id}#${s} --${pos - 1}`;
let pbtn = apixray ? ia.BtnAPI({ bg: bg, api: apixray, label: "PREV", charid: character.id, css: css }) : '';
apixray = pos === uniquekeys.length - 1 ? '' : `!xray --${character.id}#${s} --${pos + 1}`;
let nbtn = apixray ? ia.BtnAPI({ bg: bg, api: apixray, label: "NEXT", charid: character.id, css: css }) : '';
let msg = `${attrtable.replace("__TABLE-ROWS__", attrrows)}<div style="width:100%;overflow:hidden;"><div style="float:left;text-align:left;width:50%;display:inline-block;">${pbtn}</div><div style="float:right;text-align:right;width:50%;display:inline-block;">${nbtn}</div></div>`;
sendChat('API', `/w ${theSpeaker.localName} ${msg}`);
return;
};
const xraystandard = ({
// provides a listing of non-repeating attributes or abilities from position "pos"
// number of objects to show determined by "num" parameter
s: s = "attribute", // section
v: v = "c", // attribute value to retrieve (c: current, m: max; a: action)
character: character, // character object (should be identified by now)
css: css = "", // free input css for api button
bg: bg = "", // background color for api button
ord: ord = 'a', // sort order for returned objects
pos: pos = 0, // position of element to check in repeating list
cfgObj: cfgObj, // configuration settings
theSpeaker: theSpeaker, // speaker object from the message
num: num = 25 // number of objects to show in one go
}) => {
if (!bg) bg = cfgObj.bg;
if (!css) css = cfgObj.css;
ord = ['d', 'a'].includes(ord) ? ord : 'n'; // anything other than 'a' (ascending) or 'd' (descending) triggers no sort order
v = ['m', 'max'].includes(v) ? 'max' : 'current'; // catch all attributes... and...
v = s === 'ability' ? 'action' : v; // correct for abilities (if necessary)
let sheetObjs = findObjs({ type: s, characterid: character.id });
if (s === 'attribute') sheetObjs = sheetObjs.filter(a => !a.get('name').startsWith('repeating'));
switch (ord) {
case 'a':
sheetObjs = sheetObjs.sort((a, b) => a.get('name') > b.get('name') ? 1 : -1);
break;
case 'd':
sheetObjs = sheetObjs.sort((a, b) => a.get('name') > b.get('name') ? -1 : 1);
break;
case 'n':
default:
break;
}
pos = parseInt(pos);
if (isNaN(pos)) {
ia.MsgBox({ c: `xray: Argument 'pos' not recognized as number.`, t: `INVALID POSITION`, send: true, wto: theSpeaker.localName });
return;
}
if (pos >= sheetObjs.length || pos < 0) {
ia.MsgBox({ c: `Argument 'pos' out of scope. Min value is 0. Max value for this character is ${sheetObjs.length - 1}.`, t: `INVALID POSITION`, send: true, wto: theSpeaker.localName });
return;
}
if (num === 'all' || isNaN(Number(num))) {
pos = 0;
num = sheetObjs.length;
} else {
num = parseInt(num);
if (num + pos > sheetObjs.length) num = sheetObjs.length - pos;
}
let allObjsCount = sheetObjs.length;
sheetObjs = sheetObjs.slice(pos, pos + num);
let retval = "",
menufirst5 = "",
menulast5 = "",
menuapi = "",
attrtable = msgtable.replace("__bg__", rowbg[0]),
attrheader = msg1header.replace("__colspan__", '3').replace("__bg__", rowbg[1]).replace("__cell1__", `XRAY: ${character.get('name').toUpperCase()}: ${s}`) + msg3header.replace("__bg__", rowbg[1]).replace("__cell1__", s.toUpperCase()).replace("__cell2__", "MENU").replace("__cell3__", attrValTable[v].toUpperCase()),
rowtemplate = msg3row,
outputrows = sheetObjs.reduce((a, val, i) => {
retval = val.get(attrValTable[v]);
menufirst5 = "";
menulast5 = "";
menuapi = "";
if (typeof retval === "string" && retval !== "") {
if (execCharSet.includes(retval.charAt(0)) || s === 'ability') { // look for executable statements, if found, we will construct 4 buttons
retval = ia.BtnAPI({ bg: bg, api: `!xray --read --${character.id}#${val.get('name')}`, label: "View", charid: character.id, css: css }) + " " +
ia.BtnElem({ bg: bg, store: val.get('name'), label: "Exec", charname: character.get('name'), entity: btnElem[s], css: css });
menuapi = `!ia --whisper --show#msgbox{{!!c#The following ${s === 'attribute' ? 'attributes' : 'abilities'} were found matching the first 5 characters of the chosen ${s}. This list can be further refined. !!t#ELEMENTS !!btn#get${s.slice(0, 4)}s{{!!c#${character.id} !!op#b !!f#${s === 'attribute' ? 'x#' : ''}^f#\`${val.get('name').slice(0, 5)}\`}} !!send#true !!wto#${theSpeaker.localName}}}`;
menufirst5 = ia.BtnAPI({ bg: bg, api: menuapi, label: "Starts", charid: character.id, css: css });
menuapi = `!ia --whisper --show#msgbox{{!!c#The following ${s === 'attribute' ? 'attributes' : 'abilities'} were found matching the last 5 characters of the chosen ${s}. This list can be further refined. !!t#ELEMENTS !!btn#get${s.slice(0, 4)}s{{!!c#${character.id} !!op#b !!f#${s === 'attribute' ? 'x#' : ''}f^#${val.get('name').slice(-5)}}} !!send#true !!wto#${theSpeaker.localName}}}`;
menulast5 = ia.BtnAPI({ bg: bg, api: menuapi, label: "Ends", charid: character.id, css: css });
} else { // just text, so encode it so it doesn't break the output
retval = htmlCoding(retval, true);
}
}
return a + rowtemplate.replace("__bg__", rowbg[(i % 2)]).replace("__cell1__", val.get('name')).replace("__cell2__", `${menufirst5} ${menulast5}`).replace("__cell3__", retval);
}, attrheader);
let apixray = parseInt(pos) - parseInt(num) < 0 ? '' : `!xray --${character.id}#${s} --${parseInt(pos) - parseInt(num)}#${num}`;
let pbtn = apixray ? ia.BtnAPI({ bg: bg, api: apixray, label: "PREV", charid: character.id, css: css }) : '';
apixray = parseInt(pos) + parseInt(num) >= allObjsCount ? '' : `!xray --${character.id}#${s} --${parseInt(pos) + parseInt(num)}#${num}`;
let nbtn = apixray ? ia.BtnAPI({ bg: bg, api: apixray, label: "NEXT", charid: character.id, css: css }) : '';
let msg = `${attrtable.replace("__TABLE-ROWS__", outputrows)}<div style="width:100%;overflow:hidden;"><div style="float:left;text-align:left;width:50%;display:inline-block;">${pbtn}</div><div style="float:right;text-align:right;width:50%;display:inline-block;">${nbtn}</div></div>`;
sendChat('API', `/w ${theSpeaker.localName} ${msg}`);
return;
};
const viewxray = ({
// for a given character and element, returns a message box to let you read it
character: character, // character
elem: elem, // the sheet object to read
css: css = "", // free input css for api button
bg: bg = "", // background color for api button
theSpeaker: theSpeaker,
cfgObj: cfgObj
} = {}) => {
let obj = ia.AbilFromAmbig(`${character}|${elem}`) || ia.AttrFromAmbig(`${character}|${elem}`);
if (!obj) {
ia.MsgBox({ c: 'Could not find that sheet object.', t: 'NO SUCH ELEMENT', send: true, wto: theSpeaker.localName });
return;
}
ia.MsgBox({ c: htmlCoding(obj.get('type') === 'attribute' ? obj.get('current') : obj.get('action'), true), t: `TEXT OF ${obj.get('name')}`, send: true, wto: theSpeaker.localName });
return;
};
// ==================================================
// HANDLE INPUT
// ==================================================
const handleInput = (msg_orig) => {
if (!(msg_orig.type === "api" && /^!xray(?:\s|$)/.test(msg_orig.content))) return;
let theSpeaker = getTheSpeaker(msg_orig);
let cfgObj = ia.GetIndivConfig(theSpeaker);
let bg = cfgObj.bg;
let css = cfgObj.css;
let args = msg_orig.content.split(/\s+--/)
.slice(1) // get rid of api handle
let charsICon = findObjs({ type: 'character' });
if (!playerIsGM(msg_orig.playerid)) { // if the player isn't GM, limit to players they control
charsICon = charsICon.filter(c => {
return c.get('controlledby').split(/\s*,\s*/).includes(msg_orig.playerid) || c.get('controlledby').split(/\s*,\s*/).includes('all');
});
}
if (!charsICon.length) {
ia.MsgBox({ c: `xray: It doesn't look like you control any characters. Fix that and try again.`, t: `NO CHARACTERS`, send: true, wto: theSpeaker.localName });
return;
}
charsICon = charsICon.sort((a, b) => a.get('name') > b.get('name') ? 1 : -1);
const charsAvailForXray = (send = true) => {
btn = charsICon.map(c => ia.BtnAPI({ bg: bg, api: `!xray --${c.id}`, label: c.get('name'), css: css })).join(" ");
msg = `These characters are in your waiting room waiting for their xray. Click on one to continue.`;
return ia.MsgBox({ c: msg, t: 'AVAILABLE CHARACTERS', btn: btn, send: send, wto: theSpeaker.localName });
};
let msg = "", btn = "";
if (!args.length) {
charsAvailForXray();
return;
}
const getCharAndSection = (arg) => {
let [character, item] = arg.split("#");
character = charsICon.filter(c => c.id === (ia.CharFromAmbig(character) || { id: 0 }).id)[0];
if (character && item) {
switch (item) {
case 'ability':
case 'abilities':
item = 'ability';
break;
case 'attribute':
case 'attributes':
item = 'attribute';
break;
default:
item = findObjs({ type: 'attribute', characterid: character.id }).filter(a => new RegExp(`^repeating_${item}_.*`, 'g').test(a.get('name'))).length ? item : '';
if (!item) ia.MsgBox({ c: `xray: No section found to match ${mapArg}.`, t: `NO SECTION`, send: true, wto: theSpeaker.localName });
break;
}
}
return [character, item];
};
let action = 'scan', character, section, elem, pos = 0, num = 0;
let mapArg = args.shift(); // assign the first arg to mapArg
if (mapArg === 'read') {
action = 'read';
[character, elem] = args.shift().split("#");
} else if (mapArg.indexOf('#' > -1)) { // if there is a hash, we have a character and section
[character, section] = getCharAndSection(mapArg);
} else { // if we didn't have a character and a section, we should have a character, only
character = ia.CharFromAmbig(mapArg);
}
if (!character) {
ia.MsgBox({ c: `xray: No character found among those you can control for ${mapArg}.`, t: `NO CHARACTER`, send: true, wto: theSpeaker.localName });
charsAvailForXray();
return;
}
if (action === 'scan' && args.length) {
[pos = 0, num = 0] = args.shift().split("#"); // validation and sanitation of these values is handled in the appropriate called function (since they require the set of objects to review)
}
// by now, we have filled action, character, section and/or elem, pos, and num; we just have to output the correct information
if (action === 'scan') {
if (!character) { // scan, but no character, so give all characters the player controls
charsAvailForXray();
return;
}
if (section) { // character + section
switch (section) {
case 'ability': // 'abilities' has been flattened to 'ability' by now
xraystandard({ s: 'ability', character: character, css: css, bg: bg, pos: pos, num: num, cfgObj: cfgObj, theSpeaker: theSpeaker });
break;
case 'attribute': // 'attributes' has been flattened to 'attribute' by now
xraystandard({ s: 'attribute', character: character, css: css, bg: bg, pos: pos, num: num, cfgObj: cfgObj, theSpeaker: theSpeaker });
break;
default:
xraysection({ s: section, character: character, cfgObj: cfgObj, theSpeaker: theSpeaker, pos: pos });
}
} else { // character, no section = output available sections
xraysheet({ character: character, css: css, bg: bg, theSpeaker: theSpeaker, cfgObj: cfgObj });
}
} else if (action === 'read') {
if (!elem) {
ia.MsgBox({ c: `xray: No sheet item provided for read operation.`, t: `NO ITEM`, send: true, wto: theSpeaker.localName });
return;
}
viewxray({ character: character, elem: elem, theSpeaker: theSpeaker, cfgObj: cfgObj, bg: bg, css: css });
}
return;
};
const registerEventHandlers = () => {
on('chat:message', handleInput);
};
on('ready', () => {
versionInfo();
registerEventHandlers();
});
return {
// public interface
GetVrs: getVrs
};
})();
{ try { throw new Error(''); } catch (e) { API_Meta.InsertArg.lineCount = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - API_Meta.InsertArg.offset); } }
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _os = require('os');
var _os2 = _interopRequireDefault(_os);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var PingMessage = function () {
function PingMessage() {
_classCallCheck(this, PingMessage);
}
_createClass(PingMessage, null, [{
key: 'construct',
value: function construct(id) {
return {
id: id,
msg: 'I am still alive!',
os: {
mem: {
total: _os2.default.totalmem(),
free: _os2.default.freemem()
},
load: _os2.default.loadavg(),
uptime: _os2.default.uptime()
}
};
}
}]);
return PingMessage;
}();
exports.default = PingMessage;
|
'use strict';
(function() {
var env = '';
if (typeof module !== 'undefined' && module.exports) env = 'node';
var exports = {};
if (env === 'node') {
var layer = require('layer');
} else {
exports = this;
var layer = layer || this.layer;
}
exports.intercept = function (ctx, fn, interceptFn) {
var result = false;
var f = layer._find_context(ctx, fn, 0);
layer.set(ctx, fn, function() {
result = { called: true, args: Array.prototype.slice.call(arguments)};
if (interceptFn && typeof interceptFn === 'function') interceptFn(result);
layer.unset(f[0][f[1]]);
return new layer.Stop();
});
var resultFn = function() {
return result;
}
resultFn.reset = function() {
var status = true;
try {
layer.unset(f[0][f[1]]);
} catch(e) {
status = false;
}
return status;
}
return resultFn;
}
if (env === 'node') module.exports = exports.intercept;
})();
|
'use strict';
var mean = require('meanio');
var request = require('request');
var unescape = require('unescape');
exports.render = function(req, res) {
var modules = [];
// Preparing angular modules list with dependencies
for (var name in mean.modules) {
modules.push({
name: name,
module: 'mean.' + name,
angularDependencies: mean.modules[name].angularDependencies
});
}
function isAdmin() {
return req.user && req.user.roles.indexOf('admin') !== -1;
}
// Send some basic starting info to the view
res.render('index', {
user: req.user ? {
name: req.user.name,
_id: req.user._id,
username: req.user.username,
roles: req.user.roles
} : {},
modules: modules,
isAdmin: isAdmin,
adminEnabled: isAdmin() && mean.moduleEnabled('mean-admin')
});
};
exports.audio = function(req, res) {
request('http://www.haramain.info/feeds/posts/default', function (error, response, html) {
if (!error && response.statusCode === 200) {
var soundFiles = html.split('soundFile=');
var newHTML = unescape(html);
var titleNames = newHTML.split('<span style="color:');
var json = '[';
// Start at 1 because first element is some weird XML thing
for (var i = 1; i < soundFiles.length; i+=1) {
var fileEnding = soundFiles[i].indexOf('.mp3');
var fileName = soundFiles[i].substring(0, fileEnding) + '.mp3';
if (fileName.indexOf('Sheikh') > -1 && fileName.indexOf('Khutbah') < 1) {
json += '{"url": "' + fileName + '" },';
}
//
}
json = json.substring(0, json.length - 1) + ']';
var prayerLocationAndTime = [];
var surah = [];
var sheikh = [];
var beginning = '';
// Organize all the HTML into individual arrays
for (var j = 1; j < titleNames.length; j+=1) {
if (j % 3 === 1) {
beginning = titleNames[j].substring(titleNames[j].indexOf('>') + 1,50);
var prayerLocationAndTimeName = beginning.substring(0, beginning.indexOf('</span>'));
prayerLocationAndTimeName = prayerLocationAndTimeName.replace('\\', '');
prayerLocationAndTime.push(prayerLocationAndTimeName);
} else if (j % 3 === 2) {
beginning = titleNames[j].substring(titleNames[j].indexOf('>') + 1,50);
var surahName = beginning.substring(0, beginning.indexOf('</span>'));
surahName = surahName.replace('\\', '');
surah.push(surahName);
} else {
beginning = titleNames[j].substring(titleNames[j].indexOf('>') + 1,50);
var imamName = beginning.substring(0, beginning.indexOf('</span>'));
imamName = imamName.replace('\\', '');
sheikh.push(imamName);
}
}
var jsonArray = JSON.parse(json);
// Append Surah Name, Sheikh Name, and Prayer Location
for (var k = 0; k < jsonArray.length; k+=1) {
jsonArray[k].surah = surah[k];
jsonArray[k].sheikh = sheikh[k];
jsonArray[k].prayerlocation = prayerLocationAndTime[k];
}
res.json(jsonArray);
}
});
};
exports.audioNew = function(req, res) {
request('http://www.haramain.info/feeds/posts/default', function (error, response, html) {
if (!error && response.statusCode === 200) {
res.send(response);
}
});
};
|
import createMarkup from "../react.markup";
it("should return blank if no content", () => {
const result = createMarkup({
content: {
body: "false",
},
});
expect(result).toEqual({
__html: "",
});
});
it("should return from body prop by default", () => {
const result = createMarkup({
content: {
body: "<h1>test</h1>",
},
});
expect(result).toEqual({
__html: "<h1>test</h1>",
});
});
it("should allow setting a different prop for content", () => {
const result = createMarkup({
content: {
newBody: "<h1>test</h1>",
},
}, "newBody");
expect(result).toEqual({
__html: "<h1>test</h1>",
});
});
|
// Example input: [ '6', '-26 -25 -28 31 2 27' ]
function largerThanNeighbours(args) {
var i,
count = 0,
len = +args[0],
myArray = args[1].split(' ').map(Number);
for (i = 1; i < len - 1; i += 1) {
if (myArray[i] > myArray[i - 1] && myArray[i] > myArray[i + 1]) {
count += 1;
}
}
return count;
}
console.log(largerThanNeighbours([ '6', '-26 -25 -28 31 2 27' ]));
|
"use strict";
var util = require("util");
/**
* InvalidRateLimitConfiguration error triggered when passed invalid configurations.
*
* @param {String} description Extended description
* @returns {void}
*/
function InvalidRateLimiterConfiguration(description) {
Error.captureStackTrace(this, this.constructor);
this.statusCode = 421;
this.name = this.constructor.name;
this.message = "Invalid rate limit configuration !!!";
if (description) {
this.message += " " + description;
}
}
util.inherits(InvalidRateLimiterConfiguration, Error);
module.exports = InvalidRateLimiterConfiguration;
|
'use strict';
var assert = require('chai').assert;
var LinePredictor = require('../src/js/model/linePredictor.js').LinePredictor;
var Geometry = require('../src/js/model/geometry.js').Geometry;
var Line = require('../src/js/model/line.js').Line;
Geometry.init();
Line.init();
function Target (x, y) {
this.left = x;
this.top = y;
this.right = x + 100;
this.bottom = y + 35;
}
Target.prototype.getBoundingClientRect = function () {
return this;
}
var targets = [
new Target(0, 0),
new Target(110, 0),
new Target(220, 0),
new Target(330, 0),
new Target(440, 0),
new Target(550, 0),
new Target(0, 100),
new Target(110, 100),
new Target(220, 100),
new Target(330, 100),
new Target(440, 100),
new Target(550, 100),
];
var fixations = [
{x: 30, y: 15, saccade: {x: 0, y: 0, newLine: false}},
{x: 130, y: 10, saccade: {x: 100, y: -5, newLine: false}},
{x: 250, y: -5, saccade: {x: 120, y: -15, newLine: false}},
{x: 370, y: 5, saccade: {x: 120, y: 10, newLine: false}},
{x: 470, y: -10, saccade: {x: 100, y: -15, newLine: false}},
{x: 490, y: 5, saccade: {x: 20, y: 15, newLine: false}},
{x: 590, y: 0, saccade: {x: 100, y: -5, newLine: false}},
{x: 200, y: 30, saccade: {x: -290, y: 30, newLine: true}},
{x: 30, y: 120, saccade: {x: -170, y: 90, newLine: true}},
{x: 130, y: 120, saccade: {x: 100, y: 0, newLine: false}},
{x: 250, y: 115, saccade: {x: 120, y: -5, newLine: false}},
{x: 370, y: 100, saccade: {x: 120, y: -15, newLine: false}},
{x: 470, y: 95, saccade: {x: 100, y: -5, newLine: false}},
{x: 490, y: 95, saccade: {x: 20, y: 0, newLine: false}},
{x: 590, y: 90, saccade: {x: 100, y: -5, newLine: false}},
];
var model = Geometry.create( targets );
LinePredictor.init( model );
var input = fixations.map( (fix, index) => {
return {
fix: fix,
isReading: index > 1
};
});
describe( 'LinePredictor', function() {
describe( '#get( isEnteredReadingMode, currentFixation, currentLine, offset )', function () {
var line = null;
var results = input.map( (item) => {
console.log( '\n ===== NEW FIX =====\n' );
line = LinePredictor.get( item.isReading, item.fix, line, 0 );
if (line) {
line.addFixation( item.fix );
}
return line;
});
it( `should all fixations be mapped`, function () {
let fixCount = results.reduce( (count, line) => {
return count + (!line ? 1 : 0);
}, 0);
assert.equal( 0, fixCount );
});
it( `should 8 fixations be mapped onto line 0`, function () {
let fixCount = results.reduce( (count, line) => {
return count + (line && line.index === 0 ? 1 : 0);
}, 0);
assert.equal( 8, fixCount );
});
it( `should 7 fixations be mapped onto line 1`, function () {
let fixCount = results.reduce( (count, line) => {
return count + (line && line.index === 1 ? 1 : 0);
}, 0);
assert.equal( 7, fixCount );
});
});
});
|
var shovel = require('../shovel'),
util = require('../util'),
temp = require('temp');
module.exports.run = function run(opts, cb) {
temp.track();
var racketCodeDir = temp.mkdirSync('racket'),
args = ['-l', 'racket/base'];
shovel.start(opts, cb, {
solutionOnly: function () {
if (opts.setup) {
var setupFile = util.codeWriteSync('racket', opts.setup, racketCodeDir, 'setup.rkt');
args.push('-t', setupFile);
}
args.push('-e', opts.solution);
return {
name: 'racket',
args: args
};
},
fullProject: function () {
throw 'Test framework is not supported';
}
});
};
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
requirejs: {
compile: {
options: {
paths: { requireLib: 'node_modules/requirejs/require' },
include: [ "requireLib" ],
baseUrl: ".",
mainConfigFile: "app.js",
name: "app",
optimize: "uglify2",
out: "<%= pkg.name %>.min.js"
}
}
}
});
// load libs
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-exec');
// building task
grunt.registerTask('build', [ 'requirejs' ]);
};
|
var d3 = require('d3');
function true_index(arr, config) {
// Series.ix[start, end].true().index;
if (!config) { config = {}; }
if (!config.length) { config.length = arr.length }
config.start = config.start ? config.start : 0;
config.end = config.end ? config.end : config.length;
var valid = new Array(config.length);
var j = 0;
for (var i=config.start; i <= config.end; i++) {
if (arr[i]) {
valid[j] = i;
j++;
}
}
valid = valid.slice(0, j);
return valid;
}
function where(arr, mask) {
var data = arr.slice(0);
for (var i=0; i < data.length; i++) {
if (!mask[i]) {
data[i] = null;
}
}
return data;
}
module.exports.true_index = true_index;
module.exports.where = where;
mask = [true, true, false, false, true, false]
series = d3.range(mask.length);
res = true_index(mask, {});
res = true_index(mask, {'start':1});
res = where(series, mask);
|
if (process.title !== 'browser') {
switch (process.env.KADOH_TRANSPORT) {
default:
case 'xmpp':
//@browserify-ignore
module.exports = require('./node-xmpp');
break;
case 'udp':
//@browserify-ignore
module.exports = require('./udp') ;
break;
}
} else {
switch (process.env.KADOH_TRANSPORT) {
default:
case 'xmpp':
module.exports = require('./strophe');
break;
case 'simudp':
module.exports = require('./simudp');
break;
}
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdForum = function MdForum(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm28.4 20q0 0.7-0.5 1.2t-1.3 0.4h-16.6l-6.6 6.8v-23.4q0-0.7 0.4-1.2t1.2-0.4h21.6q0.7 0 1.3 0.4t0.5 1.2v15z m6.6-10q0.7 0 1.2 0.5t0.4 1.1v25l-6.6-6.6h-18.4q-0.7 0-1.1-0.5t-0.5-1.1v-3.4h21.6v-15h3.4z' })
)
);
};
exports.default = MdForum;
module.exports = exports['default'];
|
var cooking = require('cooking');
var path = require('path');
cooking.set({
entry: {
index: path.join(__dirname, 'index.js')
},
dist: path.join(__dirname, 'lib'),
template: false,
format: 'umd',
moduleName: 'MintIndicator',
extractCSS: 'style.css',
extends: ['vue', 'saladcss']
});
cooking.add('resolve.alias', {
'main': path.join(__dirname, '../../src'),
'mint-ui': path.join(__dirname, '..')
});
cooking.add('externals', {
vue: {
root: 'Vue',
commonjs: 'vue',
commonjs2: 'vue',
amd: 'vue'
}
});
module.exports = cooking.resolve();
|
import { connect } from 'react-redux'
import { helloWorld } from '../actions'
import Hello from './../components/Hello'
const mapStateToProps = (state) => {
return {
message: state.hello.message
}
}
const mapDispatchToProps = (dispatch) => {
return {
onClick: () => {
dispatch(helloWorld())
}
}
}
const HelloWorld = connect(
mapStateToProps,
mapDispatchToProps
)(Hello)
export default HelloWorld
|
/* */
define( [
"../core"
], function( jQuery ) {
"use strict";
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
return jQuery.parseXML;
} );
|
'use strict'
exports.register = function(server, options, next){
server.route([
{
method: 'GET',
path: '/createuser',
config: {
// Uncomment for security
//auth: {
// strategy: 'standard',
// scope: 'admin'
//},
handler: function(request, reply) {
return reply('<html><head><title>User Creation</title></head><body>' +
'<form method="post" action="/createuser">' +
'New Username:<br><input type="text" name="create_username" ><br>' +
'New Email:<br><input type="text" name="create_email" ><br>' +
'New Password:<br><input type="password" name="create_password"><br/><br/>' +
'Scope:<br><input type="text" name="create_scope"><br/><br/>' +
'Survey:<br><input type="int" name="survey_access_number"><br/><br/>' +
'<input type="submit" value="Create User"></form></body></html>')
}
}
},
{
method: 'POST',
path: '/createuser',
config: {
// Uncomment for security
//auth: {
// strategy: 'standard',
// scope: 'admin'
//},
handler: function(request, reply) {
const User = server.plugins['hapi-shelf'].model('Users')
const user = new User()
.save({
username: request.payload.create_username,
email: request.payload.create_email,
password: request.payload.create_password,
scope: request.payload.create_scope,
survey: request.payload.survey_access_number
})
.then(function(new_user) {
reply.redirect('/allusers')
})
.catch()
}
}
},
{
method: 'GET',
path: '/allusers',
config: {
handler: function(request, reply) {
const User = server.plugins['hapi-shelf'].model('Users')
reply(User
.fetchAll()
)
}
}
}])
next()
}
exports.register.attributes = {
name: 'newuser'
}
|
BASE.require([
"BASE.sqlite.Visitor"
],
function () {
});
|
// This file is part of Indico.
// Copyright (C) 2002 - 2019 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
(function(global) {
'use strict';
global.setupLinkingWidget = function setupLinkingWidget(options) {
options = $.extend(
true,
{
fieldId: null,
},
options
);
function updateDropdownState() {
var $this = $(this);
if ($this.prop('checked')) {
$this
.closest('.i-radio')
.siblings('.i-radio')
.find('.i-linking-dropdown select')
.prop('disabled', true);
$this
.siblings('.i-linking-dropdown')
.find('select')
.prop('disabled', false);
}
}
var field = $('#' + options.fieldId);
field
.find('.i-linking > .i-linking-dropdown > select > option[value=""]')
.prop('disabled', true);
field
.find('.i-linking.i-radio > input[type="radio"]')
.off('change')
.on('change', updateDropdownState)
.each(updateDropdownState);
};
})(window);
|
/**
@ngdoc directive
@name umbraco.directives.directive:umbChildSelector
@restrict E
@scope
@description
Use this directive to render a ui component for selecting child items to a parent node.
<h3>Markup example</h3>
<pre>
<div ng-controller="My.Controller as vm">
<umb-child-selector
selected-children="vm.selectedChildren"
available-children="vm.availableChildren"
parent-name="vm.name"
parent-icon="vm.icon"
parent-id="vm.id"
on-add="vm.addChild"
on-remove="vm.removeChild">
</umb-child-selector>
<!-- use overlay to select children from -->
<umb-overlay
ng-if="vm.overlay.show"
model="vm.overlay"
position="target"
view="vm.overlay.view">
</umb-overlay>
</div>
</pre>
<h3>Controller example</h3>
<pre>
(function () {
"use strict";
function Controller() {
var vm = this;
vm.id = 1;
vm.name = "My Parent element";
vm.icon = "icon-document";
vm.selectedChildren = [];
vm.availableChildren = [
{
id: 1,
alias: "item1",
name: "Item 1",
icon: "icon-document"
},
{
id: 2,
alias: "item2",
name: "Item 2",
icon: "icon-document"
}
];
vm.addChild = addChild;
vm.removeChild = removeChild;
function addChild($event) {
vm.overlay = {
view: "itempicker",
title: "Choose child",
availableItems: vm.availableChildren,
selectedItems: vm.selectedChildren,
event: $event,
show: true,
submit: function(model) {
// add selected child
vm.selectedChildren.push(model.selectedItem);
// close overlay
vm.overlay.show = false;
vm.overlay = null;
}
};
}
function removeChild($index) {
vm.selectedChildren.splice($index, 1);
}
}
angular.module("umbraco").controller("My.Controller", Controller);
})();
</pre>
@param {array} selectedChildren (<code>binding</code>): Array of selected children.
@param {array} availableChildren (<code>binding</code>: Array of items available for selection.
@param {string} parentName (<code>binding</code>): The parent name.
@param {string} parentIcon (<code>binding</code>): The parent icon.
@param {number} parentId (<code>binding</code>): The parent id.
@param {callback} onRemove (<code>binding</code>): Callback when removing an item.
<h3>The callback returns:</h3>
<ul>
<li><code>child</code>: The selected item.</li>
<li><code>$index</code>: The selected item index.</li>
</ul>
@param {callback} onAdd (<code>binding</code>): Callback when adding an item.
<h3>The callback returns:</h3>
<ul>
<li><code>$event</code>: The select event.</li>
</ul>
@param {callback} onSort (<code>binding</code>): Callback when sorting an item.
<h3>The callback returns:</h3>
<ul>
<li><code>$event</code>: The select event.</li>
</ul>
**/
(function() {
'use strict';
function ChildSelectorDirective() {
function link(scope, el, attr, ctrl) {
var eventBindings = [];
scope.dialogModel = {};
scope.showDialog = false;
scope.removeChild = function(selectedChild, $index) {
if(scope.onRemove) {
scope.onRemove(selectedChild, $index);
}
};
scope.addChild = function($event) {
if(scope.onAdd) {
scope.onAdd($event);
}
};
function syncParentName() {
// update name on available item
angular.forEach(scope.availableChildren, function(availableChild){
if(availableChild.id === scope.parentId) {
availableChild.name = scope.parentName;
}
});
// update name on selected child
angular.forEach(scope.selectedChildren, function(selectedChild){
if(selectedChild.id === scope.parentId) {
selectedChild.name = scope.parentName;
}
});
}
function syncParentIcon() {
// update icon on available item
angular.forEach(scope.availableChildren, function(availableChild){
if(availableChild.id === scope.parentId) {
availableChild.icon = scope.parentIcon;
}
});
// update icon on selected child
angular.forEach(scope.selectedChildren, function(selectedChild){
if(selectedChild.id === scope.parentId) {
selectedChild.icon = scope.parentIcon;
}
});
}
eventBindings.push(scope.$watch('parentName', function(newValue, oldValue){
if (newValue === oldValue) { return; }
if (oldValue === undefined || newValue === undefined) { return; }
syncParentName();
}));
eventBindings.push(scope.$watch('parentIcon', function(newValue, oldValue){
if (newValue === oldValue) { return; }
if (oldValue === undefined || newValue === undefined) { return; }
syncParentIcon();
}));
// sortable options for allowed child content types
scope.sortableOptions = {
axis: "y",
cancel: ".unsortable",
containment: "parent",
distance: 10,
opacity: 0.7,
tolerance: "pointer",
scroll: true,
zIndex: 6000,
update: function (e, ui) {
if(scope.onSort) {
scope.onSort();
}
}
};
// clean up
scope.$on('$destroy', function(){
// unbind watchers
for(var e in eventBindings) {
eventBindings[e]();
}
});
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/umb-child-selector.html',
scope: {
selectedChildren: '=',
availableChildren: "=",
parentName: "=",
parentIcon: "=",
parentId: "=",
onRemove: "=",
onAdd: "=",
onSort: "="
},
link: link
};
return directive;
}
angular.module('umbraco.directives').directive('umbChildSelector', ChildSelectorDirective);
})();
|
'use strict'
var fs = require('graceful-fs')
var path = require('path')
var mkdirpSync = require('mkdirp').sync
var rimraf = require('rimraf')
var test = require('tap').test
var common = require('../common-tap.js')
var base = common.pkg
var cruft = path.join(base, 'node_modules', 'cruuuft')
var pkg = {
name: 'example',
version: '1.0.0',
dependencies: {}
}
function setup () {
mkdirpSync(path.dirname(cruft))
fs.writeFileSync(cruft, 'this is some cruft for sure')
fs.writeFileSync(path.join(base, 'package.json'), JSON.stringify(pkg))
}
function cleanup () {
rimraf.sync(base)
}
test('setup', function (t) {
cleanup()
setup()
t.done()
})
test('cruft', function (t) {
common.npm(['ls'], {cwd: base}, function (er, code, stdout, stderr) {
t.is(stderr, '', 'no warnings or errors from ls')
t.done()
})
})
test('cleanup', function (t) {
cleanup()
t.done()
})
|
var _INCLUDED = false;
module.exports = function() {
var BandRenderer = require('../../../core/renderers/band_renderer.js');
if (_INCLUDED) { return BandRenderer; }
_INCLUDED = true;
// cached state object, for quick access during rendering, populated in begin() method:
BandRenderer.hasA("state");
BandRenderer.respondsTo("begin", function (context) {
var state = {
"context" : context,
"run" : [],
"linecolor" : this.getOptionValue("linecolor"),
"line1color" : this.getOptionValue("line1color"),
"line2color" : this.getOptionValue("line2color"),
"linewidth" : this.getOptionValue("linewidth"),
"line1width" : this.getOptionValue("line1width"),
"line2width" : this.getOptionValue("line2width"),
"fillcolor" : this.getOptionValue("fillcolor"),
"fillopacity" : this.getOptionValue("fillopacity")
};
this.state(state);
});
// This renderer's dataPoint() method works by accumulating
// and drawing one "run" of data points at a time. A "run" of
// points consists of a consecutive sequence of non-missing
// data points which have the same fill color. (The fill
// color can change if the data line crosses the fill base
// line, if the downfillcolor is different from the
// fillcolor.)
BandRenderer.respondsTo("dataPoint", function (datap) {
var state = this.state();
if (this.isMissing(datap)) {
// if this is a missing point, render and reset the current run, if any
if (state.run.length > 0) {
this.renderRun();
state.run = [];
}
} else {
// otherwise, transform point to pixel coords
var p = this.transformPoint(datap);
// and add it to the current run
state.run.push(p);
}
});
BandRenderer.respondsTo("end", function () {
var state = this.state();
// render the current run, if any
if (state.run.length > 0) {
this.renderRun();
}
});
/*
* Private utility function to stroke line segments connecting the points of a run
*/
var strokeRunLine = function(context, run, whichLine, color, defaultColor, width, defaultWidth) {
var i;
width = (width >= 0) ? width : defaultWidth;
if (width > 0) {
color = (color !== null) ? color : defaultColor;
context.save();
context.strokeStyle = color.getHexString("#");
context.lineWidth = width;
context.beginPath();
context.moveTo(run[0][0], run[0][whichLine]);
for (i = 1; i < run.length; ++i) {
context.lineTo(run[i][0], run[i][whichLine]);
}
context.stroke();
context.restore();
}
};
// Render the current run of data points. This consists of drawing the fill region
// in the band between the two data lines, and connecting the points of each data line
// with lines of the appropriate color.
BandRenderer.respondsTo("renderRun", function () {
var state = this.state(),
context = state.context,
run = state.run,
i;
// fill the run
context.save();
context.globalAlpha = state.fillopacity;
context.fillStyle = state.fillcolor.getHexString("#");
context.beginPath();
// trace to the right along line 1
context.moveTo(run[0][0], run[0][1]);
for (i = 1; i < run.length; ++i) {
context.lineTo(run[i][0], run[i][1]);
}
// trace back to the left along line 2
context.lineTo(run[run.length-1][0], run[run.length-1][2]);
for (i = run.length-1; i >= 0; --i) {
context.lineTo(run[i][0], run[i][2]);
}
context.fill();
context.restore();
// stroke line1
strokeRunLine(context, run, 1, state.line1color, state.linecolor, state.line1width, state.linewidth);
// stroke line2
strokeRunLine(context, run, 2, state.line2color, state.linecolor, state.line2width, state.linewidth);
});
BandRenderer.respondsTo("renderLegendIcon", function (context, x, y, icon) {
var state = this.state(),
iconWidth = icon.width(),
iconHeight = icon.height();
context.save();
context.transform(1, 0, 0, 1, x, y);
context.save();
// Draw icon background (with opacity)
if (iconWidth < 10 || iconHeight < 10) {
context.fillStyle = state.fillcolor.toRGBA();
} else {
context.fillStyle = "#FFFFFF";
}
context.fillRect(0, 0, iconWidth, iconHeight);
context.restore();
// Draw icon graphics
context.strokeStyle = (state.line2color !== null) ? state.line2color : state.linecolor;
context.lineWidth = (state.line2width >= 0) ? state.line2width : state.linewidth;
context.fillStyle = state.fillcolor.toRGBA(state.fillopacity);
context.beginPath();
context.moveTo(0, 2*iconHeight/8);
context.lineTo(0, 6*iconHeight/8);
context.lineTo(iconWidth, 7*iconHeight/8);
context.lineTo(iconWidth, 3*iconHeight/8);
context.lineTo(0, 2*iconHeight/8);
context.fill();
context.stroke();
context.restore();
});
return BandRenderer;
};
|
import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import Welcome from '../../src/js/components/Welcome';
describe('Welcome Component', () => {
var welcomeComponent;
beforeEach(() => {
welcomeComponent = shallow(<Welcome />);
});
it('renders Mikey Welcomes You! in a h1 tag', () => {
expect(welcomeComponent.find('h1').text()).to.equal('Mikey Welcomes You!');
});
it('renders Use the latest web development technologies. in a h2 tag', () => {
expect(welcomeComponent.find('h2').text()).to.equal('Use the latest web development technologies.');
});
});
|
export default {
'ACT': 'Australian Capital Territory',
'NSW': 'New South Wales',
'NT' : 'Northern Territory',
'QLD': 'Queensland',
'SA' : 'South Australia',
'TAS': 'Tasmania',
'VIC': 'Victoria',
'WA' : 'Western Australia'
}
|
if( typeof module !== 'undefined' )
require( 'wFiles' )
var _ = wTools;
/* filesCopy HardDrive -> Extract */
var hub = _.FileProvider.Hub();
var simpleStructure = _.FileProvider.Extract
({
filesTree : Object.create( null )
});
hub.providerRegister( simpleStructure );
var hdUrl = _.fileProvider.urlFromLocal( _.normalize( __dirname ) );
var ssUrl = simpleStructure.urlFromLocal( '/dir/copy/to' );
hub.filesCopy
({
dst : ssUrl,
src : hdUrl,
preserveTime : 0
});
var tree = _.entity.exportString( simpleStructure.filesTree, { levels : 4 } );
console.log( tree );
|
version https://git-lfs.github.com/spec/v1
oid sha256:e330e85aabf65a6116144dfe2e726f649a1cdfd88a33e6ce4e3a39f40ebadfbb
size 153184
|
/**
* report business validation library
*/
var async = require('async');
module.exports = function(services, logger) {
var me = this;
me.validate = function(object, callback) {
var errors = [];
me.done = function() {
var bVal = {valid: !(errors.length), errors: errors};
callback(bVal);
};
me.validateObject(object, errors, me.done);
};
/**
* Default messages to include with validation errors.
*/
me.messages = {
alpha_report_id: "Alpha Report id is invalid",
target_event_id: "Target Event id is invalid",
profile_id: "Profile id is invalid",
assertions: "Assertions are invalid"
};
me.validateObject = function(object, errors, done) {
var value = object.alpha_report_id;
me.alphaReportExists(value, errors, function (err, found) {
var property = 'alpha_report_id';
if (value !== undefined){
if (!found) {
me.error(property, value, errors, "Alpha Report does not exist.");
logger.debug("alphaReportExists " + value + " does not exist.");
}
}
value = object.target_event_id;
me.targetEventExists(value, errors, function(err, found) {
var property = 'target_event_id';
if (value !== undefined) {
if (!found){
me.error(property, value, errors, "Target Event does not exist.");
logger.debug("targetEventExists " + value + " does not exist.");
}
}
value = object.profile_id;
me.profileExists(value, errors, function(err, found) {
var property = 'profile_id';
if (value !== undefined) {
if (!found) {
me.error(property, value, errors, "Profile does not exist.");
logger.debug("profileExists " + value + " does not exist");
}
}
value = object.assertions;
me.assertionsExist(value, errors, function(err, found) {
var property = 'assertions';
if (value !== undefined) {
if (!found) {
me.error(property, value, errors, "Assertions do not exist.");
logger.info("assertionsExist " + value + " do not exist");
}
}
done();
});
});
});
});
};
//alpha report exists
me.alphaReportExists = function(value, errors, callback) {
services.alphaReportService.get(value, function(err, docs) {
if (err) {
me.error('alpha_report_id', value, errors, 'Error reading alpha_report_id ' + err);
logger.error("Error getting alphaReport by id ", err);
callback(err, false);
} else if (0 !== docs.length) {
logger.info("Alpha Report found for alphaReportExists" + JSON.stringify(docs));
callback(err, true);
} else {
logger.info("Alpha Report not found " + value);
callback(err, false);
}
});
};
me.targetEventExists = function(value, errors, callback) {
if(typeof(value) === 'undefined' || !value) {
callback(null, true);
} else {
services.targetEventService.get(value, function(err, docs){
if (err) {
me.error('target_event_id', value, errors, 'Error reading target_event_id ' + err);
me.logger.error("Error getting targetEvent by id ", err);
callback(err, false);
} else if (0 !== docs.length) {
me.logger.info("Target Event found for targetEventIsValid" + JSON.stringify(docs));
callback(err, true);
} else {
me.logger.info("Target Event not found " + value);
callback(err, false);
}
});
}
};
me.profileExists = function(value, errors, callback) {
if(typeof(value) === 'undefined' || !value) {
callback(null, true);
} else {
services.profileService.get(value, function(err, docs) {
if (err) {
me.error('profile_id', value, errors, 'Error reading profile ' + err);
logger.error("Error getting profile by id ", err);
callback(err, false);
} else if (0 !== docs.length) {
logger.info("Profile found for profile" + JSON.stringify(docs));
callback(err, true);
} else {
logger.info("Profile string not found " + value);
callback(err, false);
}
});
}
};
me.assertionsExist = function(value, errors, callback) {
if (typeof(value) === 'undefined' || value.length === 0) {
callback(null, true);
} else {
async.each(value, function(assertion, eachCallback) {
services.assertionService.get(assertion, function(err, assertionDoc) {
if (err) {
me.error('assertions', value, errors, 'Error reading assertion ' + err);
logger.error("Error getting assertion by id ", err);
eachCallback(err);
} else if (0 !== assertionDoc.length) {
logger.info("Assertion found for assertionsAreValid" + JSON.stringify(assertionDoc));
eachCallback(err);
} else {
logger.info("Assertion not found " + value);
eachCallback(err);
}
});
}, function (err) {
if (err) {
callback(err, false);
} else {
callback(err, true);
}
});
}
};
me.error = function(property, actual, errors, msg) {
var lookup = {
property : property
};
var message = msg || me.messages[property] || "no default message";
message = message.replace(/%\{([a-z]+)\}/ig, function(_, match) {
var msg = lookup[match.toLowerCase()] || "";
return msg;
});
errors.push({
property : property,
actual : actual,
message : message
});
};
};
|
win = windows.getAll()[0]
test(function() {
g[0] = groups.create(
[
{ url: "data:text/plain,1" },
{ url: "data:text/plain,2" },
{ url: "data:text/plain,yay" },
])
assert_equals(g[0].tabs.getAll().length, 3)
var tab = g[0].tabs.getAll()[2]
g[1] = groups.create(
[
tab, // <-- throws
{ url: "data:text/plain,9" }
])
assert_equals( g[0].tabs.getAll().length, 2)
assert_equals( g[1].tabs.getAll().length, 2)
}, "Create group in default window")
|
// @flow
import Bluebird from 'bluebird';
import type { Disposable } from 'bluebird';
const defer: Bluebird.Defer = Bluebird.defer();
const promise: Bluebird<*> = defer.promise;
(promise.isFulfilled(): bool);
promise.reflect().then(inspection => {
(inspection.isCancelled(): bool);
(inspection.pending(): bool);
});
// $FlowExpectedError
new Bluebird();
Bluebird.all([
new Bluebird(() => {}),
]);
Bluebird.map([1], (x: number) => new Bluebird(() => {})).all();
Bluebird.map(Bluebird.resolve([1]), (x: number) => new Bluebird(() => {})).all();
Bluebird.reject('test');
Bluebird.all([
1
]);
function mapper(x: number): Promise<number> {
return Bluebird.resolve(x);
}
let mapResult: Promise<number[]> = Bluebird.map([1], mapper);
let mapSeriesResult: Promise<number[]> = Bluebird.mapSeries([1], mapper);
Bluebird.resolve([1,2,3]).then(function(arr) {
let l = arr.length;
// $FlowExpectedError Property not found in Array
arr.then(r => r);
});
let response = fetch('/').then(r => r.text())
Bluebird.resolve(response).then(function(responseBody) {
let length: number = responseBody.length;
// $FlowExpectedError Property not found in string
responseBody.then(r => r);
});
Bluebird.all([1, Bluebird.resolve(1), Promise.resolve(1)]).then(function(r: Array<number>) { });
Bluebird.all(['hello', Bluebird.resolve('world'), Promise.resolve('!')]).then(function(r: Array<string>) { });
Bluebird.join(1, Bluebird.resolve(2), function (a, b) { return a + b }).then(function (s) { return s + 1 })
Bluebird.join(
1,
Bluebird.resolve(2),
Promise.resolve(3),
function (a, b) { return a + b }).then(function (s) { return s + 1 })
Bluebird.join(1, Bluebird.resolve(2),
function (a, b) { return Bluebird.resolve(a + b) }).then(function (s) { return s + 1 })
// $FlowExpectedError
Bluebird.all([1, Bluebird.resolve(1), Promise.resolve(1)]).then(function(r: Array<string>) { });
function foo(a: number, b: string) {
throw new Error('oh no');
}
let fooPromise = Bluebird.method(foo);
fooPromise(1, 'b').catch(function(e: Error) {
let m: string = e.message;
});
function fooPlain (a: number, b: string) {
return 1;
}
let fooPlainPromise = Bluebird.method(fooPlain);
fooPlainPromise(1, 'a').then(function (n: number) {
let n2 = n;
});
function fooNative (a: number, b: string) {
return Promise.resolve(2);
}
let fooNativePromise = Bluebird.method(fooNative);
fooNativePromise(1, 'a').then(function (n: number) {
let n2 = n;
});
function fooBluebird (a: number, b: string) {
return Bluebird.resolve(3);
}
let fooBluebirdPromise = Bluebird.method(fooBluebird);
fooBluebirdPromise(1, 'a').then(function (n: number) {
let n2 = n;
});
// $FlowExpectedError
fooPromise('a', 1)
// $FlowExpectedError
fooPromise()
Bluebird.resolve(['arr', { some: 'value' }, 42])
.spread((someString: string, map: Object, answer: number) => answer)
.then(answer => answer * 2);
Bluebird.reduce([5, Bluebird.resolve(6), Promise.resolve(7)], (memo, next) => memo + next);
Bluebird.reduce([5, Bluebird.resolve(6), Promise.resolve(7)], (memo, next) => memo + next, 1);
Bluebird.reduce([5, Bluebird.resolve(6), Promise.resolve(7)], (memo, next) => memo + next, Bluebird.resolve(1));
Bluebird.reduce([5, Bluebird.resolve(6), Promise.resolve(7)], (memo, next) => memo + next, Promise.resolve(1));
Bluebird.reduce(Promise.resolve([5, Bluebird.resolve(6), Promise.resolve(7)]), (memo, next) => memo + next);
Bluebird.reduce(Bluebird.resolve([5, Bluebird.resolve(6), Promise.resolve(7)]), (memo, next) => memo + next, 1);
Bluebird.reduce([1, Bluebird.resolve(2), Promise.resolve(3)], (prev, num) => Promise.resolve(prev * num));
Bluebird.reduce([1, Bluebird.resolve(2), Promise.resolve(3)], (prev, num) => Bluebird.resolve(prev * num));
//$FlowExpectedError
Bluebird.reduce([1, Bluebird.resolve(2), Promise.resolve(3)], (prev, num) => Bluebird.resolve(prev * num), 'hello');
type PromiseOutput<T> = () => Promise<T>;
let givePromise1: PromiseOutput<number> = () => Promise.resolve(1);
let givePromise2: PromiseOutput<number> = () => Bluebird.resolve(2);
// $FlowExpectedError
let givePromise3: PromiseOutput<number> = () => Bluebird.resolve('hello');
type PromiseInput<T> = (input: Promise<T>) => Function
let takePromise: PromiseInput<number> = (promise) => promise.then
takePromise(Promise.resolve(1));
takePromise(Bluebird.resolve(1));
// $FlowExpectedError
takePromise(Bluebird.resolve('hello'));
Bluebird.delay(500);
// $FlowExpectedError
Bluebird.delay('500');
Bluebird.delay(500, 1);
Bluebird.delay(500, Promise.resolve(5));
Bluebird.delay(500, Bluebird.resolve(5));
Bluebird.resolve().return(5).then((result: number) => {});
Bluebird.resolve().thenReturn(5).then((result: number) => {});
// $FlowExpectedError
Bluebird.resolve().return(5).then((result: string) => {});
// $FlowExpectedError
Bluebird.resolve().thenReturn(5).then((result: string) => {});
let disposable: Disposable<boolean> = Bluebird.resolve(true).disposer((value: boolean) => {});
Bluebird.using(disposable, (value: boolean) => 9).then((result: number) => {});
// $FlowExpectedError
Bluebird.using(disposable, (value: number) => 9);
// $FlowExpectedError
Bluebird.using(disposable, (value: boolean) => 9).then((result: boolean) => {});
|
"use strict";
input.map(function (item) {
return item + 1;
});
(function (a) {
return a + 1;
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="m12 17.27l4.15 2.51c.76.46 1.69-.22 1.49-1.08l-1.1-4.72 3.67-3.18c.67-.58.31-1.68-.57-1.75l-4.83-.41-1.89-4.46c-.34-.81-1.5-.81-1.84 0L9.19 8.63l-4.83.41c-.88.07-1.24 1.17-.57 1.75l3.67 3.18-1.1 4.72c-.2.86.73 1.54 1.49 1.08l4.15-2.5z" />
, 'StarRounded');
|
#!/usr/bin/env node
'use strict'
var fs = require('fs')
var Promise = require('promise')
var colors = require('colors')
var _ = require('underscore')
const areaNameRegex = new RegExp('^[a-zA-Z]+$')
const templatesDir = process.cwd() + '/_scripts/.templates'
const areasDir = process.cwd() + '/src/app/areas'
var areasToCreate = _.uniq(process.argv.slice(2))
var areasPromises = []
areasToCreate.forEach(function (areaName) {
if (canCreateArea(areasDir + '/' + areaName)) {
areasPromises.push(createAreaDirStructure(areaName))
} else {
areasToCreate = _.without(areasToCreate, areaName)
}
})
Promise.all(areasPromises).then(function (results) {
results.forEach(function (result, i) {
console.log(colors.cyan.bold('✔ Created area: ', areasToCreate[i]))
result.forEach(function (file) {
console.log(colors.green(' +'), file)
})
})
})
function dirExists (filePath) {
try {
return fs.statSync(filePath).isDirectory()
} catch (err) {
return false
}
}
function canCreateArea (areaName) {
if (areaNameRegex.test(areaName.split('/').pop())) {
if (dirExists(areaName)) {
console.log(colors.yellow('! Skipping', colors.bold(areaName.split('/').pop()), ', area already exists'))
return false
}
return true
} else {
console.log(colors.red('! Skipping', colors.bold(areaName.split('/').pop()), ', wrong name, you can use letters only'))
return false
}
}
function createAreaDirStructure (areaName) {
try {
const areaDir = areasDir + '/' + areaName
const areaTestsDir = areasDir + '/' + areaName + '/' + 'test'
var filePromises = []
process.chdir(areasDir)
fs.mkdirSync(areaName)
fs.mkdirSync(areaName + '/test')
filePromises.push(createFileFromTemplate(areaDir, 'actions.js', 'actions.tmpl.js', { areaName: areaName }))
filePromises.push(createFileFromTemplate(areaDir, 'reducer.js', 'reducer.tmpl.js', { areaName: areaName }))
filePromises.push(createFileFromTemplate(areaTestsDir, 'reducer.spec.js', 'reducer.spec.tmpl.js', { areaName: areaName }))
process.chdir(areasDir)
return Promise.all(filePromises)
} catch (e) {
return false
}
}
function createFileFromTemplate (dir, filename, templateName, templateData) {
return new Promise(function (resolve, reject) {
fs.readFile(templatesDir + '/' + templateName, function (err, data) {
var fileContent = new Buffer((_.template(data.toString()))(templateData))
process.chdir(dir)
fs.open(filename, 'w', function (err, fd) {
if (err) {
throw 'Error opening file: ' + err
}
fs.write(fd, fileContent, 0, fileContent.length, null, function (err) {
if (err) {
throw 'Error writing file: ' + err
}
fs.close(fd, function () {
process.chdir(areasDir)
resolve(dir + '/' + filename)
})
})
})
})
})
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "m14 16.64-4-1.45V17h4zM6 8.5c.15 0 .3-.03.44-.1.49-.24.7-.84.46-1.34-.19-.41-.59-.56-.9-.56-.15 0-.3.03-.44.1-.32.16-.45.42-.5.56-.05.15-.12.44.04.77.2.42.59.57.9.57zm13.16 2.52-6.69-2.41-.7 1.91 8.59 3.11.01-.02c.19-.51.17-1.05-.06-1.53-.23-.5-.63-.87-1.15-1.06z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M1.5 12.14 8 14.48V19h8v-1.63L20.52 19l.69-1.89-19.02-6.86-.69 1.89zm8.5 3.05 4 1.44V17h-4v-1.81zm9.84-6.05-8.56-3.09-2.08 5.66 12.36 4.47.69-1.89c.77-2.09-.31-4.39-2.41-5.15zm.53 4.46-.01.02-8.59-3.11.7-1.91 6.69 2.41c.52.19.93.56 1.15 1.05.23.49.25 1.04.06 1.54zM6 10.5c.44 0 .88-.1 1.3-.3 1.49-.72 2.12-2.51 1.41-4C8.19 5.13 7.12 4.5 6 4.5c-.44 0-.88.1-1.3.3-1.49.71-2.12 2.5-1.4 4 .51 1.07 1.58 1.7 2.7 1.7zm-.94-3.34c.05-.14.18-.4.51-.56.14-.06.28-.1.43-.1.31 0 .7.15.9.56.24.5.02 1.1-.47 1.34-.14.06-.28.1-.43.1-.3 0-.7-.15-.89-.56-.17-.34-.1-.63-.05-.78z"
}, "1")], 'AirlineSeatFlatAngledTwoTone');
|
var b2Vec2 = Box2D.Common.Math.b2Vec2;
var b2Body = Box2D.Dynamics.b2Body;
var b2BodyDef = Box2D.Dynamics.b2BodyDef;
var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
var b2Math = Box2D.Common.Math.b2Math;
function parseQueryString(str){
var dec = decodeURIComponent;
var arr = [];
var item;
if (typeof(str) == 'undefined') { return arr; }
if (str.indexOf('?', 0) > -1) { str = str.split('?')[1]; }
str = str.split('&');
for (var i = 0; i < str.length; ++i){
item = str[i].split("=");
if(item[0] != ''){
arr[item[0]] = typeof(item[1]) == 'undefined' ? true : dec(item[1]);
}
}
return arr;
}
function inspect(dict) {
var str = '';
for (var key in dict){
str += key + "=" + dict[key] + "\n";
}
alert(str);
}
function randomPM() { return Math.random() * 2 - 1; }
function color(r, g, b) {
var f = function(g) {
return ('0' + Math.floor(g()).toString(16)).slice(-2);
};
return "#" + f(r) + f(g) + f(b);
}
function whitish() { return Math.random() * 64 + 192; }
function light() { return Math.random() * 128 + 128; }
function middle() { return Math.random() * 128 + 64; }
function dark() { return Math.random() * 128 ; }
function blackish() { return Math.random() * 64 ; }
function updateShape(evt) {
evt.body.shape.x = evt.body.GetPosition().x * ppm;
evt.body.shape.y = evt.body.GetPosition().y * ppm;
evt.body.shape.rotation = evt.body.GetAngle() * 360.0 / (2.0 * Math.PI)
}
function smooth(times, interval, func) {
var i = interval;
var j = times;
var tick = function() {
if (0 < i) {
--i;
} else {
i = interval;
if (0 < j) {
--j;
func();
} else {
createjs.Ticker.removeEventListener("tick", tick);
}
}
}
createjs.Ticker.addEventListener("tick", tick);
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M10 6.35V4.26c-.66.17-1.29.43-1.88.75l1.5 1.5c.13-.05.25-.11.38-.16zM20 12c0-2.21-.91-4.2-2.36-5.64L20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 .85-.19 1.65-.51 2.38l1.5 1.5C19.63 14.74 20 13.41 20 12zM4.27 4L2.86 5.41l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.24-.76.34v2.09c.8-.21 1.55-.54 2.23-.96l2.58 2.58 1.41-1.41L4.27 4z" />
, 'SyncDisabledTwoTone');
|
import {ColumnView} from '../scene/view';
import {ColumnModel} from './column.model';
import {TemplatePath} from '../template';
TemplatePath.register('row-number-cell', (template, column) => {
return {
model: template.for,
resource: column.key
};
});
export class RowNumberColumnModel extends ColumnModel {
constructor() {
super('row-number');
this.pin = 'left';
this.key = '$row.number';
this.title = 'No.';
this.canEdit = false;
this.canResize = true;
this.canFocus = false;
this.canMove = false;
this.canHighlight = false;
this.canSort = false;
this.canFilter = false;
this.class = 'control';
}
}
export class RowNumberColumn extends ColumnView {
constructor(model) {
super(model);
}
static model(model) {
return model ? RowNumberColumn.assign(model) : new RowNumberColumnModel();
}
}
|
$(function (){
location.hash = "#welcome.html";
loader("welcome.html");
});
var loader = function (s) {
// load content from server
$.get(s, function (data){
var result = $(data);
$("#content").html(result);
// send event to Google Analytics
ga('send', 'event', 'content', 'load', s);
// process math
MathJax.Hub.Queue(["Typeset", MathJax.Hub, "content"]);
});
}
window.onhashchange = function () {
console.log(location.hash);
loader(location.hash.substring(1));
}
|
(function() {
'use strict';
angular.module('civic.events.evidence')
.config(evidenceEditConfig)
.factory('EvidenceEditViewOptions', EvidenceEditViewOptions)
.controller('EvidenceEditController', EvidenceEditController);
// @ngInject
function evidenceEditConfig($stateProvider) {
$stateProvider
.state('events.genes.summary.variants.summary.evidence.edit', {
abstract: true,
url: '/edit',
templateUrl: 'app/views/events/evidence/edit/EvidenceEditView.tpl.html',
controller: 'EvidenceEditController',
controllerAs: 'vm',
resolve: {
EvidenceRevisions: 'EvidenceRevisions',
initEvidenceEdit: function(Evidence, EvidenceRevisions, EvidenceHistory, $stateParams, $q) {
var evidenceId = $stateParams.evidenceId;
return $q.all([
EvidenceRevisions.initRevisions(evidenceId),
EvidenceRevisions.getPendingFields(evidenceId),
EvidenceHistory.initBase(evidenceId)
]);
}
},
deepStateRedirect: [ 'evidenceId' ],
data: {
titleExp: '"Evidence " + evidence.name + " Edit"',
navMode: 'sub'
}
})
.state('events.genes.summary.variants.summary.evidence.edit.basic', {
url: '/basic',
template: '<evidence-edit-basic></evidence-edit-basic>',
data: {
titleExp: '"Evidence " + evidence.name + " Edit"',
navMode: 'sub'
}
});
}
// @ngInject
function EvidenceEditViewOptions($state, $stateParams) {
var baseUrl = '';
var baseState = '';
var styles = {};
function init() {
baseState = 'events.genes.summary.evidence.edit';
baseUrl = $state.href(baseUrl, $stateParams);
angular.copy({
view: {
summaryBackgroundColor: 'pageBackground2',
editBackgroundColor: 'pageBackground',
talkBackgroundColor: 'pageBackground'
},
tabs: {
tabRowBackground: 'pageBackground2Gradient'
}
}, styles);
}
return {
init: init,
state: {
baseParams: $stateParams,
baseState: baseState,
baseUrl: baseUrl
},
styles: styles
};
}
// @ngInject
function EvidenceEditController(Evidence, EvidenceRevisions, EvidenceEditViewOptions) {
console.log('EvidenceEditController called.');
EvidenceEditViewOptions.init();
this.EvidenceEditViewModel = Evidence; // we're re-using the Evidence model here but could in the future have a EvidenceEdit model if warranted
this.EvidenceRevisionsModel = EvidenceRevisions;
this.EvidenceEditViewOptions = EvidenceEditViewOptions;
}
})();
|
'use strict';
const applySourceMap = require('vinyl-sourcemaps-apply');
const CleanCSS = require('clean-css');
const path = require('path');
const PluginError = require('gulp-util').PluginError;
const through = require('through2');
module.exports = function gulpCleanCSS(options, callback) {
options = options || {};
if (arguments.length === 1 && Object.prototype.toString.call(arguments[0]) === '[object Function]')
callback = arguments[0];
let transform = function (file, enc, cb) {
if (!file || !file.contents)
return cb(null, file);
if (file.isStream()) {
this.emit('error', new PluginError('gulp-clean-css', 'Streaming not supported!'));
return cb(null, file);
}
if (file.sourceMap)
options.sourceMap = JSON.parse(JSON.stringify(file.sourceMap));
if(!options.rebaseTo)
options.rebase = false;
let style = {
[file.path]: {
styles: file.contents ? file.contents.toString() : ''
}
};
new CleanCSS(options).minify(style, function (errors, css) {
if (errors)
return cb(errors.join(' '));
if (typeof callback === 'function') {
let details = {
'stats': css.stats,
'errors': css.errors,
'warnings': css.warnings,
'path': file.path,
'name': file.path.split(file.base)[1]
};
if (css.sourceMap)
details['sourceMap'] = css.sourceMap;
callback(details);
}
file.contents = new Buffer(css.styles);
if (css.sourceMap) {
let map = JSON.parse(css.sourceMap);
map.file = path.relative(file.base, file.path);
map.sources = map.sources.map(function (src) {
return path.relative(file.base, file.path)
});
applySourceMap(file, map);
}
cb(null, file);
});
};
return through.obj(transform);
};
|
var anchor;
while (anchor = schema.nextAnchor()) {
if(anchor.hasMoreAttributes()) { // only do perspectives if there are attributes
var knot, attribute;
/*~
-- Point-in-time perspective ------------------------------------------------------------------------------------------
-- p$anchor.name viewed as it was on the given timepoint
-----------------------------------------------------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION $anchor.capsule\.p$anchor.name (
changingTimepoint $schema.metadata.chronon
)
RETURNS TABLE (
$anchor.identityColumnName $anchor.identity,
$(schema.METADATA)? $anchor.metadataColumnName $schema.metadata.metadataType,~*/
while (attribute = anchor.nextAttribute()) {
/*~
$(schema.IMPROVED)? $attribute.anchorReferenceName $anchor.identity,
$(schema.METADATA)? $attribute.metadataColumnName $schema.metadata.metadataType,
$(attribute.timeRange)? $attribute.changingColumnName $attribute.timeRange,
$(attribute.isEquivalent())? $attribute.equivalentColumnName $schema.metadata.equivalentRange,
~*/
if(attribute.isKnotted()) {
knot = attribute.knot;
/*~
$(knot.hasChecksum())? $attribute.knotChecksumColumnName bytea,
$(knot.isEquivalent())? $attribute.knotEquivalentColumnName $schema.metadata.equivalentRange,
$attribute.knotValueColumnName $knot.dataRange,
$(schema.METADATA)? $attribute.knotMetadataColumnName $schema.metadata.metadataType,
~*/
}
/*~
$(attribute.hasChecksum())? $attribute.checksumColumnName bytea,
$attribute.valueColumnName $(attribute.isKnotted())? $knot.identity: $attribute.dataRange~*/
/*~$(anchor.hasMoreAttributes())?,
~*/
}
/*~
) AS '
SELECT
$anchor.mnemonic\.$anchor.identityColumnName,
$(schema.METADATA)? $anchor.mnemonic\.$anchor.metadataColumnName,
~*/
while (attribute = anchor.nextAttribute()) {
/*~
$(schema.IMPROVED)? $attribute.mnemonic\.$attribute.anchorReferenceName,
$(schema.METADATA)? $attribute.mnemonic\.$attribute.metadataColumnName,
$(attribute.timeRange)? $attribute.mnemonic\.$attribute.changingColumnName,
$(attribute.isEquivalent())? $attribute.mnemonic\.$attribute.equivalentColumnName,
~*/
if(attribute.isKnotted()) {
knot = attribute.knot;
/*~
$(knot.hasChecksum())? k$attribute.mnemonic\.$knot.checksumColumnName AS $attribute.knotChecksumColumnName,
$(knot.isEquivalent())? k$attribute.mnemonic\.$knot.equivalentColumnName AS $attribute.knotEquivalentColumnName,
k$attribute.mnemonic\.$knot.valueColumnName AS $attribute.knotValueColumnName,
$(schema.METADATA)? k$attribute.mnemonic\.$knot.metadataColumnName AS $attribute.knotMetadataColumnName,
~*/
}
/*~
$(attribute.hasChecksum())? $attribute.mnemonic\.$attribute.checksumColumnName,
$attribute.mnemonic\.$attribute.valueColumnName$(anchor.hasMoreAttributes())?,
~*/
}
/*~
FROM
$anchor.capsule\.$anchor.name $anchor.mnemonic
~*/
while (attribute = anchor.nextAttribute()) {
if(attribute.isHistorized()) {
if(attribute.isEquivalent()) {
/*~
LEFT JOIN
$attribute.capsule\.r$attribute.name(0, CAST(changingTimepoint AS $attribute.timeRange)) $attribute.mnemonic
~*/
}
else {
/*~
LEFT JOIN
$attribute.capsule\.r$attribute.name(CAST(changingTimepoint AS $attribute.timeRange)) $attribute.mnemonic
~*/
}
/*~
ON
$attribute.mnemonic\.$attribute.anchorReferenceName = $anchor.mnemonic\.$anchor.identityColumnName
AND
$attribute.mnemonic\.$attribute.changingColumnName = (
SELECT
max(sub.$attribute.changingColumnName)
FROM
$(attribute.isEquivalent())? $attribute.capsule\.r$attribute.name(0, CAST(changingTimepoint AS $attribute.timeRange)) sub : $attribute.capsule\.r$attribute.name(CAST(changingTimepoint AS $attribute.timeRange)) sub
WHERE
sub.$attribute.anchorReferenceName = $anchor.mnemonic\.$anchor.identityColumnName
)~*/
}
else {
if(attribute.isEquivalent()) {
/*~
LEFT JOIN
$attribute.capsule\.e$attribute.name(0) $attribute.mnemonic
~*/
}
else {
/*~
LEFT JOIN
$attribute.capsule\.$attribute.name $attribute.mnemonic
~*/
}
/*~
ON
$attribute.mnemonic\.$attribute.anchorReferenceName = $anchor.mnemonic\.$anchor.identityColumnName~*/
}
if(attribute.isKnotted()) {
knot = attribute.knot;
if(knot.isEquivalent()) {
/*~
LEFT JOIN
$knot.capsule\.e$knot.name(0) k$attribute.mnemonic
~*/
}
else {
/*~
LEFT JOIN
$knot.capsule\.$knot.name k$attribute.mnemonic
~*/
}
/*~
ON
k$attribute.mnemonic\.$knot.identityColumnName = $attribute.mnemonic\.$attribute.knotReferenceName~*/
}
if(!anchor.hasMoreAttributes()) {
/*~;~*/
}
}
/*~
' LANGUAGE SQL;~*/
}
}
|
'use strict';
// Use local.env.js for environment variables that grunt will set when the server starts locally.
// Use for your api keys, secrets, etc. This file should not be tracked by git.
//
// You will need to set these on the server you deploy to.
module.exports = {
DOMAIN: 'http://localhost:9000',
SESSION_SECRET: "jogging-secret",
FACEBOOK_ID: 'app-id',
FACEBOOK_SECRET: 'secret',
TWITTER_ID: 'app-id',
TWITTER_SECRET: 'secret',
GOOGLE_ID: 'app-id',
GOOGLE_SECRET: 'secret',
// Control debug level for modules using visionmedia/debug
DEBUG: ''
};
|
"use strict";
module.exports = MapField;
// extends Field
var Field = require("./field");
((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";
var types = require("./types"),
util = require("./util");
/**
* Constructs a new map field instance.
* @classdesc Reflected map field.
* @extends FieldBase
* @constructor
* @param {string} name Unique name within its namespace
* @param {number} id Unique id within its namespace
* @param {string} keyType Key type
* @param {string} type Value type
* @param {Object.<string,*>} [options] Declared options
*/
function MapField(name, id, keyType, type, options) {
Field.call(this, name, id, type, options);
/* istanbul ignore if */
if (!util.isString(keyType))
throw TypeError("keyType must be a string");
/**
* Key type.
* @type {string}
*/
this.keyType = keyType; // toJSON, marker
/**
* Resolved key type if not a basic type.
* @type {ReflectionObject|null}
*/
this.resolvedKeyType = null;
// Overrides Field#map
this.map = true;
}
/**
* Map field descriptor.
* @interface IMapField
* @extends {IField}
* @property {string} keyType Key type
*/
/**
* Extension map field descriptor.
* @interface IExtensionMapField
* @extends IMapField
* @property {string} extend Extended type
*/
/**
* Constructs a map field from a map field descriptor.
* @param {string} name Field name
* @param {IMapField} json Map field descriptor
* @returns {MapField} Created map field
* @throws {TypeError} If arguments are invalid
*/
MapField.fromJSON = function fromJSON(name, json) {
return new MapField(name, json.id, json.keyType, json.type, json.options);
};
/**
* Converts this map field to a map field descriptor.
* @returns {IMapField} Map field descriptor
*/
MapField.prototype.toJSON = function toJSON() {
return util.toObject([
"keyType" , this.keyType,
"type" , this.type,
"id" , this.id,
"extend" , this.extend,
"options" , this.options
]);
};
/**
* @override
*/
MapField.prototype.resolve = function resolve() {
if (this.resolved)
return this;
// Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"
if (types.mapKey[this.keyType] === undefined)
throw Error("invalid key type: " + this.keyType);
return Field.prototype.resolve.call(this);
};
/**
* Map field decorator (TypeScript).
* @name MapField.d
* @function
* @param {number} fieldId Field id
* @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type
* @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type
* @returns {FieldDecorator} Decorator function
* @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }
*/
MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {
// submessage value: decorate the submessage and use its name as the type
if (typeof fieldValueType === "function")
fieldValueType = util.decorateType(fieldValueType).name;
// enum reference value: create a reflected copy of the enum and keep reuseing it
else if (fieldValueType && typeof fieldValueType === "object")
fieldValueType = util.decorateEnum(fieldValueType).name;
return function mapFieldDecorator(prototype, fieldName) {
util.decorateType(prototype.constructor)
.add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));
};
};
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
* @emails oncall+relay
*/
// flowlint ambiguous-object-type:error
'use strict';
const RelayModernEnvironment = require('../RelayModernEnvironment');
const RelayModernStore = require('../RelayModernStore');
const RelayNetwork = require('../../network/RelayNetwork');
const RelayObservable = require('../../network/RelayObservable');
const RelayRecordSource = require('../RelayRecordSource');
const nullthrows = require('nullthrows');
const {
createOperationDescriptor,
} = require('../RelayModernOperationDescriptor');
const {
getSingularSelector,
createReaderSelector,
} = require('../RelayModernSelector');
const {generateAndCompile} = require('relay-test-utils-internal');
describe('executeMutation() with @match', () => {
let callbacks;
let commentFragment;
let commentID;
let complete;
let dataSource;
let environment;
let error;
let fetch;
let fragmentCallback;
let markdownRendererFragment;
let markdownRendererNormalizationFragment;
let mutation;
let next;
let operation;
let commentQuery;
let queryOperation;
let operationCallback;
let operationLoader;
let resolveFragment;
let source;
let store;
let variables;
let queryVariables;
beforeEach(() => {
jest.resetModules();
commentID = '1';
({
CommentFragment: commentFragment,
CommentQuery: commentQuery,
CreateCommentMutation: mutation,
MarkdownUserNameRenderer_name: markdownRendererFragment,
MarkdownUserNameRenderer_name$normalization: markdownRendererNormalizationFragment,
} = generateAndCompile(`
mutation CreateCommentMutation($input: CommentCreateInput!) {
commentCreate(input: $input) {
comment {
actor {
name
nameRenderer @match {
...PlainUserNameRenderer_name
@module(name: "PlainUserNameRenderer.react")
...MarkdownUserNameRenderer_name
@module(name: "MarkdownUserNameRenderer.react")
}
}
}
}
}
fragment PlainUserNameRenderer_name on PlainUserNameRenderer {
plaintext
data {
text
}
}
fragment MarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
__typename
markdown
data {
markup @__clientField(handle: "markup_handler")
}
}
fragment CommentFragment on Comment {
id
actor {
name
nameRenderer @match {
...PlainUserNameRenderer_name
@module(name: "PlainUserNameRenderer.react")
...MarkdownUserNameRenderer_name
@module(name: "MarkdownUserNameRenderer.react")
}
}
}
query CommentQuery($id: ID!) {
node(id: $id) {
id
...CommentFragment
}
}
`));
variables = {
input: {
clientMutationId: '0',
feedbackId: '1',
},
};
queryVariables = {
id: commentID,
};
operation = createOperationDescriptor(mutation, variables);
queryOperation = createOperationDescriptor(commentQuery, queryVariables);
const MarkupHandler = {
update(storeProxy, payload) {
const record = storeProxy.get(payload.dataID);
if (record != null) {
const markup = record.getValue(payload.fieldKey);
record.setValue(
typeof markup === 'string' ? markup.toUpperCase() : null,
payload.handleKey,
);
}
},
};
complete = jest.fn();
error = jest.fn();
next = jest.fn();
callbacks = {complete, error, next};
fetch = (_query, _variables, _cacheConfig) => {
return RelayObservable.create(sink => {
dataSource = sink;
});
};
operationLoader = {
load: jest.fn(moduleName => {
return new Promise(resolve => {
resolveFragment = resolve;
});
}),
get: jest.fn(),
};
source = RelayRecordSource.create();
store = new RelayModernStore(source);
environment = new RelayModernEnvironment({
network: RelayNetwork.create(fetch),
store,
operationLoader,
handlerProvider: name => {
switch (name) {
case 'markup_handler':
return MarkupHandler;
}
},
});
const selector = createReaderSelector(
commentFragment,
commentID,
{},
queryOperation.request,
);
const fragmentSnapshot = environment.lookup(selector);
fragmentCallback = jest.fn();
environment.subscribe(fragmentSnapshot, fragmentCallback);
const operationSnapshot = environment.lookup(operation.fragment);
operationCallback = jest.fn();
environment.subscribe(operationSnapshot, operationCallback);
});
it('executes the optimistic updater immediately, does not mark the mutation as being in flight in the operation tracker', () => {
environment
.executeMutation({
operation,
optimisticUpdater: _store => {
const comment = _store.create(commentID, 'Comment');
comment.setValue(commentID, 'id');
const actor = _store.create('4', 'User');
comment.setLinkedRecord(actor, 'actor');
actor.setValue('optimistic-name', 'name');
},
})
.subscribe(callbacks);
expect(complete).not.toBeCalled();
expect(error).not.toBeCalled();
expect(fragmentCallback.mock.calls.length).toBe(1);
expect(fragmentCallback.mock.calls[0][0].data).toEqual({
id: commentID,
actor: {
name: 'optimistic-name',
nameRenderer: undefined,
},
});
// The mutation affecting the query should not be marked as in flight yet
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).toBe(null);
});
it('calls next() and publishes the initial payload to the store', () => {
environment.executeMutation({operation}).subscribe(callbacks);
const payload = {
data: {
commentCreate: {
comment: {
id: commentID,
actor: {
id: '4',
name: 'actor-name',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_CreateCommentMutation:
'MarkdownUserNameRenderer.react',
__module_operation_CreateCommentMutation:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>', // server data is lowercase
},
},
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
expect(next.mock.calls.length).toBe(1);
expect(complete).not.toBeCalled();
expect(error).not.toBeCalled();
expect(operationCallback).toBeCalledTimes(1);
const operationSnapshot = operationCallback.mock.calls[0][0];
expect(operationSnapshot.isMissingData).toBe(false);
expect(operationSnapshot.data).toEqual({
commentCreate: {
comment: {
actor: {
name: 'actor-name',
nameRenderer: {
__id:
'client:4:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__fragmentPropName: 'name',
__fragments: {
MarkdownUserNameRenderer_name: {},
},
__fragmentOwner: operation.request,
__module_component: 'MarkdownUserNameRenderer.react',
},
},
},
},
});
expect(fragmentCallback).toBeCalledTimes(1);
const fragmentSnapshot = fragmentCallback.mock.calls[0][0];
// data is missing since match field data hasn't been processed yet
expect(fragmentSnapshot.isMissingData).toBe(true);
expect(fragmentSnapshot.data).toEqual({
id: commentID,
actor: {
name: 'actor-name',
nameRenderer: {},
},
});
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data: any)?.commentCreate?.comment?.actor
?.nameRenderer,
),
);
const matchSnapshot = environment.lookup(matchSelector);
// ref exists but match field data hasn't been processed yet
expect(matchSnapshot.isMissingData).toBe(true);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: undefined,
markdown: undefined,
});
// The mutation affecting the query should be marked as in flight now
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).not.toBe(null);
});
it('loads the @match fragment and normalizes/publishes the field payload', () => {
environment.executeMutation({operation}).subscribe(callbacks);
const payload = {
data: {
commentCreate: {
comment: {
id: commentID,
actor: {
id: '4',
name: 'actor-name',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_CreateCommentMutation:
'MarkdownUserNameRenderer.react',
__module_operation_CreateCommentMutation:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>', // server data is lowercase
},
},
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
next.mockClear();
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toEqual(
'MarkdownUserNameRenderer_name$normalization.graphql',
);
expect(operationCallback).toBeCalledTimes(1);
// result tested above
const operationSnapshot = operationCallback.mock.calls[0][0];
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data: any)?.commentCreate?.comment?.actor
?.nameRenderer,
),
);
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(true);
const matchCallback = jest.fn();
environment.subscribe(initialMatchSnapshot, matchCallback);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
// next() should not be called when @match resolves, no new GraphQLResponse
// was received for this case
expect(next).toBeCalledTimes(0);
expect(operationCallback).toBeCalledTimes(0);
expect(matchCallback).toBeCalledTimes(1);
const matchSnapshot = matchCallback.mock.calls[0][0];
expect(matchSnapshot.isMissingData).toBe(false);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<MARKUP/>',
},
markdown: 'markdown payload',
});
// The mutation affecting the query should still be marked as in flight
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).not.toBe(null);
});
it('calls complete() only after match payloads are processed (network completes first)', () => {
environment.executeMutation({operation}).subscribe(callbacks);
const payload = {
data: {
commentCreate: {
comment: {
id: commentID,
actor: {
id: '4',
name: 'actor-name',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_CreateCommentMutation:
'MarkdownUserNameRenderer.react',
__module_operation_CreateCommentMutation:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>', // server data is lowercase
},
},
},
},
},
},
};
dataSource.next(payload);
dataSource.complete();
jest.runAllTimers();
expect(complete).toBeCalledTimes(0);
expect(error).toBeCalledTimes(0);
expect(next).toBeCalledTimes(1);
// The mutation affecting the query should still be in flight
// even if the network completed, since we're waiting for a 3d payload
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).not.toBe(null);
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toEqual(
'MarkdownUserNameRenderer_name$normalization.graphql',
);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
expect(complete).toBeCalledTimes(1);
expect(error).toBeCalledTimes(0);
expect(next).toBeCalledTimes(1);
// The mutation affecting the query should no longer be in flight
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).toBe(null);
});
it('calls complete() only after match payloads are processed (network completes last)', () => {
environment.executeMutation({operation}).subscribe(callbacks);
const payload = {
data: {
commentCreate: {
comment: {
id: commentID,
actor: {
id: '4',
name: 'actor-name',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_CreateCommentMutation:
'MarkdownUserNameRenderer.react',
__module_operation_CreateCommentMutation:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>', // server data is lowercase
},
},
},
},
},
},
};
dataSource.next(payload);
jest.runAllTimers();
expect(operationLoader.load).toBeCalledTimes(1);
expect(operationLoader.load.mock.calls[0][0]).toEqual(
'MarkdownUserNameRenderer_name$normalization.graphql',
);
resolveFragment(markdownRendererNormalizationFragment);
jest.runAllTimers();
// The mutation affecting the query should still be in flight
// since the network hasn't completed
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).not.toBe(null);
expect(complete).toBeCalledTimes(0);
expect(error).toBeCalledTimes(0);
expect(next).toBeCalledTimes(1);
dataSource.complete();
expect(complete).toBeCalledTimes(1);
expect(error).toBeCalledTimes(0);
expect(next).toBeCalledTimes(1);
// The mutation affecting the query should no longer be in flight
expect(
environment
.getOperationTracker()
.getPromiseForPendingOperationsAffectingOwner(queryOperation.request),
).toBe(null);
});
describe('optimistic updates', () => {
const optimisticResponse = {
commentCreate: {
comment: {
id: commentID,
actor: {
id: '4',
name: 'optimisitc-actor-name',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_CreateCommentMutation:
'MarkdownUserNameRenderer.react',
__module_operation_CreateCommentMutation:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<optimistic_markup/>', // server data is lowercase
},
},
},
},
},
};
it('optimistically creates @match fields', () => {
operationLoader.get.mockImplementationOnce(name => {
return markdownRendererNormalizationFragment;
});
environment
.executeMutation({operation, optimisticResponse})
.subscribe(callbacks);
jest.runAllTimers();
expect(next.mock.calls.length).toBe(0);
expect(complete).not.toBeCalled();
expect(error.mock.calls.map(call => call[0].message)).toEqual([]);
expect(operationCallback).toBeCalledTimes(1);
const operationSnapshot = operationCallback.mock.calls[0][0];
expect(operationSnapshot.isMissingData).toBe(false);
expect(operationSnapshot.data).toEqual({
commentCreate: {
comment: {
actor: {
name: 'optimisitc-actor-name',
nameRenderer: {
__id:
'client:4:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__fragmentPropName: 'name',
__fragments: {
MarkdownUserNameRenderer_name: {},
},
__fragmentOwner: operation.request,
__module_component: 'MarkdownUserNameRenderer.react',
},
},
},
},
});
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data: any)?.commentCreate?.comment?.actor
?.nameRenderer,
),
);
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(false);
expect(initialMatchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<OPTIMISTIC_MARKUP/>',
},
markdown: 'markdown payload',
});
});
it('optimistically creates @match fields and loads resources', () => {
operationLoader.load.mockImplementationOnce(() => {
return new Promise(resolve => {
setImmediate(() => {
resolve(markdownRendererNormalizationFragment);
});
});
});
environment
.executeMutation({operation, optimisticResponse})
.subscribe(callbacks);
jest.runAllTimers();
expect(next.mock.calls.length).toBe(0);
expect(complete).not.toBeCalled();
expect(error.mock.calls.map(call => call[0].message)).toEqual([]);
expect(operationCallback).toBeCalledTimes(1);
const operationSnapshot = operationCallback.mock.calls[0][0];
expect(operationSnapshot.isMissingData).toBe(false);
expect(operationSnapshot.data).toEqual({
commentCreate: {
comment: {
actor: {
name: 'optimisitc-actor-name',
nameRenderer: {
__id:
'client:4:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__fragmentPropName: 'name',
__fragments: {
MarkdownUserNameRenderer_name: {},
},
__fragmentOwner: operation.request,
__module_component: 'MarkdownUserNameRenderer.react',
},
},
},
},
});
operationCallback.mockClear();
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data: any)?.commentCreate?.comment?.actor
?.nameRenderer,
),
);
const initialMatchSnapshot = environment.lookup(matchSelector);
expect(initialMatchSnapshot.isMissingData).toBe(false);
expect(initialMatchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: {
// NOTE: should be uppercased by the MarkupHandler
markup: '<OPTIMISTIC_MARKUP/>',
},
markdown: 'markdown payload',
});
});
it('does not apply aysnc 3D optimistic updates if the server response arrives first', () => {
operationLoader.load.mockImplementationOnce(() => {
return new Promise(resolve => {
setTimeout(() => {
resolve(markdownRendererNormalizationFragment);
}, 1000);
});
});
environment
.executeMutation({operation, optimisticResponse})
.subscribe(callbacks);
const serverPayload = {
data: {
commentCreate: {
comment: {
id: commentID,
actor: {
id: '4',
name: 'actor-name',
__typename: 'User',
nameRenderer: {
__typename: 'MarkdownUserNameRenderer',
__module_component_CreateCommentMutation:
'MarkdownUserNameRenderer.react',
__module_operation_CreateCommentMutation:
'MarkdownUserNameRenderer_name$normalization.graphql',
markdown: 'markdown payload',
data: {
markup: '<markup/>', // server data is lowercase
},
},
},
},
},
},
};
dataSource.next(serverPayload);
jest.runAllTimers();
expect(next.mock.calls.length).toBe(1);
expect(complete).not.toBeCalled();
expect(error).not.toBeCalled();
expect(operationCallback).toBeCalledTimes(2);
const operationSnapshot = operationCallback.mock.calls[1][0];
expect(operationSnapshot.isMissingData).toBe(false);
expect(operationSnapshot.data).toEqual({
commentCreate: {
comment: {
actor: {
name: 'actor-name',
nameRenderer: {
__id:
'client:4:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
__fragmentPropName: 'name',
__fragments: {
MarkdownUserNameRenderer_name: {},
},
__fragmentOwner: operation.request,
__module_component: 'MarkdownUserNameRenderer.react',
},
},
},
},
});
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data: any)?.commentCreate?.comment?.actor
?.nameRenderer,
),
);
const matchSnapshot = environment.lookup(matchSelector);
// optimistic update should not be applied
expect(matchSnapshot.isMissingData).toBe(true);
expect(matchSnapshot.data).toEqual({
__typename: 'MarkdownUserNameRenderer',
data: undefined,
markdown: undefined,
});
});
it('does not apply async 3D optimistic updates if the operation is cancelled', () => {
operationLoader.load.mockImplementationOnce(() => {
return new Promise(resolve => {
setTimeout(() => {
resolve(markdownRendererNormalizationFragment);
}, 1000);
});
});
const disposable = environment
.executeMutation({operation, optimisticResponse})
.subscribe(callbacks);
disposable.unsubscribe();
jest.runAllImmediates();
jest.runAllTimers();
expect(next).not.toBeCalled();
expect(complete).not.toBeCalled();
expect(error).not.toBeCalled();
expect(operationCallback).toBeCalledTimes(2);
// get the match snapshot from sync optimistic response
const operationSnapshot = operationCallback.mock.calls[0][0];
expect(operationSnapshot.isMissingData).toBe(false);
const matchSelector = nullthrows(
getSingularSelector(
markdownRendererFragment,
(operationSnapshot.data: any)?.commentCreate?.comment?.actor
?.nameRenderer,
),
);
const matchSnapshot = environment.lookup(matchSelector);
// optimistic update should not be applied
expect(matchSnapshot.isMissingData).toBe(true);
expect(matchSnapshot.data).toEqual(undefined);
});
it('catches error when opeartionLoader.load fails synchoronously', () => {
operationLoader.load.mockImplementationOnce(() => {
throw new Error('<user-error>');
});
environment
.executeMutation({operation, optimisticResponse})
.subscribe(callbacks);
jest.runAllTimers();
expect(error.mock.calls.length).toBe(1);
expect(error.mock.calls[0][0]).toEqual(new Error('<user-error>'));
});
});
});
|
/* eslint no-sync: 0 */
const fs = require("fs");
const path = require("path");
const Logger = require("./Log");
const Plugin = require("./Plugin");
// A small utility functor to find a plugin with a given name
const nameMatches = targetName => pl => pl.plugin.name.toLowerCase() === targetName.toLowerCase();
const SYNC_INTERVAL = 5000;
function messageIsCommand(message) {
if (!message.entities) return;
const entity = message.entities[0];
return entity.offset === 0 && entity.type === "bot_command";
}
// Note: we only parse commands at the start of the message,
// therefore we suppose entity.offset = 0
function parseCommand(message) {
const entity = message.entities[0];
const rawCommand = message.text.substring(1, entity.length);
let command;
if (rawCommand.search("@") === -1)
command = rawCommand;
else
command = rawCommand.substring(0, rawCommand.search("@"));
let args = [];
if (message.text.length > entity.length) {
args = message.text.slice(entity.length + 1).split(" ");
}
return {args, command};
}
module.exports = class PluginManager {
constructor(bot, config, auth) {
this.bot = bot;
this.log = new Logger("PluginManager", config);
this.auth = auth;
this.plugins = [];
this.config = config;
const events = Object.keys(Plugin.handlerNames)
// We handle the message event by ourselves.
.filter(prop => prop !== "message")
// Events beginning with an underscore (eg. _command) are internal.
.filter(prop => prop[0] !== "_");
// Registers a handler for every Telegram event.
// It runs the message through the proxy and forwards it to the plugin manager.
for (const eventName of events) {
bot.on(
eventName,
async message => {
// const messageID = message.message_id + '@' + message.chat.id;
// console.time(messageID);
this.parseHardcoded(message);
try {
await Promise.all(this.plugins
.filter(plugin => plugin.plugin.isProxy)
.map(plugin => plugin.proxy(eventName, message))
);
} catch (err) {
if (err)
this.log.error("Message rejected with error", err);
}
try {
await this.emit("message", message);
await this.emit(eventName, message);
this.log.debug("Message chain completed.");
} catch (e) {
if (!e) {
this.log.error("Message chain failed with no error message.");
this.bot.sendMessage(message.chat.id, "An error occurred.");
return;
}
this.log.error(e);
this.bot.sendMessage(message.chat.id, e.stack.split("\n").slice(0, 2).join("\n"));
}
// console.timeEnd(messageID);
}
);
}
}
parseHardcoded(message) {
// Hardcoded commands
if (!messageIsCommand(message)) return;
const {command, args: [pluginName, targetChat]} = parseCommand(message);
// Skip everything if we're not interested in this command
if (command !== "help"
&& command !== "start"
&& command !== "plugins"
&& command !== "enable"
&& command !== "disable") return;
const response = this.processHardcoded(command, pluginName, targetChat, message);
this.bot.sendMessage(message.chat.id, response, {
parse_mode: "markdown",
disable_web_page_preview: true
});
}
processHardcoded(command, pluginName, targetChat, message) {
if (command === "start") {
let text = `*Nikoro* v${require("../package.json").version}
Nikoro is a plugin-based Telegram bot. To get started, use /help to find out how to use the currently active plugins.`;
if (this.auth.isOwner(message.from.id))
text += `\n\nYou can also use /plugins for a list of available plugins, or browse the [user guide](https://telegram-bot-node.github.io/Nikoro/user.html) for more information on this bot's features.`;
return text;
}
if (command === "help") {
const availablePlugins = this.plugins
.map(pl => pl.plugin)
.filter(pl => !pl.isHidden);
if (!pluginName)
return "The following plugins are enabled:\n\n" + availablePlugins
.map(pl => `*${pl.name}*`)
.join("\n") + "\n\nFor help about a specific plugin, use /help PluginName.";
const plugin = availablePlugins
.find(pl => pl.name.toLowerCase() === pluginName.toLowerCase());
if (!plugin)
return "No such plugin.";
return `*${plugin.name}* - ${plugin.description}\n\n${plugin.help}`;
}
if (command === "plugins") {
const pluginPath = path.join(__dirname, "plugins");
const files = fs.readdirSync(pluginPath).map(filename => filename.replace(/\.js$/, ""));
const plugins = files.map(filename => {
try {
const plugin = require(path.join(pluginPath, filename), false).plugin;
return {
name: filename,
description: plugin.description
};
} catch (e) {
let message = e.message;
message = message.replace(/^Cannot find module '([^']+)'$/, "Must install `$1` first");
return {
name: `${filename}`,
disabled: message
};
}
});
// Does the list of plugins contain the given name?
const isEnabled = pl => this.plugins.some(nameMatches(pl.name))
const enabled = plugins
.filter(pl => isEnabled(pl))
.map(pl => `*${pl.name}*: ${pl.description}`)
.join("\n");
const available = plugins
.filter(pl => !isEnabled(pl))
.map(pl => `*${pl.name}*` + (pl.disabled ? ` (${pl.disabled})` : `: ${pl.description}`))
.join("\n");
return "Enabled:\n" + enabled + "\n\nAvailable:\n" + available + "\n\nUse \"/enable PluginName\" to load a plugin.";
}
if (!this.auth.isOwner(message.from.id, message.chat.id))
return "Insufficient privileges (owner required).";
// Syntax: /("enable"|"disable") pluginName [targetChat|"chat"]
// The string "chat" will enable the plugin in the current chat.
if (targetChat === "chat") targetChat = message.chat.id;
targetChat = Number(targetChat);
// Checks if it is already in this.plugins
const isGloballyEnabled = this.plugins.some(nameMatches(pluginName));
switch (command) {
case "enable":
if (targetChat) {
try {
this.loadAndAdd(pluginName);
const plugin = this.plugins.find(nameMatches(pluginName));
plugin.blacklist.delete(targetChat);
return `Plugin enabled successfully for chat ${targetChat}.`;
} catch (e) {
this.log.warn(e);
if (e.message === "No such file.")
return "No such plugin.\n\nIf you can't find the plugin you want, try running /plugins.";
return "Couldn't load plugin: " + e.message;
}
}
if (isGloballyEnabled)
return "Plugin already enabled.";
this.log.info(`Enabling ${pluginName} from message interface`);
try {
this.loadAndAdd(pluginName);
return "Plugin enabled successfully.";
} catch (e) {
this.log.warn(e);
if (e.message === "No such file.")
return "No such plugin.\n\nIf you can't find the plugin you want, try running /plugins.";
if (!/^Cannot find module/.test(e.message))
return "Couldn't load plugin, check console for errors.";
return e.message.replace(/Cannot find module '([^']+)'/, "The plugin has a missing dependency: `$1`");
}
case "disable":
if (targetChat) {
if (!isGloballyEnabled)
return "Plugin isn't enabled.";
const plugin = this.plugins.find(nameMatches(pluginName));
plugin.blacklist.add(targetChat);
return `Plugin disabled successfully for chat ${targetChat}.`;
}
if (isGloballyEnabled) {
const outcome = this.removePlugin(pluginName);
return outcome ? "Plugin disabled successfully." : "An error occurred.";
}
return "Plugin already disabled.";
}
}
// Instantiates the plugin.
// Case-insensitive.
// Returns the plugin itself.
loadPlugin(_pluginName) {
// Find a matching filename, case-insensitively
const files = fs.readdirSync(path.join(__dirname, "plugins")).map(filename => filename.replace(/\.js$/, ""));
const pluginName = files.find(filename => filename.toLowerCase() === _pluginName.toLowerCase());
if (!pluginName)
throw new Error("No such file.");
const pluginPath = path.join(__dirname, "plugins", pluginName);
/* Invalidates the require() cache.
* This allows for "hot fixes" to plugins: just /disable it, make the
* required changes, and /enable it again.
* If the cache wasn't invalidated, the plugin would be loaded from
* cache rather than from disk, meaning that your changes wouldn't apply.
* Method: https://stackoverflow.com/a/16060619
*/
delete require.cache[require.resolve(pluginPath)];
const ThisPlugin = require(pluginPath);
this.log.debug(`Required ${pluginName}`);
// Load the blacklist and database from disk
const databasePath = PluginManager.getDatabasePath(pluginName);
let db = {};
let blacklist = [];
if (fs.existsSync(databasePath)) {
const data = JSON.parse(fs.readFileSync(databasePath, "utf8"));
db = data.db;
blacklist = data.blacklist;
}
const loadedPlugin = new ThisPlugin({
db,
blacklist,
bot: this.bot,
config: this.config,
auth: this.auth
});
// Bind all the methods from the bot API
for (const method of Object.getOwnPropertyNames(Object.getPrototypeOf(this.bot))) {
if (typeof this.bot[method] !== "function") continue;
if (method === "constructor" || method === "on" || method === "onText") continue;
if (/^_/.test(method)) continue; // Do not expose internal methods
this.log.debug(`Binding ${method}`);
loadedPlugin[method] = this.bot[method].bind(this.bot);
}
this.log.debug(`Created ${pluginName}.`);
return loadedPlugin;
}
// Adds the plugin to the list of active plugins
addPlugin(loadedPlugin) {
this.plugins.push(loadedPlugin);
this.log.verbose(`Added ${loadedPlugin.plugin.name}.`);
}
// Returns true if the plugin was added successfully, false otherwise.
loadAndAdd(pluginName, persist = true) {
try {
const plugin = this.loadPlugin(pluginName);
this.log.debug(pluginName + " loaded correctly.");
this.addPlugin(plugin);
if (persist) {
this.config.activePlugins.push(pluginName);
fs.writeFileSync("config.json", JSON.stringify(this.config, null, 4));
}
} catch (e) {
this.log.warn(`Failed to initialize plugin ${pluginName}.`);
throw e;
}
}
// Load and add every plugin in the list.
loadPlugins(pluginNames, persist = true) {
this.log.verbose(`Loading and adding ${pluginNames.length} plugins...`);
Error.stackTraceLimit = 5; // Avoid printing useless data in stack traces
const log = pluginNames.map(name => {
try {
this.loadAndAdd(name, persist);
return true;
} catch (e) {
this.log.warn(e);
return false;
}
});
if (log.some(result => result !== true)) {
this.log.warn("Some plugins couldn't be loaded.");
}
Error.stackTraceLimit = 10; // Reset to default value
}
// Returns true if at least one plugin was removed
removePlugin(pluginName, persist = true) {
this.log.verbose(`Removing plugin ${pluginName}`);
if (persist) {
this.config.activePlugins = this.config.activePlugins.filter(name => !nameMatches(name));
fs.writeFileSync("config.json", JSON.stringify(this.config, null, 4));
}
const prevPluginNum = this.plugins.length;
const isCurrentPlugin = nameMatches(pluginName);
this.plugins.filter(isCurrentPlugin).forEach(pl => pl.stop());
this.plugins = this.plugins.filter(pl => !isCurrentPlugin(pl));
const curPluginNum = this.plugins.length;
return (prevPluginNum - curPluginNum) > 0;
}
stopPlugins() {
return Promise.all(this.plugins.map(pl => pl.stop()));
}
static getDatabasePath(pluginName) {
return path.join(__dirname, "..", "db", "plugin_" + pluginName + ".json");
}
startSynchronization() {
this.synchronizationInterval = setInterval(() => {
this.log.debug("Starting synchronization");
this.auth.synchronize();
this.plugins.forEach(plugin => {
fs.writeFile(
PluginManager.getDatabasePath(plugin.plugin.name),
JSON.stringify({
db: plugin.db,
blacklist: Array.from(plugin.blacklist)
}),
err => {
if (err) {
this.log.error("Error synchronizing the database", err);
}
}
);
});
}, SYNC_INTERVAL);
}
stopSynchronization() {
if (this.synchronizationInterval) {
clearInterval(this.synchronizationInterval);
}
}
emit(event, message) {
this.log.debug(`Triggered event ${event}`);
let cmdPromise;
if (event !== "message") {
// Command emitter
if (messageIsCommand(message)) {
const {command, args} = parseCommand(message);
cmdPromise = this._emit("_command", {message, command, args});
} else if (message.query !== undefined) {
const parts = message.query.split(" ");
const command = parts[0].toLowerCase();
const args = parts.length > 1 ? parts.slice(1) : [];
cmdPromise = this._emit("_inline_command", {message, command, args});
}
}
const msgPromise = this._emit(event, {message});
return Promise.all([cmdPromise, msgPromise]);
}
_emit(event, data) {
const handlerName = Plugin.handlerNames[event];
return Promise.all(this.plugins
// If the plugin exposes a listener
.filter(pl => handlerName in pl)
// If the plugin is disabled in this chat
.filter(pl => ("chat" in data.message) && !pl.blacklist.has(data.message.chat.id))
.map(pl => {
try {
const ret = pl[handlerName](data)
const smartReply = pl.smartReply.bind(pl);
if (ret && ret.then)
return ret.then(x => smartReply(x, data.message));
return smartReply(ret, data.message);
} catch (e) {
return Promise.reject(e);
}
})
);
}
};
|
/**
Represents a bullet bill enemy.
Code by Rob Kleffner, 2011
*/
Mario.BulletBill = function(world, x, y, dir) {
this.Image = Enjine.Resources.Images["enemies"];
this.World = world;
this.X = x;
this.Y = y;
this.Facing = dir;
this.XPicO = 8;
this.YPicO = 31;
this.Height = 12;
this.Width = 4;
this.PicWidth = 16;
this.YPic = 5;
this.XPic = 0;
this.Ya = -5;
this.DeadTime = 0;
this.Dead = false;
this.Anim = 0;
};
Mario.BulletBill.prototype = new Mario.NotchSprite();
Mario.BulletBill.prototype.CollideCheck = function() {
if (this.Dead) {
return;
}
var xMarioD = Mario.MarioCharacter.X - this.X, yMarioD = Mario.MarioCharacter.Y - this.Y;
if (xMarioD > -16 && xMarioD < 16) {
if (yMarioD > -this.Height && yMarioD < this.World.Mario.Height) {
if (Mario.MarioCharacter.Y > 0 && yMarioD <= 0 && (!Mario.MarioCharacter.OnGround || !Mario.MarioCharacter.WasOnGround)) {
Mario.MarioCharacter.Stomp(this);
this.Dead = true;
this.Xa = 0;
this.Ya = 1;
this.DeadTime = 100;
} else {
Mario.MarioCharacter.GetHurt();
}
}
}
};
Mario.BulletBill.prototype.Move = function() {
var i = 0, sideWaysSpeed = 4;
if (this.DeadTime > 0) {
this.DeadTime--;
if (this.DeadTime === 0) {
this.DeadTime = 1;
for (i = 0; i < 8; i++) {
this.World.AddSprite(new Mario.Sparkle(((this.X + Math.random() * 16 - 8) | 0) + 4, ((this.Y + Math.random() * 8) | 0) + 4, Math.random() * 2 - 1, Math.random() * -1, 0, 1, 5));
}
this.World.RemoveSprite(this);
}
this.X += this.Xa;
this.Y += this.Ya;
this.Ya *= 0.95;
this.Ya += 1;
return;
}
this.Xa = this.Facing * sideWaysSpeed;
this.XFlip = this.Facing === -1;
this.Move(this.Xa, 0);
};
Mario.BulletBill.prototype.SubMove = function(xa, ya) {
this.X += xa;
return true;
};
Mario.BulletBill.prototype.FireballCollideCheck = function(fireball) {
if (this.DeadTime !== 0) {
return false;
}
var xD = fireball.X - this.X, yD = fireball.Y - this.Y;
if (xD > -16 && xD < 16) {
if (yD > -this.Height && yD < fireball.Height) {
return true;
}
}
return false;
};
Mario.BulletBill.prototype.ShellCollideCheck = function(shell) {
if (this.DeadTime !== 0) {
return false;
}
var xD = shell.X - this.X, yD = shell.Y - this.Y;
if (xD > -16 && xD < 16) {
if (yD > -this.Height && yD < shell.Height) {
Enjine.Resources.PlaySound("kick");
this.Dead = true;
this.Xa = 0;
this.Ya = 1;
this.DeadTime = 100;
return true;
}
}
return false;
};
|
'use strict';
var assert = require('assert');
it('throws after timeout', function (done) {
setTimeout(function () {
throw new Error('Exception in delayed function');
}, 10);
});
|
/*
* mocaccino.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
/*globals describe, it*/
'use strict';
describe('cover', function () {
function called() {
return 42;
}
function test(a) {
return a || called();
}
it('yields', function (done) {
setTimeout(done, 50);
});
it('passes', function () {
test(false);
});
});
|
var _curry2 = require('./internal/_curry2');
var _map = require('./internal/_map');
var curryN = require('./curryN');
var pluck = require('./pluck');
/**
* Accepts a converging function and a list of branching functions and returns a new function.
* When invoked, this new function is applied to some arguments, each branching
* function is applied to those same arguments. The results of each branching
* function are passed as arguments to the converging function to produce the return value.
*
* @func
* @memberOf R
* @since v0.4.2
* @category Function
* @sig (x1 -> x2 -> ... -> z) -> [(a -> b -> ... -> x1), (a -> b -> ... -> x2), ...] -> (a -> b -> ... -> z)
* @param {Function} after A function. `after` will be invoked with the return values of
* `fn1` and `fn2` as its arguments.
* @param {Array} functions A list of functions.
* @return {Function} A new function.
* @example
*
* var add = (a, b) => a + b;
* var multiply = (a, b) => a * b;
* var subtract = (a, b) => a - b;
*
* //≅ multiply( add(1, 2), subtract(1, 2) );
* R.converge(multiply, [add, subtract])(1, 2); //=> -3
*
* var add3 = (a, b, c) => a + b + c;
* R.converge(add3, [multiply, add, subtract])(1, 2); //=> 4
*/
module.exports = _curry2(function converge(after, fns) {
return curryN(Math.max.apply(Math, pluck('length', fns)), function() {
var args = arguments;
var context = this;
return after.apply(context, _map(function(fn) {
return fn.apply(context, args);
}, fns));
});
});
|
import {
MISC_SELECTEDPLAYLIST_SET,
MISC_SELECTEDPLAYLIST_CLEAR,
MISC_SONGNAVSELECTION_SET,
} from '../constants';
export function setActivePlaylist(playlistId) {
return {
type: MISC_SELECTEDPLAYLIST_SET,
payload: { playlistId },
};
}
export function clearActivePlaylist() {
return {
type: MISC_SELECTEDPLAYLIST_CLEAR,
};
}
export function setSongNavSelectionType(songNavSelection) {
return {
type: MISC_SONGNAVSELECTION_SET,
payload: {
songNavSelection,
},
};
}
|
angular.module('dialogDemo1', ['ngMaterial'])
.controller('AppCtrl', function($scope, $mdDialog) {
$scope.alert = '';
$scope.showAlert = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
// Modal dialogs should fully cover application
// to prevent interaction outside of dialog
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.clickOutsideToClose(true)
.title('This is an alert title')
.content('You can specify some description text in here.')
.ariaLabel('Alert Dialog Demo')
.ok('Got it!')
.targetEvent(ev)
);
};
$scope.showConfirm = function(ev) {
// Appending dialog to document.body to cover sidenav in docs app
var confirm = $mdDialog.confirm()
.parent(angular.element(document.body))
.title('Would you like to delete your debt?')
.content('All of the banks have agreed to forgive you your debts.')
.ariaLabel('Lucky day')
.ok('Please do it!')
.cancel('Sounds like a scam')
.targetEvent(ev);
$mdDialog.show(confirm).then(function() {
$scope.alert = 'You decided to get rid of your debt.';
}, function() {
$scope.alert = 'You decided to keep your debt.';
});
};
$scope.showAdvanced = function(ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: 'dialog1.tmpl.html',
parent: angular.element(document.body),
targetEvent: ev,
})
.then(function(answer) {
$scope.alert = 'You said the information was "' + answer + '".';
}, function() {
$scope.alert = 'You cancelled the dialog.';
});
};
});
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
}
|
/**
* jquery.calendar.js 1.0
* http://jquerywidget.com
*/
;(function (factory) {
if (typeof define === "function" && (define.amd || define.cmd) && !jQuery) {
// AMD或CMD
define([ "jquery" ],factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
} else {
jQuery = require('jquery')(root);
}
}
factory(jQuery);
return jQuery;
};
} else {
//Browser globals
factory(jQuery);
}
}(function ($) {
$.fn.calendar = function(parameter,getApi) {
if(typeof parameter == 'function'){ //重载
getApi = parameter;
parameter = {};
}else{
parameter = parameter || {};
getApi = getApi||function(){};
}
var defaults = {
prefix:'widget', //生成日历的class前缀
isRange:false, //是否选择范围
limitRange:[], //有效选择区域的范围
highlightRange:[], //指定日期范围高亮
onChange:function(){}, //当前选中月份修改时触发
onSelect:function(){} //选择日期时触发
};
var options = $.extend({}, defaults, parameter);
return this.each(function() {
var $this = $(this);
var $table = $('<table>').appendTo($this);
var $caption = $('<caption>').appendTo($table);
var $prevYear = $('<a class="'+options.prefix+'-prevYear" href="javascript:;"><<</a>').appendTo($caption);
var $prevMonth = $('<a class="'+options.prefix+'-prevMonth" href="javascript:;"><</a>').appendTo($caption);
var $title = $('<span>').appendTo($caption);
var $nextMonth = $('<a class="'+options.prefix+'-nextMonth" href="javascript:;">></a>').appendTo($caption);
var $nextYear = $('<a class="'+options.prefix+'-nextYear" href="javascript:;">>></a>').appendTo($caption);
var $back = $('<a class="'+options.prefix+'-back" href="javascript:;">今天</a>').appendTo($caption);
var _today, //当天
_data, //日期数据
_day, //日历状态
_range = []; //当前选择范围
/***** 节点修改 *****/
$table.append('<thead><tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr></thead>');
var $tbody = $('<tbody>').appendTo($table);
/***** 私有方法 *****/
//获取日期数据
var getDateObj = function(year,month,day){
var date = arguments.length&&year?new Date(year,month-1,day):new Date();
var obj = {
'year':date.getFullYear(),
'month':date.getMonth()+1,
'day':date.getDate(),
'week':date.getDay()
};
obj['code'] = ''+obj['year']+(obj['month']>9?obj['month']:'0'+obj['month'])+(obj['day']>9?obj['day']:'0'+obj['day']);
return obj;
};
//获取当月天数
var getMonthDays = function(obj){
var day = new Date(obj.year,obj.month,0);
return day.getDate();
};
//获取某天日期信息
var getDateInfo = function(obj){
if(options.limitRange.length){
obj['status'] = 'disabled';
for(var i=0;i<options.limitRange.length;i++){
var start = options.limitRange[i][0];
var end = options.limitRange[i][1];
if(start=='today'){
start = _today['code'];
}
if(end=='today'){
end = _today['code'];
}
if(start>end){
start = [end,end=start][0];
}
if(obj['code']>=start&&obj['code']<=end){
obj['status'] = '';
break;
}
}
}
obj['sign'] = [];
if(options.highlightRange.length){
for(var i=0;i<options.highlightRange.length;i++){
var start = options.highlightRange[i][0];
var end = options.highlightRange[i][1];
if(start=='today'){
start = _today['code'];
}
if(end=='today'){
end = _today['code'];
}
if(start>end){
start = [end,end=start][0];
}
if(obj['code']>=start&&obj['code']<=end){
obj['sign'].push('highlight');
break;
}
}
}
if(obj['code']==_today['code']){
obj['sign'].push('today');
}
return obj;
};
var getData = function(obj){
if(typeof obj=='undefined'){
obj = _today;
}
_day = getDateObj(obj['year'],obj['month'],1); //当月第一天
var days = getMonthDays(_day); //当月天数
var data = []; //日历信息
var obj = {};
//上月日期
for(var i=_day['week'];i>0;i--){
obj = getDateObj(_day['year'],_day['month'],_day['day']-i);
var info = getDateInfo(obj);
if(!options.limitRange.length){
info['status'] = 'disabled';
}
data.push(info);
}
//当月日期
for(var i=0;i<days;i++){
obj = {
'year':_day['year'],
'month':_day['month'],
'day':_day['day']+i,
'week':(_day['week']+i)%7
};
obj['code'] = ''+obj['year']+(obj['month']>9?obj['month']:'0'+obj['month'])+(obj['day']>9?obj['day']:'0'+obj['day']);
var info = getDateInfo(obj);
data.push(info);
}
//下月日期
var last = obj;
for(var i=1;last['week']+i<7;i++){
obj = getDateObj(last['year'],last['month'],last['day']+i);
var info = getDateInfo(obj);
if(!options.limitRange.length){
info['status'] = 'disabled';
}
data.push(info);
}
return data;
};
var format = function(data){
options.onChange(_day);
for(var i=0;i<data.length;i++){
var d = data[i];
if(d['status'] == 'active'){
d['status'] = '';
}
}
if(_range.length==2){
var start = _range[0]['code'];
var end = _range[1]['code'];
for(var i=0;i<data.length;i++){
var d = data[i];
if(d['code']>=start&&d['code']<=end){
if(d['status']=='disabled'){
_range[1]=d;
break;
}else{
d['status'] = 'active';
}
}
}
}else if(_range.length==1){
for(var i=0;i<data.length;i++){
var d = data[i];
if(d['code']==_range[0]['code']){
d['status'] = 'active';
}
}
}
var html = '<tr>';
for(var i=0,len=data.length;i<len;i++){
var day = data[i];
var arr = [];
for(var s=0;s<day['sign'].length;s++){
arr.push(options.prefix+'-'+day['sign'][s]);
}
if(day['status']){
arr.push(options.prefix+'-'+day['status']);
}
var className = arr.join(' ');
html+='<td'+(className?' class="'+className+'"':'')+' data-id="'+i+'">\
'+(day['link']?'<a href="'+day['link']+'">'+day['day']+'</a>':'<span>'+day['day']+'</span>')+'\
</td>';
if(i%7==6&&i<len-1){
html+='</tr><tr>';
}
}
html+='</tr>';
$title.html(_day['year']+'年'+_day['month']+'月');
$tbody.html(html);
};
/***** 初始化 *****/
_today = getDateObj();
_day = {
'year':_today['year'],
'month':_today['month']
};
$prevMonth.click(function(){
_day['month']--;
_data = getData(_day);
format(_data);
});
$nextMonth.click(function(){
_day['month']++;
_data = getData(_day);
format(_data);
});
$prevYear.click(function(){
_day['year']--;
_data = getData(_day);
format(_data);
});
$nextYear.click(function(){
_day['year']++;
_data = getData(_day);
format(_data);
});
$back.click(function(){
_data = getData();
format(_data);
});
$this.on('click','td',function(){
var $this = $(this);
var index = $(this).data('id');
var day = _data[index];
if(day['status']!='disabled'){
if(options.isRange){
if(_range.length!=1){
_range = [day];
format(_data);
}else{
_range.push(day);
_range.sort(function(a,b){
return a['code']>b['code'];
});
format(_data);
options.onSelect(_range);
}
}else{
_range = [day];
format(_data);
options.onSelect(_range);
}
}
});
_data = getData();
format(_data);
});
};
}));
|
import Route from '@ember/routing/route';
export default class Index extends Route {
async model() {
return await this.modelFor('blog');
}
resetController(controller, isExiting, transition) {
if (isExiting && transition.targetName !== 'error') {
controller.set('page', 1);
}
}
}
|
/* global describe, it */
var assert = require('assert');
var jsdom = require('mocha-jsdom');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var stubContext = require('react-stub-context');
var Three = require('../src/Three');
describe('Three', function () {
jsdom();
var levels, content, render;
it('renders one level deep', function () {
render = TestUtils.renderIntoDocument(
React.createElement(Three)
);
levels = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
assert.equal(levels.length, 1);
});
describe('without context', function () {
it('renders nothing without context from parents at one level deep', function () {
render = TestUtils.renderIntoDocument(
React.createElement(Three)
);
content = render.getDOMNode().textContent;
assert.notEqual(content.indexOf('Three (, )'), -1);
});
});
describe('with context', function () {
it('renders context from parents at one level deep', function () {
Three = stubContext(Three, { a: 'Aye', b: 'Bee' });
render = TestUtils.renderIntoDocument(
React.createElement(Three)
);
content = render.getDOMNode().textContent;
assert.notEqual(content.indexOf('Three (Aye, Bee)'), -1);
});
});
});
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./app.ts");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./app.ts":
/*!****************!*\
!*** ./app.ts ***!
\****************/
/*! no static exports found */
/***/ (function(module, exports) {
eval("throw new Error(\"Module parse failed: Unexpected token (2:1)/nYou may need an appropriate loader to handle this file type./n| var a;/n| == 0;/n| \");\n\n//# sourceURL=webpack:///./app.ts?");
/***/ })
/******/ });
|
var searchData=
[
['addra',['addrA',['../a00028.html#a3cae9d5d9bef65c080151c7a068aba59',1,'ip_addr']]],
['addrb',['addrB',['../a00028.html#affc4950defbac0add14648c302d1cca3',1,'ip_addr']]],
['addrc',['addrC',['../a00028.html#a2965c835c1e5f0a593e0ce78a9e22596',1,'ip_addr']]],
['addrd',['addrD',['../a00028.html#a46e67573cf0c4c6cc8fcaf4573a441c5',1,'ip_addr']]],
['adv',['adv',['../a00043.html#aa0b33ec0b236628dd65628a7aa238b03',1,'utils_temperature']]],
['aitc',['aitc',['../a00046.html#a4ef06d5c9fc774f79cf065ec4d971518',1,'aitc.c']]],
['all_5fships',['all_ships',['../a00101.html#af4ba9abb0410a1ddc659f565de7a0e00',1,'model_battleship.c']]],
['apprunning',['appRunning',['../a00099.html#a2c9ae8a4de631e631a531446605ee47d',1,'model.c']]],
['apptext',['appText',['../a00099.html#acb5bd952a87114eb0c59dcba58e5f782',1,'model.c']]],
['arpcache',['arpcache',['../a00108.html#a7489612cbdbbec7ea6dc20811cafd90f',1,'network.h']]]
];
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("widget","en-gb",{move:"Click and drag to move"});
|
import { initialize } from 'ember-off-canvas-components/initializers/custom-events';
export default {
name: 'eoc-custom-events',
initialize: initialize
};
|
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import NoteAdd from 'material-ui/svg-icons/action/note-add';
import Delete from 'material-ui/svg-icons/action/delete';
import IconMenu from 'material-ui/IconMenu';
import ShowChart from 'material-ui/svg-icons/editor/show-chart';
import MenuItem from 'material-ui/MenuItem';
import History from 'material-ui/svg-icons/action/history';
import IconButtonElement from 'components/utils/IconButtonElement';
import { openKeyDialog,
openConfirmDeleteNamespaceDialog } from 'actions/dialogActions';
const anchorOrigin = {
vertical: 'bottom',
horizontal: 'left',
};
const targetOrigin = {
vertical: 'top',
horizontal: 'left',
};
export class NamespaceItemMenu extends Component {
createKey(name) {
this.props.newKey(name);
}
deleteNamespace(name) {
this.props.deleteNamespace(name);
}
render() {
const { name, ...props } = this.props;
return (
<IconMenu disableAutoFocus
iconButtonElement={ <IconButtonElement /> }
anchorOrigin={ anchorOrigin }
targetOrigin={ targetOrigin }
{...props}
>
<MenuItem leftIcon={<NoteAdd />} onTouchTap={ this.createKey.bind(this, name) }>
New key
</MenuItem>
<MenuItem leftIcon={<ShowChart />} containerElement={<Link to={`/stats/${name}`} />}>
Statistics
</MenuItem>
<MenuItem containerElement={<Link to={`/history/${name}`} />} leftIcon={<History />}>
History
</MenuItem>
<MenuItem leftIcon={<Delete />} onTouchTap={ this.deleteNamespace.bind(this, name) }>
Delete
</MenuItem>
</IconMenu>
);
}
}
NamespaceItemMenu.propTypes = {
name: PropTypes.string,
deleteNamespace: PropTypes.func,
newKey: PropTypes.func,
};
const mapDispatchToProps = (dispatch) => ({
deleteNamespace(namespace) {
dispatch(openConfirmDeleteNamespaceDialog({ namespace }));
},
newKey(namespace) {
dispatch(openKeyDialog({ namespace }));
},
});
export default connect(
null,
mapDispatchToProps
)(NamespaceItemMenu);
|
/*! 1.2.7 */
window.XMLHttpRequest&&window.FormData&&(XMLHttpRequest=function(a){return function(){var b=new a;return b.setRequestHeader=function(a){return function(c,d){if("__setXHR_"===c){var e=d(b);e instanceof Function&&e(b)}else a.apply(b,arguments)}}(b.setRequestHeader),b}}(XMLHttpRequest),window.XMLHttpRequest.__isShim=!0);
|
const ClientCommand = require('./_base-command.js');
/**
* Maximizes the current window.
*
* @example
* this.demoTest = function (browser) {
* browser.maximizeWindow();
* };
*
*
* @method maximizeWindow
* @param {function} [callback] Optional callback function to be called when the command finishes.
* @see windowMaximize
* @api protocol.contexts
*/
class WindowMaximize extends ClientCommand {
performAction(callback) {
this.api.windowMaximize('current', callback);
}
}
module.exports = WindowMaximize;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var IoIonic = function IoIonic(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm32.9 10.4c1.9 2.6 3.1 6 3.1 9.6 0 9-7.3 16.3-16.2 16.3s-16.3-7.3-16.3-16.3 7.3-16.2 16.3-16.2c3.5 0 6.9 1.1 9.6 3.1 0.4-0.3 0.8-0.4 1.4-0.4 1.4 0 2.5 1.1 2.5 2.5 0 0.5-0.2 1-0.4 1.4z m-2.5 20.2c1.4-1.4 2.4-2.9 3.2-4.7 0.8-1.9 1.2-3.9 1.2-5.9s-0.4-4-1.2-5.9c-0.5-1-1-2-1.7-2.9-0.3 0.1-0.7 0.3-1.1 0.3-1.4 0-2.5-1.1-2.5-2.5 0-0.4 0.1-0.9 0.3-1.2-1-0.6-2-1.2-3-1.6-1.9-0.8-3.8-1.2-5.8-1.2s-4 0.4-5.9 1.2c-1.8 0.8-3.4 1.8-4.8 3.2s-2.4 2.9-3.2 4.7c-0.8 1.9-1.1 3.9-1.1 5.9s0.3 4 1.1 5.9c0.8 1.8 1.8 3.3 3.2 4.7s3 2.4 4.8 3.2c1.9 0.8 3.8 1.2 5.9 1.2s3.9-0.4 5.8-1.2c1.8-0.8 3.4-1.8 4.8-3.2z m-18.1-10.6c0-5 2.5-7.5 7.5-7.5s7.5 2.5 7.5 7.5-2.5 7.5-7.5 7.5-7.5-2.5-7.5-7.5z' })
)
);
};
exports.default = IoIonic;
module.exports = exports['default'];
|
$(function () {
if (!Modernizr.json) {
alert('Navegador muy antiguo, por favor actualícelo');
window.location = "http://whatbrowser.org/"
}
});
|
var baseDifference = require('../internal/baseDifference'),
baseFlatten = require('../internal/baseFlatten'),
isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
restParam = require('../function/restParam');
/**
* Creates an array excluding all values of the provided arrays using
* `SameValueZero` for equality comparisons.
*
* **Note:** [`SameValueZero`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)
* comparisons are like strict equality comparisons, e.g. `===`, except that
* `NaN` matches `NaN`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.difference([1, 2, 3], [4, 2]);
* // => [1, 3]
*/
var difference = restParam(function(array, values) {
return (isArray(array) || isArguments(array))
? baseDifference(array, baseFlatten(values, false, true))
: [];
});
module.exports = difference;
|
// class HandleDeleteApplication {
// constructor() {
// this.ui = {};
//
// this.applications_page = $('div#third_party_applications_page');
//
// //Delete aplication modal
// this.modal_delete_application = $('div#delete_application_modal');
// this.button_delete_application = $(
// 'button#delete_application',
// this.applications_page
// );
// this.form_delete_application = $(
// 'form#delete_application_form',
// this.modal_delete_application
// );
// }
// }
|
var block = {
"tags":["video-tag"],
"videos":["https:\/\/www.youtube.com\/v\/YigKNDHhjTA?version=3&f=videos&app=youtube_gdata"],
"liked":false,
"notebooks":["47307eb6-cd32-4544-9677-1ba276b54dd3"],
"image":"https:\/\/i1.ytimg.com\/vi\/YigKNDHhjTA\/0.jpg",
"type":"Video",
"url":"https:\/\/www.youtube.com\/watch?v=YigKNDHhjTA&feature=youtube_gdata_player",
"modified":"2014-05-19T14:08:05+0000",
"created":"2014-05-19T14:07:57+0000",
"complete":false,
"description":"FREE Download: http:\/\/www.mediafire.com\/?oj4x2qokmsner8u\n\nCover \/ Remix of \"All of the Lights\" (originally by Kanye West) performed by The Northern Lights. The Northern Lights is: Kyle Lampert, producer; Riki Lavi, vocalist; and MCs Jahizzi and Sheck, also of Divine Rhyme.\n\nOur 2010 album on iTunes:\nhttp:\/\/itunes.apple.com\/us\/album\/journey-through-your-minds\/id353700260\n\nFree ALBUM downloads from The Northern Lights and Divine Rhyme available at\nhttp:\/\/www.TheNorthernLights.bandcamp.com\nhttp:\/\/www.DivineRhyme.bandcamp.com\n\nFollow us on Facebook: http:\/\/www.facebook.com\/TNLexperience",
"name":"All of the Lights - kanye west cover (by The Northern Lights)",
"uuid":"473d3867-e3b6-4fc4-8f51-fa27aab65c28",
"rating":0.0,
"public":true,
"comments":[
{
"commenter":"klmprt",
"date":"2014-05-19T14:07:58+0000",
"comment":"VIdeo comment"
}]
};
|
$(document).ready(function() {
//WAYPOINT - JQUERY COUNTTO PROGRESS BAR//
$('#count-wrapper').waypoint(function() {
$('.title-count').countTo();
}, {
offset: '80%',
triggerOnce: true
});
// MIXITUP PORTFOLIO
$(function() {
$('#container-mixitup').mixItUp();
});
// MAGNIFIC POPUP
$('#container-mixitup').magnificPopup({
delegate: 'a', // child items selector, by clicking on it popup will open
type: 'image'
// other options
});
//GOOGLE MAPS //
var myLatlng = new google.maps.LatLng(40.6700, -73.9400);
var mapOptions = {
zoom: 11,
scrollwheel: false,
center: myLatlng,
styles: [{
featureType: "landscape",
stylers: [{
saturation: -100
}, {
lightness: 65
}, {
visibility: "on"
}]
}, {
featureType: "poi",
stylers: [{
saturation: -100
}, {
lightness: 51
}, {
visibility: "simplified"
}]
}, {
featureType: "road.highway",
stylers: [{
saturation: -100
}, {
visibility: "simplified"
}]
}, {
featureType: "road.arterial",
stylers: [{
saturation: -100
}, {
lightness: 30
}, {
visibility: "on"
}]
}, {
featureType: "road.local",
stylers: [{
saturation: -100
}, {
lightness: 40
}, {
visibility: "on"
}]
}, {
featureType: "transit",
stylers: [{
saturation: -100
}, {
visibility: "simplified"
}]
}, {
featureType: "administrative.province",
stylers: [{
visibility: "off"
}] /**/
}, {
featureType: "administrative.locality",
stylers: [{
visibility: "off"
}]
}, {
featureType: "administrative.neighborhood",
stylers: [{
visibility: "on"
}] /**/
}, {
featureType: "water",
elementType: "labels",
stylers: [{
visibility: "on"
}, {
lightness: -25
}, {
saturation: -100
}]
}, {
featureType: "water",
elementType: "geometry",
stylers: [{
hue: "#ffff00"
}, {
lightness: -25
}, {
saturation: -97
}]
}]
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// To add the marker to the map, use the 'map' property
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Hello World!"
});
// Clients Slider
$("#owl-clients").owlCarousel({
autoPlay: 4500,
items: 4,
pagination: false,
itemsCustom: [
[0, 3],
[450, 4]
]
});
// validate contact form
$(function() {
$('#contact').validate({
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
message: {
required: true
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "your name must consist of at least 2 characters"
},
email: {
required: "Please enter your email address"
},
message: {
required: "Please enter your message",
minlength: "thats all? really?"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"contact.php",
success: function() {
$('#contact').css( "display", 'none');
$('#contact :input').attr('disabled', 'disabled');
$('#success').fadeIn();
},
error: function() {
$('#contact').css( "display", 'none');
$('#contact :input').attr('disabled', 'disabled');
$('#error').fadeIn();
}
});
}
});
});
$(function () {
$('[data-toggle="tooltip"]').tooltip();
});
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.14_A10_T1;
* @section: 12.14;
* @assertion: Using "try" with "catch" or "finally" statement within/without a "while" statement;
* @description: Throwing exception while executing iteration statement placed into try Block;
*/
// CHECK#1
var i=0;
try{
while(i<10){
if(i===5) throw i;
i++;
}
}
catch(e){
if(e!==5)$ERROR('#1: Exception === 5. Actual: Exception ==='+ e );
}
|
'use strict';
var chai = require('chai'),
chaiAsPromised = require('chai-as-promised');
if (!global.Promise) {
global.Promise = require('promise-polyfill');
}
chai.use(chaiAsPromised);
chai.should();
var async = require('../../lib/async-as-promised');
describe('aplus', function () {
describe('setPromise()', function () {
afterEach(function () {
async.resetPromise();
});
it('should set async.Promise', function () {
var value = Math.random();
async.setPromise(value);
async.Promise.should.equal(value);
});
});
describe('resetPromise()', function () {
afterEach(function () {
async.resetPromise();
});
it('should restore async.Promise', function () {
var value = async.Promise;
async.Promise = Math.random();
async.resetPromise();
async.Promise.should.equal(value);
});
});
});
describe('async.constant()', function () {
it('should return a Promise', function () {
async.constant(5).should.be.an.instanceOf(Promise);
});
it('should resolve to provided value', function () {
return async.constant(5).should.eventually.equal(5);
});
});
describe('async.fail()', function () {
it('should return a Promise', function () {
async.fail('boo!').should.be.an.instanceOf(Promise);
});
it('should resolve to provided value', function () {
return async.fail('boo!').should.eventually.be.rejectedWith('boo!');
});
});
describe('async.delay()', function () {
it('should alias async.later to async.delay', function () {
async.later.should.equal(async.delay);
});
it('should return a promise', function () {
async.delay(1).should.be.an.instanceOf(Promise);
});
it('should resolve after delay', function () {
var now = Date.now();
return async.delay(500).then(function () {
(Date.now() - now).should.be.at.least(499);
});
});
it('should resolve using default delay if not specified', function () {
var now = Date.now();
return async.delay().then(function () {
(Date.now() - now).should.be.at.least(99);
});
});
it('should resolve using default delay when no parameters specified', function () {
var now = Date.now();
return async.delay().then(function () {
(Date.now() - now).should.be.at.least(99);
});
});
it('should resolve to `undefined` when no parameters specified', function () {
return async.delay().then(function (value) {
chai.expect(value).to.equal(undefined);
});
});
it('should resolve using default delay when only value specified', function () {
var now = Date.now();
return async.delay('hi!').then(function () {
(Date.now() - now).should.be.at.least(99);
});
});
it('should resolve to value when only value specified', function () {
return async.delay('hi!').then(function (value) {
value.should.equal('hi!');
});
});
it('should resolve using provided delay when delay and value specified', function () {
var now = Date.now();
return async.delay(200, 'bye!').then(function () {
(Date.now() - now).should.be.at.least(199);
});
});
it('should resolve to value when delay and value specified', function () {
return async.delay(50, 'bye').then(function (value) {
value.should.equal('bye');
});
});
it('should throw exception when non number provided as delay and value is specified', function () {
function test() {
return async.delay('five seconds', 'hi!');
}
chai.expect(test).to.throw(TypeError);
});
it('should throw expected message for invalid delay', function () {
function test() {
return async.delay('five seconds', 'hi!');
}
chai.expect(test).to.throw('parameter ms must be a number, string was provided instead');
});
});
|
'use strict';
var ssacl = require('../lib')
, chai = require('chai')
, expect = chai.expect
, helper = require('./helper')
, Sequelize = require('sequelize')
, Promise = helper.Promise;
Promise.longStackTraces();
chai.use(require('chai-as-promised'));
describe('writer', function () {
beforeEach(function () {
this.Post = this.sequelize.define('Post', {
title: {
type: Sequelize.STRING
},
userId: {
type: Sequelize.INTEGER,
allowNull: false,
defaultValue: 0
}
});
this.User = this.sequelize.define('User', {
});
return Promise.join(
this.Post.sync({force: true}),
this.User.sync({force: true})
).bind(this).then(function () {
return this.User.create();
}).then(function (user) {
this.user = user;
return this.Post.create({
title: 'Super Awesome Post',
userId: this.user.get('id')
});
}).then(function (post) {
this.post = post;
});
});
describe('Instance.update', function () {
beforeEach(function () {
ssacl(this.Post, {
write: {
attribute: 'userId'
}
});
});
it('should reject update without actor', function () {
return expect(this.post.update({
title: 'Less Awesome Post'
})).be.rejectedWith(ssacl.ParanoiaError);
});
it('should reject update with wrong actor', function () {
return expect(this.post.update({
title: 'Less Awesome Post'
}, {
actor: this.User.build({
id: this.user.get('id')+13
})
})).be.rejectedWith(ssacl.WrongActorError);
});
it('should allow update when correct actor', function () {
return this.post.update({
title: 'Super Duper Awesome Post'
}, {
actor: this.user
});
});
it('should allow update when omnipotent actor', function () {
return this.post.update({
title: 'Super Duper Awesome Post'
}, {
actor: new ssacl.Omnipotent()
});
});
});
describe('Model.update', function () {
beforeEach(function () {
ssacl(this.Post, {
write: {
attribute: 'userId'
}
});
});
it('should reject update without actor', function () {
return expect(this.Post.update({
title: 'Less Awesome Post'
}, {
where: {}
})).be.rejectedWith(ssacl.ParanoiaError);
});
it('should filter update to actor', function () {
return this.Post.update({
title: 'Less Awesome Post',
}, {
where: {},
actor: this.User.build({
id: this.user.get('id')+13
})
}).bind(this).spread(function (affected) {
expect(affected).to.equal(0);
return this.Post.findAll({
paranoia: false
}).then(function (posts) {
expect(posts[0].get('title')).to.equal('Super Awesome Post');
});
}).then(function () {
return this.Post.update({
title: 'Super Duper Awesome Post',
}, {
where: {},
actor: this.user
}).bind(this).spread(function (affected) {
expect(affected).to.equal(1);
return this.Post.findAll({
paranoia: false
}).then(function (posts) {
expect(posts[0].get('title')).to.equal('Super Duper Awesome Post');
});
});
});
});
});
describe('Instance.destroy', function () {
beforeEach(function () {
ssacl(this.Post, {
write: {
attribute: 'userId'
}
});
});
it('should reject destroy without actor', function () {
return expect(this.post.destroy()).be.rejectedWith(ssacl.ParanoiaError);
});
it('should reject destroy with wrong actor', function () {
return expect(this.post.destroy({
actor: this.User.build({
id: this.user.get('id')+13
})
})).be.rejectedWith(ssacl.WrongActorError);
});
it('should allow destroy when correct actor', function () {
return this.post.destroy({
actor: this.user
});
});
it('should allow destroy when omnipotent actor', function () {
return this.post.destroy({
actor: new ssacl.Omnipotent()
});
});
});
describe('Model.destroy', function () {
beforeEach(function () {
ssacl(this.Post, {
write: {
attribute: 'userId'
}
});
});
it('should reject destroy without actor', function () {
return expect(this.Post.destroy({
where: {}
})).be.rejectedWith(ssacl.ParanoiaError);
});
it('should filter destroy to actor', function () {
return this.Post.destroy({
where: {},
actor: this.User.build({
id: this.user.get('id')+13
})
}).bind(this).then(function (affected) {
expect(affected).to.equal(0);
return this.Post.findAll({
paranoia: false
}).then(function (posts) {
expect(posts.length).to.equal(1);
});
}).then(function () {
return this.Post.destroy({
where: {},
actor: this.user
}).bind(this).then(function (affected) {
expect(affected).to.equal(1);
return this.Post.findAll({
paranoia: false
}).then(function (posts) {
expect(posts.length).to.equal(0);
});
});
});
});
});
});
|
'use strict'
/*global describe, it, before, after, beforeEach */
var should = require('should')
var thunk = require('thunks')()
var JSONKit = require('jsonkit')
var redis = require('../index')
module.exports = function () {
describe('commands:Set', function () {
var client
before(function () {
client = redis.createClient({
database: 0
})
client.on('error', function (error) {
console.error('redis client:', error)
})
})
beforeEach(function (done) {
client.flushdb()(function (error, res) {
should(error).be.equal(null)
should(res).be.equal('OK')
})(done)
})
after(function () {
client.clientEnd()
})
it('client.sadd, client.scard', function (done) {
client.scard('setA')(function (error, res) {
should(error).be.equal(null)
should(res).be.equal(0)
return thunk.all(this.set('key', 'abc'), this.scard('key'))
})(function (error, res) {
should(error).be.instanceOf(Error)
return this.sadd('key', 'a')
})(function (error, res) {
should(error).be.instanceOf(Error)
return thunk.all(this.sadd('setA', 'a', 'b'), this.sadd('setA', 'b', 'c'), this.sadd('setA', 'a', 'c'), this.scard('setA'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([2, 1, 0, 3])
})(done)
})
it('client.sdiff, client.sdiffstore', function (done) {
client.sdiff('setA')(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([])
return thunk.all(this.sadd('setA', 'a', 'b', 'c'), this.sadd('setB', 'b', 'c', 'd'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([3, 3])
return thunk.all(client.sdiff('setA'), client.sdiff('setA', 'setB'), client.sdiff('setA', 'setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res[0].length).be.equal(3)
should(res[0]).be.containEql('a')
should(res[0]).be.containEql('b')
should(res[0]).be.containEql('c')
should(res[1].length).be.equal(1)
should(res[1]).be.containEql('a')
should(res[2].length).be.equal(3)
should(res[2]).be.containEql('a')
should(res[2]).be.containEql('b')
should(res[2]).be.containEql('c')
return thunk.all(client.sdiffstore('setC', 'setA', 'setB'), client.sdiffstore('setA', 'setA', 'setB'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([1, 1])
return thunk.all(this.scard('setA'), this.scard('setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([1, 1])
})(done)
})
it('client.sinter, client.sinterstore', function (done) {
client.sinter('setA')(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([])
return thunk.all(this.sadd('setA', 'a', 'b', 'c'), this.sadd('setB', 'b', 'c', 'd'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([3, 3])
return thunk.all(client.sinter('setA'), client.sinter('setA', 'setB'), client.sinter('setA', 'setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res[0].length).be.equal(3)
should(res[0]).be.containEql('a')
should(res[0]).be.containEql('b')
should(res[0]).be.containEql('c')
should(res[1].length).be.equal(2)
should(res[1]).be.containEql('b')
should(res[1]).be.containEql('c')
should(res[2].length).be.equal(0)
return thunk.all(client.sinterstore('setC', 'setA', 'setB'), client.sinterstore('setA', 'setA', 'setB'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([2, 2])
return thunk.all(this.scard('setA'), this.scard('setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([2, 2])
})(done)
})
it('client.sismember, client.smembers', function (done) {
client.smembers('setA')(function (error, res) {
should(error).be.equal(null)
should(res).be.equal([])
return thunk.all(this.set('key', 'abc'), this.smembers('key'))
})(function (error, res) {
should(error).be.instanceOf(Error)
return thunk.all(this.sadd('setA', 'a', 'b', 'c'), this.smembers('setA'))
})(function (error, res) {
should(error).be.equal(null)
should(res[0]).be.equal(3)
should(res[1].length).be.equal(3)
should(res[1]).be.containEql('a')
should(res[1]).be.containEql('b')
should(res[1]).be.containEql('c')
return thunk.all(this.sismember('setA', 'a'), this.sismember('setA', 'd'), this.sismember('setB', 'd'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([1, 0, 0])
})(done)
})
it('client.smove, client.spop', function (done) {
client.smove('setA', 'setB', 'a')(function (error, res) {
should(error).be.equal(null)
should(res).be.equal(0)
return thunk.all(this.sadd('setA', 'a', 'b', 'c'), this.smove('setA', 'setB', 'a'), this.smove('setA', 'setB', 'd'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([3, 1, 0])
return thunk.all(this.sadd('setB', 'b'), this.smove('setA', 'setB', 'b'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([1, 1])
return thunk.all(this.spop('setA'), this.spop('setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql(['c', null])
})(done)
})
it('client.srandmember, client.srem', function (done) {
client.srandmember('setA')(function (error, res) {
should(error).be.equal(null)
should(res).be.equal(null)
return thunk.all(this.sadd('setA', 'a', 'b', 'c'), this.srandmember('setA'), this.srandmember('setA', 2))
})(function (error, res) {
should(error).be.equal(null)
should(res[0]).be.eql(3)
should(['a', 'b', 'c']).be.containEql(res[1])
should(res[2].length).be.equal(2)
should(['a', 'b', 'c']).be.containEql(res[2][0])
should(['a', 'b', 'c']).be.containEql(res[2][1])
return thunk.all(this.scard('setA'), this.srem('setA', 'b', 'd'), this.srem('setA', 'b', 'a', 'c'), this.scard('setA'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([3, 1, 2, 0])
})(done)
})
it('client.sunion, client.sunionstore', function (done) {
client.sunion('setA')(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([])
return thunk.all(this.sadd('setA', 'a', 'b', 'c'), this.sadd('setB', 'b', 'c', 'd'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([3, 3])
return thunk.all(client.sunion('setA'), client.sunion('setA', 'setB'), client.sunion('setA', 'setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res[0].length).be.equal(3)
should(res[0]).be.containEql('a')
should(res[0]).be.containEql('b')
should(res[0]).be.containEql('c')
should(res[1].length).be.equal(4)
should(res[1]).be.containEql('a')
should(res[1]).be.containEql('b')
should(res[1]).be.containEql('c')
should(res[1]).be.containEql('d')
should(res[2].length).be.equal(3)
return thunk.all(client.sunionstore('setC', 'setA', 'setB'), client.sunionstore('setA', 'setA', 'setB'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([4, 4])
return thunk.all(this.scard('setA'), this.scard('setC'))
})(function (error, res) {
should(error).be.equal(null)
should(res).be.eql([4, 4])
})(done)
})
it('client.sscan', function (done) {
var count = 100
var data = []
var scanKeys = []
while (count--) data.push('m' + count)
function fullScan (cursor) {
return client.sscan('set', cursor)(function (error, res) {
should(error).be.equal(null)
scanKeys = scanKeys.concat(res[1])
if (res[0] === '0') return res
return fullScan(res[0])
})
}
client.sscan('set', 0)(function (error, res) {
should(error).be.equal(null)
should(res).be.eql(['0', []])
var args = data.slice()
args.unshift('set')
return this.sadd.apply(this, args)
})(function (error, res) {
should(error).be.equal(null)
should(res).be.equal(100)
return fullScan(0)
})(function (error, res) {
should(error).be.equal(null)
should(scanKeys.length).be.equal(100)
JSONKit.each(data, function (value) {
should(scanKeys).be.containEql(value)
})
return this.sscan('set', 0, 'count', 20)
})(function (error, res) {
should(error).be.equal(null)
should(res[0] > 0).be.equal(true)
should(res[1].length > 0).be.equal(true)
return this.sscan('set', 0, 'count', 200, 'match', '*0')
})(function (error, res) {
should(error).be.equal(null)
should(res[0] === '0').be.equal(true)
should(res[1].length === 10).be.equal(true)
})(done)
})
})
}
|
/**
* Custom error types to differentiate eBay response errors and client-level errors.
*
* @see http://developer.ebay.com/devzone/xml/docs/Reference/ebay/Errors/ErrorMessages.htm
*/
var
inherits = require('util').inherits,
_ = require('lodash');
function EbayClientError(message, extraProps) {
Error.apply(this, arguments);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
_.defaults(this, extraProps);
}
inherits(EbayClientError, Error);
function EbaySystemError(message, extraProps) {
EbayClientError.apply(this, arguments);
this.name = this.constructor.name;
}
inherits(EbaySystemError, EbayClientError);
function EbayRequestError(message) {
EbayClientError.apply(this, arguments);
this.name = this.constructor.name;
}
inherits(EbayRequestError, EbayClientError);
function EbayAuthenticationError(message) {
EbayClientError.apply(this, arguments);
this.name = this.constructor.name;
}
inherits(EbayAuthenticationError, EbayClientError);
module.exports = {
EbayClientError: EbayClientError,
EbaySystemError: EbaySystemError,
EbayRequestError: EbayRequestError,
EbayAuthenticationError: EbayAuthenticationError,
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.