text
stringlengths 2
1.05M
|
|---|
import {
GET_FEATURES,
ADD_FEATURE,
REMOVE_FEATURE,
TOGGLE_FEATURE,
UPDATE_FEATURE_GROUPS,
UPDATE_FEATURE_USERS,
UPDATE_FEATURE_PERCENTAGE,
} from './actionTypes';
export const addFeature = feature => ({
type: ADD_FEATURE,
payload: feature,
})
export const removeFeature = feature => ({
type: REMOVE_FEATURE,
payload: feature,
})
export const getFeatures = (features) => ({
type: GET_FEATURES,
payload: {
features,
},
})
export const toggleFeature = (key, status) => ({
type: TOGGLE_FEATURE,
payload: {
key: key,
enabled: status,
},
})
export const updateFeatureGroups = (key, groups) => ({
type: UPDATE_FEATURE_GROUPS,
payload: {
key: key,
groups: groups,
}
})
export const updateFeatureUsers = (key, users) => ({
type: UPDATE_FEATURE_USERS,
payload: {
key: key,
users: users,
}
})
export const updateFeaturePercentage = (key, percentage) => ({
type: UPDATE_FEATURE_PERCENTAGE,
payload: {
key: key,
percentage: percentage,
}
})
|
var express = require('express');
var app = express();
app.use(express.static('public'));
// //setup for local development
// app.get("/data", function (req, res) {
// const content = require('./service/content.json');
// res.send(content);
// });
app.listen(3000);
|
var expect = require("chai").expect;
module.exports = function(helpers) {
var items = ["a", "b", "c"];
var count = 0;
var component = helpers.mount(require.resolve("./index"), {
items: items,
count: count
});
expect(
helpers.targetEl.firstElementChild.getAttribute("data-count")
).to.equal("0");
Array.from(helpers.targetEl.firstElementChild.childNodes).forEach(child => {
if (child.tagName === "div") {
expect(child.getAttribute("data-count")).to.equal("0");
}
});
expect(helpers.targetEl.textContent).to.equal("abc");
component.input = {
count: ++count,
items: [].concat(items).reverse()
};
component.update();
expect(
helpers.targetEl.firstElementChild.getAttribute("data-count")
).to.equal("1");
Array.from(helpers.targetEl.firstElementChild.childNodes).forEach(child => {
if (child.tagName === "div") {
expect(child.getAttribute("data-count")).to.equal("0");
}
});
expect(helpers.targetEl.textContent).to.equal("cba");
};
|
define(['dart_sdk'], function(dart_sdk) {
'use strict';
const core = dart_sdk.core;
const typed_data = dart_sdk.typed_data;
const collection = dart_sdk.collection;
const _native_typed_data = dart_sdk._native_typed_data;
const dart = dart_sdk.dart;
const dartx = dart_sdk.dartx;
const typed_buffers = Object.create(dart.library);
const $length = dartx.length;
const $_get = dartx._get;
const $_set = dartx._set;
const $setRange = dartx.setRange;
const $elementSizeInBytes = dartx.elementSizeInBytes;
const $offsetInBytes = dartx.offsetInBytes;
const $buffer = dartx.buffer;
const $addAll = dartx.addAll;
const $insertAll = dartx.insertAll;
const CT = Object.create(null);
const _buffer = dart.privateName(typed_buffers, "_buffer");
const _length = dart.privateName(typed_buffers, "_length");
const _typedBuffer = dart.privateName(typed_buffers, "_typedBuffer");
const _defaultValue = dart.privateName(typed_buffers, "_defaultValue");
const _createBuffer = dart.privateName(typed_buffers, "_createBuffer");
const _createBiggerBuffer = dart.privateName(typed_buffers, "_createBiggerBuffer");
const _grow = dart.privateName(typed_buffers, "_grow");
const _add = dart.privateName(typed_buffers, "_add");
const _addAll = dart.privateName(typed_buffers, "_addAll");
const _insertKnownLength = dart.privateName(typed_buffers, "_insertKnownLength");
const _ensureCapacity = dart.privateName(typed_buffers, "_ensureCapacity");
const _setRange = dart.privateName(typed_buffers, "_setRange");
const _is__TypedDataBuffer_default = Symbol('_is__TypedDataBuffer_default');
typed_buffers._TypedDataBuffer$ = dart.generic(E => {
let IterableOfE = () => (IterableOfE = dart.constFn(core.Iterable$(E)))();
let _TypedDataBufferOfE = () => (_TypedDataBufferOfE = dart.constFn(typed_buffers._TypedDataBuffer$(E)))();
class _TypedDataBuffer extends collection.ListBase$(E) {
get [_typedBuffer]() {
return typed_data.TypedData.as(this[_buffer]);
}
get length() {
return this[_length];
}
_get(index) {
if (dart.notNull(index) >= dart.notNull(this.length)) dart.throw(new core.IndexError.new(index, this));
return this[_buffer][$_get](index);
}
_set(index, value$) {
let value = value$;
E._check(value);
if (dart.notNull(index) >= dart.notNull(this.length)) dart.throw(new core.IndexError.new(index, this));
this[_buffer][$_set](index, value);
return value$;
}
set length(newLength) {
if (dart.notNull(newLength) < dart.notNull(this[_length])) {
let defaultValue = this[_defaultValue];
for (let i = newLength; dart.notNull(i) < dart.notNull(this[_length]); i = dart.notNull(i) + 1) {
this[_buffer][$_set](i, defaultValue);
}
} else if (dart.notNull(newLength) > dart.notNull(this[_buffer][$length])) {
let newBuffer = null;
if (this[_buffer][$length] === 0) {
newBuffer = this[_createBuffer](newLength);
} else {
newBuffer = this[_createBiggerBuffer](newLength);
}
newBuffer[$setRange](0, this[_length], this[_buffer]);
this[_buffer] = newBuffer;
}
this[_length] = newLength;
}
[_add](value) {
let t0;
if (this[_length] == this[_buffer][$length]) this[_grow](this[_length]);
this[_buffer][$_set]((t0 = this[_length], this[_length] = dart.notNull(t0) + 1, t0), value);
}
add(value) {
E._check(value);
this[_add](value);
}
addAll(values, start, end) {
IterableOfE()._check(values);
if (start === void 0) start = 0;
if (end === void 0) end = null;
core.RangeError.checkNotNegative(start, "start");
if (end != null && dart.notNull(start) > dart.notNull(end)) {
dart.throw(new core.RangeError.range(end, start, null, "end"));
}
this[_addAll](values, start, end);
}
insertAll(index, values, start, end) {
let t0;
IterableOfE()._check(values);
if (start === void 0) start = 0;
if (end === void 0) end = null;
core.RangeError.checkValidIndex(index, this, "index", dart.notNull(this[_length]) + 1);
core.RangeError.checkNotNegative(start, "start");
if (end != null) {
if (dart.notNull(start) > dart.notNull(end)) {
dart.throw(new core.RangeError.range(end, start, null, "end"));
}
if (start == end) return;
}
if (index == this[_length]) {
this[_addAll](values, start, end);
return;
}
if (end == null && core.List.is(values)) {
end = values[$length];
}
if (end != null) {
this[_insertKnownLength](index, values, start, end);
return;
}
let writeIndex = this[_length];
let skipCount = start;
for (let value of values) {
if (dart.notNull(skipCount) > 0) {
skipCount = dart.notNull(skipCount) - 1;
continue;
}
if (writeIndex == this[_buffer][$length]) {
this[_grow](writeIndex);
}
this[_buffer][$_set]((t0 = writeIndex, writeIndex = dart.notNull(t0) + 1, t0), value);
}
if (dart.notNull(skipCount) > 0) {
dart.throw(new core.StateError.new("Too few elements"));
}
if (end != null && dart.notNull(writeIndex) < dart.notNull(end)) {
dart.throw(new core.RangeError.range(end, start, writeIndex, "end"));
}
typed_buffers._TypedDataBuffer._reverse(this[_buffer], index, this[_length]);
typed_buffers._TypedDataBuffer._reverse(this[_buffer], this[_length], writeIndex);
typed_buffers._TypedDataBuffer._reverse(this[_buffer], index, writeIndex);
this[_length] = writeIndex;
return;
}
static _reverse(buffer, start, end) {
end = dart.notNull(end) - 1;
while (dart.notNull(start) < dart.notNull(end)) {
let first = buffer[$_get](start);
let last = buffer[$_get](end);
buffer[$_set](end, first);
buffer[$_set](start, last);
start = dart.notNull(start) + 1;
end = dart.notNull(end) - 1;
}
}
[_addAll](values, start, end) {
if (start === void 0) start = 0;
if (end === void 0) end = null;
if (core.List.is(values)) end == null ? end = values[$length] : null;
if (end != null) {
this[_insertKnownLength](this[_length], values, start, end);
return;
}
let i = 0;
for (let value of values) {
if (i >= dart.notNull(start)) this.add(value);
i = i + 1;
}
if (i < dart.notNull(start)) dart.throw(new core.StateError.new("Too few elements"));
}
[_insertKnownLength](index, values, start, end) {
if (core.List.is(values)) {
end == null ? end = values[$length] : null;
if (dart.notNull(start) > dart.notNull(values[$length]) || dart.notNull(end) > dart.notNull(values[$length])) {
dart.throw(new core.StateError.new("Too few elements"));
}
} else {
if (!(end != null)) dart.assertFailed(null, "org-dartlang-app:///packages/typed_data/typed_buffers.dart", 210, 14, "end != null");
}
let valuesLength = dart.notNull(end) - dart.notNull(start);
let newLength = dart.notNull(this[_length]) + valuesLength;
this[_ensureCapacity](newLength);
this[_buffer][$setRange](dart.notNull(index) + valuesLength, dart.notNull(this[_length]) + valuesLength, this[_buffer], index);
this[_buffer][$setRange](index, dart.notNull(index) + valuesLength, values, start);
this[_length] = newLength;
}
insert(index, element) {
E._check(element);
if (dart.notNull(index) < 0 || dart.notNull(index) > dart.notNull(this[_length])) {
dart.throw(new core.RangeError.range(index, 0, this[_length]));
}
if (dart.notNull(this[_length]) < dart.notNull(this[_buffer][$length])) {
this[_buffer][$setRange](dart.notNull(index) + 1, dart.notNull(this[_length]) + 1, this[_buffer], index);
this[_buffer][$_set](index, element);
this[_length] = dart.notNull(this[_length]) + 1;
return;
}
let newBuffer = this[_createBiggerBuffer](null);
newBuffer[$setRange](0, index, this[_buffer]);
newBuffer[$setRange](dart.notNull(index) + 1, dart.notNull(this[_length]) + 1, this[_buffer], index);
newBuffer[$_set](index, element);
this[_length] = dart.notNull(this[_length]) + 1;
this[_buffer] = newBuffer;
}
[_ensureCapacity](requiredCapacity) {
if (dart.notNull(requiredCapacity) <= dart.notNull(this[_buffer][$length])) return;
let newBuffer = this[_createBiggerBuffer](requiredCapacity);
newBuffer[$setRange](0, this[_length], this[_buffer]);
this[_buffer] = newBuffer;
}
[_createBiggerBuffer](requiredCapacity) {
let newLength = dart.notNull(this[_buffer][$length]) * 2;
if (requiredCapacity != null && dart.notNull(newLength) < dart.notNull(requiredCapacity)) {
newLength = requiredCapacity;
} else if (dart.notNull(newLength) < 8) {
newLength = 8;
}
return this[_createBuffer](newLength);
}
[_grow](length) {
let t0;
this[_buffer] = (t0 = this[_createBiggerBuffer](null), t0[$setRange](0, length, this[_buffer]), t0);
}
setRange(start, end, source, skipCount) {
IterableOfE()._check(source);
if (skipCount === void 0) skipCount = 0;
if (dart.notNull(end) > dart.notNull(this[_length])) dart.throw(new core.RangeError.range(end, 0, this[_length]));
this[_setRange](start, end, source, skipCount);
}
[_setRange](start, end, source, skipCount) {
if (_TypedDataBufferOfE().is(source)) {
this[_buffer][$setRange](start, end, source[_buffer], skipCount);
} else {
this[_buffer][$setRange](start, end, source, skipCount);
}
}
get elementSizeInBytes() {
return this[_typedBuffer][$elementSizeInBytes];
}
get lengthInBytes() {
return dart.notNull(this[_length]) * dart.notNull(this[_typedBuffer][$elementSizeInBytes]);
}
get offsetInBytes() {
return this[_typedBuffer][$offsetInBytes];
}
get buffer() {
return this[_typedBuffer][$buffer];
}
}
(_TypedDataBuffer.new = function(buffer) {
this[_buffer] = buffer;
this[_length] = buffer[$length];
;
}).prototype = _TypedDataBuffer.prototype;
dart.addTypeTests(_TypedDataBuffer);
_TypedDataBuffer.prototype[_is__TypedDataBuffer_default] = true;
dart.setMethodSignature(_TypedDataBuffer, () => ({
__proto__: dart.getMethods(_TypedDataBuffer.__proto__),
_get: dart.fnType(E, [core.int]),
[$_get]: dart.fnType(E, [core.int]),
_set: dart.fnType(dart.void, [core.int, core.Object]),
[$_set]: dart.fnType(dart.void, [core.int, core.Object]),
[_add]: dart.fnType(dart.void, [E]),
addAll: dart.fnType(dart.void, [core.Object], [core.int, core.int]),
[$addAll]: dart.fnType(dart.void, [core.Object], [core.int, core.int]),
insertAll: dart.fnType(dart.void, [core.int, core.Object], [core.int, core.int]),
[$insertAll]: dart.fnType(dart.void, [core.int, core.Object], [core.int, core.int]),
[_addAll]: dart.fnType(dart.void, [core.Iterable$(E)], [core.int, core.int]),
[_insertKnownLength]: dart.fnType(dart.void, [core.int, core.Iterable$(E), core.int, core.int]),
[_ensureCapacity]: dart.fnType(dart.void, [core.int]),
[_createBiggerBuffer]: dart.fnType(core.List$(E), [core.int]),
[_grow]: dart.fnType(dart.void, [core.int]),
[_setRange]: dart.fnType(dart.void, [core.int, core.int, core.Iterable$(E), core.int])
}));
dart.setGetterSignature(_TypedDataBuffer, () => ({
__proto__: dart.getGetters(_TypedDataBuffer.__proto__),
[_typedBuffer]: typed_data.TypedData,
length: core.int,
[$length]: core.int,
elementSizeInBytes: core.int,
lengthInBytes: core.int,
offsetInBytes: core.int,
buffer: typed_data.ByteBuffer
}));
dart.setSetterSignature(_TypedDataBuffer, () => ({
__proto__: dart.getSetters(_TypedDataBuffer.__proto__),
length: core.int,
[$length]: core.int
}));
dart.setLibraryUri(_TypedDataBuffer, "package:typed_data/typed_buffers.dart");
dart.setFieldSignature(_TypedDataBuffer, () => ({
__proto__: dart.getFields(_TypedDataBuffer.__proto__),
[_buffer]: dart.fieldType(core.List$(E)),
[_length]: dart.fieldType(core.int)
}));
dart.defineExtensionMethods(_TypedDataBuffer, [
'_get',
'_set',
'add',
'addAll',
'insertAll',
'insert',
'setRange'
]);
dart.defineExtensionAccessors(_TypedDataBuffer, ['length']);
return _TypedDataBuffer;
});
typed_buffers._TypedDataBuffer = typed_buffers._TypedDataBuffer$();
dart.defineLazy(typed_buffers._TypedDataBuffer, {
/*typed_buffers._TypedDataBuffer.INITIAL_LENGTH*/get INITIAL_LENGTH() {
return 8;
}
});
dart.addTypeTests(typed_buffers._TypedDataBuffer, _is__TypedDataBuffer_default);
typed_buffers._IntBuffer = class _IntBuffer extends typed_buffers._TypedDataBuffer$(core.int) {
get [_defaultValue]() {
return 0;
}
};
(typed_buffers._IntBuffer.new = function(buffer) {
typed_buffers._IntBuffer.__proto__.new.call(this, buffer);
;
}).prototype = typed_buffers._IntBuffer.prototype;
dart.addTypeTests(typed_buffers._IntBuffer);
dart.setGetterSignature(typed_buffers._IntBuffer, () => ({
__proto__: dart.getGetters(typed_buffers._IntBuffer.__proto__),
[_defaultValue]: core.int
}));
dart.setLibraryUri(typed_buffers._IntBuffer, "package:typed_data/typed_buffers.dart");
typed_buffers._FloatBuffer = class _FloatBuffer extends typed_buffers._TypedDataBuffer$(core.double) {
get [_defaultValue]() {
return 0.0;
}
};
(typed_buffers._FloatBuffer.new = function(buffer) {
typed_buffers._FloatBuffer.__proto__.new.call(this, buffer);
;
}).prototype = typed_buffers._FloatBuffer.prototype;
dart.addTypeTests(typed_buffers._FloatBuffer);
dart.setGetterSignature(typed_buffers._FloatBuffer, () => ({
__proto__: dart.getGetters(typed_buffers._FloatBuffer.__proto__),
[_defaultValue]: core.double
}));
dart.setLibraryUri(typed_buffers._FloatBuffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Uint8Buffer = class Uint8Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeUint8List.new(size);
}
};
(typed_buffers.Uint8Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Uint8Buffer.__proto__.new.call(this, _native_typed_data.NativeUint8List.new(initialLength));
;
}).prototype = typed_buffers.Uint8Buffer.prototype;
dart.addTypeTests(typed_buffers.Uint8Buffer);
dart.setMethodSignature(typed_buffers.Uint8Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Uint8Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Uint8List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Uint8Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Int8Buffer = class Int8Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeInt8List.new(size);
}
};
(typed_buffers.Int8Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Int8Buffer.__proto__.new.call(this, _native_typed_data.NativeInt8List.new(initialLength));
;
}).prototype = typed_buffers.Int8Buffer.prototype;
dart.addTypeTests(typed_buffers.Int8Buffer);
dart.setMethodSignature(typed_buffers.Int8Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Int8Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Int8List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Int8Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Uint8ClampedBuffer = class Uint8ClampedBuffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeUint8ClampedList.new(size);
}
};
(typed_buffers.Uint8ClampedBuffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Uint8ClampedBuffer.__proto__.new.call(this, _native_typed_data.NativeUint8ClampedList.new(initialLength));
;
}).prototype = typed_buffers.Uint8ClampedBuffer.prototype;
dart.addTypeTests(typed_buffers.Uint8ClampedBuffer);
dart.setMethodSignature(typed_buffers.Uint8ClampedBuffer, () => ({
__proto__: dart.getMethods(typed_buffers.Uint8ClampedBuffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Uint8ClampedList, [core.int])
}));
dart.setLibraryUri(typed_buffers.Uint8ClampedBuffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Uint16Buffer = class Uint16Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeUint16List.new(size);
}
};
(typed_buffers.Uint16Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Uint16Buffer.__proto__.new.call(this, _native_typed_data.NativeUint16List.new(initialLength));
;
}).prototype = typed_buffers.Uint16Buffer.prototype;
dart.addTypeTests(typed_buffers.Uint16Buffer);
dart.setMethodSignature(typed_buffers.Uint16Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Uint16Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Uint16List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Uint16Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Int16Buffer = class Int16Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeInt16List.new(size);
}
};
(typed_buffers.Int16Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Int16Buffer.__proto__.new.call(this, _native_typed_data.NativeInt16List.new(initialLength));
;
}).prototype = typed_buffers.Int16Buffer.prototype;
dart.addTypeTests(typed_buffers.Int16Buffer);
dart.setMethodSignature(typed_buffers.Int16Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Int16Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Int16List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Int16Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Uint32Buffer = class Uint32Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeUint32List.new(size);
}
};
(typed_buffers.Uint32Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Uint32Buffer.__proto__.new.call(this, _native_typed_data.NativeUint32List.new(initialLength));
;
}).prototype = typed_buffers.Uint32Buffer.prototype;
dart.addTypeTests(typed_buffers.Uint32Buffer);
dart.setMethodSignature(typed_buffers.Uint32Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Uint32Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Uint32List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Uint32Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Int32Buffer = class Int32Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeInt32List.new(size);
}
};
(typed_buffers.Int32Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Int32Buffer.__proto__.new.call(this, _native_typed_data.NativeInt32List.new(initialLength));
;
}).prototype = typed_buffers.Int32Buffer.prototype;
dart.addTypeTests(typed_buffers.Int32Buffer);
dart.setMethodSignature(typed_buffers.Int32Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Int32Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Int32List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Int32Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Uint64Buffer = class Uint64Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return typed_data.Uint64List.new(size);
}
};
(typed_buffers.Uint64Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Uint64Buffer.__proto__.new.call(this, typed_data.Uint64List.new(initialLength));
;
}).prototype = typed_buffers.Uint64Buffer.prototype;
dart.addTypeTests(typed_buffers.Uint64Buffer);
dart.setMethodSignature(typed_buffers.Uint64Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Uint64Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Uint64List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Uint64Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Int64Buffer = class Int64Buffer extends typed_buffers._IntBuffer {
[_createBuffer](size) {
return typed_data.Int64List.new(size);
}
};
(typed_buffers.Int64Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Int64Buffer.__proto__.new.call(this, typed_data.Int64List.new(initialLength));
;
}).prototype = typed_buffers.Int64Buffer.prototype;
dart.addTypeTests(typed_buffers.Int64Buffer);
dart.setMethodSignature(typed_buffers.Int64Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Int64Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Int64List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Int64Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Float32Buffer = class Float32Buffer extends typed_buffers._FloatBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeFloat32List.new(size);
}
};
(typed_buffers.Float32Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Float32Buffer.__proto__.new.call(this, _native_typed_data.NativeFloat32List.new(initialLength));
;
}).prototype = typed_buffers.Float32Buffer.prototype;
dart.addTypeTests(typed_buffers.Float32Buffer);
dart.setMethodSignature(typed_buffers.Float32Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Float32Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Float32List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Float32Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Float64Buffer = class Float64Buffer extends typed_buffers._FloatBuffer {
[_createBuffer](size) {
return _native_typed_data.NativeFloat64List.new(size);
}
};
(typed_buffers.Float64Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Float64Buffer.__proto__.new.call(this, _native_typed_data.NativeFloat64List.new(initialLength));
;
}).prototype = typed_buffers.Float64Buffer.prototype;
dart.addTypeTests(typed_buffers.Float64Buffer);
dart.setMethodSignature(typed_buffers.Float64Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Float64Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Float64List, [core.int])
}));
dart.setLibraryUri(typed_buffers.Float64Buffer, "package:typed_data/typed_buffers.dart");
typed_buffers.Int32x4Buffer = class Int32x4Buffer extends typed_buffers._TypedDataBuffer$(typed_data.Int32x4) {
get [_defaultValue]() {
return typed_buffers.Int32x4Buffer._zero;
}
[_createBuffer](size) {
return new _native_typed_data.NativeInt32x4List.new(size);
}
};
(typed_buffers.Int32x4Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Int32x4Buffer.__proto__.new.call(this, new _native_typed_data.NativeInt32x4List.new(initialLength));
;
}).prototype = typed_buffers.Int32x4Buffer.prototype;
dart.addTypeTests(typed_buffers.Int32x4Buffer);
dart.setMethodSignature(typed_buffers.Int32x4Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Int32x4Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Int32x4List, [core.int])
}));
dart.setGetterSignature(typed_buffers.Int32x4Buffer, () => ({
__proto__: dart.getGetters(typed_buffers.Int32x4Buffer.__proto__),
[_defaultValue]: typed_data.Int32x4
}));
dart.setLibraryUri(typed_buffers.Int32x4Buffer, "package:typed_data/typed_buffers.dart");
dart.defineLazy(typed_buffers.Int32x4Buffer, {
/*typed_buffers.Int32x4Buffer._zero*/get _zero() {
return new _native_typed_data.NativeInt32x4.new(0, 0, 0, 0);
},
set _zero(_) {}
});
typed_buffers.Float32x4Buffer = class Float32x4Buffer extends typed_buffers._TypedDataBuffer$(typed_data.Float32x4) {
get [_defaultValue]() {
return new _native_typed_data.NativeFloat32x4.zero();
}
[_createBuffer](size) {
return new _native_typed_data.NativeFloat32x4List.new(size);
}
};
(typed_buffers.Float32x4Buffer.new = function(initialLength) {
if (initialLength === void 0) initialLength = 0;
typed_buffers.Float32x4Buffer.__proto__.new.call(this, new _native_typed_data.NativeFloat32x4List.new(initialLength));
;
}).prototype = typed_buffers.Float32x4Buffer.prototype;
dart.addTypeTests(typed_buffers.Float32x4Buffer);
dart.setMethodSignature(typed_buffers.Float32x4Buffer, () => ({
__proto__: dart.getMethods(typed_buffers.Float32x4Buffer.__proto__),
[_createBuffer]: dart.fnType(typed_data.Float32x4List, [core.int])
}));
dart.setGetterSignature(typed_buffers.Float32x4Buffer, () => ({
__proto__: dart.getGetters(typed_buffers.Float32x4Buffer.__proto__),
[_defaultValue]: typed_data.Float32x4
}));
dart.setLibraryUri(typed_buffers.Float32x4Buffer, "package:typed_data/typed_buffers.dart");
dart.trackLibraries("packages/typed_data/typed_buffers", {
"package:typed_data/typed_buffers.dart": typed_buffers
}, {
}, '{"version":3,"sourceRoot":"","sources":["typed_buffers.dart"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BgC,cAAQ,yBAAR;MAAoB;;AAShC;MAAO;WACP;AAChB,YAAU,aAAN,KAAK,kBAAI,cAAQ,AAAuC,WAA7B,wBAAiB,KAAK,EAAE;AACvD,cAAO,AAAO,sBAAC,KAAK;MACtB;WAEsB;YAAS;;AAC7B,YAAU,aAAN,KAAK,kBAAI,cAAQ,AAAuC,WAA7B,wBAAiB,KAAK,EAAE;AACjC,QAAtB,AAAO,qBAAC,KAAK,EAAI,KAAK;;MACxB;iBAEoB;AAClB,YAAc,aAAV,SAAS,iBAAG;AACZ,6BAAe;AACjB,mBAAS,IAAI,SAAS,EAAI,aAAF,CAAC,iBAAG,gBAAS,IAAC,aAAD,CAAC;AACX,YAAzB,AAAO,qBAAC,CAAC,EAAI,YAAY;;cAEtB,KAAc,aAAV,SAAS,iBAAG,AAAQ;AACrB;AACR,cAAI,AAAQ,AAAO,2BAAG;AACgB,YAApC,YAAY,oBAAc,SAAS;;AAEO,YAA1C,YAAY,0BAAoB,SAAS;;AAEJ,UAAvC,AAAU,SAAD,YAAU,GAAG,eAAS;AACZ,UAAnB,gBAAU,SAAS;;AAEF,QAAnB,gBAAU,SAAS;MACrB;aAEY;;AACV,YAAI,AAAQ,iBAAG,AAAQ,wBAAQ,AAAc,YAAR;AACX,QAA1B,AAAO,sBAAQ,oBAAP,mCAAO,QAAM,KAAK;MAC5B;UAKW;;AACE,QAAX,WAAK,KAAK;MACZ;aAWwB,QAAa,OAAe;;;;AACP,QAAhC,iCAAiB,KAAK,EAAE;AACnC,YAAI,GAAG,IAAI,QAAc,aAAN,KAAK,iBAAG,GAAG;AACuB,UAAnD,WAAU,0BAAiB,GAAG,EAAE,KAAK,EAAE,MAAM;;AAGpB,QAA3B,cAAQ,MAAM,EAAE,KAAK,EAAE,GAAG;MAC5B;gBAWmB,OAAmB,QAAa,OAAe;;;;;AACH,QAAlD,gCAAgB,KAAK,EAAE,MAAM,SAAiB,aAAR,iBAAU;AAChB,QAAhC,iCAAiB,KAAK,EAAE;AACnC,YAAI,GAAG,IAAI;AACT,cAAU,aAAN,KAAK,iBAAG,GAAG;AACsC,YAAnD,WAAU,0BAAiB,GAAG,EAAE,KAAK,EAAE,MAAM;;AAE/C,cAAI,AAAM,KAAD,IAAI,GAAG,EAAE;;AAOpB,YAAI,AAAM,KAAD,IAAI;AACgB,UAA3B,cAAQ,MAAM,EAAE,KAAK,EAAE,GAAG;AAC1B;;AAGF,YAAI,AAAI,GAAD,IAAI,QAAe,aAAP,MAAM;AACJ,UAAnB,MAAM,AAAO,MAAD;;AAEd,YAAI,GAAG,IAAI;AACoC,UAA7C,yBAAmB,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG;AAC5C;;AAKE,yBAAa;AACb,wBAAY,KAAK;AACrB,iBAAS,QAAS,OAAM;AACtB,cAAc,aAAV,SAAS,IAAG;AACH,YAAX,YAAS,aAAT,SAAS;AACT;;AAEF,cAAI,AAAW,UAAD,IAAI,AAAQ;AACP,YAAjB,YAAM,UAAU;;AAEW,UAA7B,AAAO,sBAAW,KAAV,UAAU,0CAAM,KAAK;;AAG/B,YAAc,aAAV,SAAS,IAAG;AAC0B,UAAxC,WAAU,wBAAW;;AAEvB,YAAI,GAAG,IAAI,QAAmB,aAAX,UAAU,iBAAG,GAAG;AACwB,UAAzD,WAAU,0BAAiB,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE;;AAIpB,QAAjC,wCAAS,eAAS,KAAK,EAAE;AACa,QAAtC,wCAAS,eAAS,eAAS,UAAU;AACD,QAApC,wCAAS,eAAS,KAAK,EAAE,UAAU;AACf,QAApB,gBAAU,UAAU;AACpB;MACF;sBAG0B,QAAY,OAAW;AAC1C,QAAL,MAAG,aAAH,GAAG;AACH,eAAa,aAAN,KAAK,iBAAG,GAAG;AACZ,sBAAQ,AAAM,MAAA,QAAC,KAAK;AACpB,qBAAO,AAAM,MAAA,QAAC,GAAG;AACF,UAAnB,AAAM,MAAA,QAAC,GAAG,EAAI,KAAK;AACC,UAApB,AAAM,MAAA,QAAC,KAAK,EAAI,IAAI;AACb,UAAP,QAAK,aAAL,KAAK;AACA,UAAL,MAAG,aAAH,GAAG;;MAEP;gBAOyB,QAAa,OAAe;;;AACnD,YAAW,aAAP,MAAM,GAAU,AAAI,AAAiB,GAAlB,IAAC,OAAJ,MAAQ,AAAO,MAAD,YAAV;AAKxB,YAAI,GAAG,IAAI;AACsC,UAA/C,yBAAmB,eAAS,MAAM,EAAE,KAAK,EAAE,GAAG;AAC9C;;AAIE,gBAAI;AACR,iBAAS,QAAS,OAAM;AACtB,cAAI,AAAE,CAAD,iBAAI,KAAK,GAAE,AAAU,SAAN,KAAK;AACtB,UAAH,IAAA,AAAC,CAAA;;AAEH,YAAI,AAAE,CAAD,gBAAG,KAAK,GAAE,AAAwC,WAA9B,wBAAW;MACtC;2BAG4B,OAAmB,QAAY,OAAW;AACpE,YAAW,aAAP,MAAM;AACa,UAArB,AAAI,GAAD,IAAC,OAAJ,MAAQ,AAAO,MAAD,YAAV;AACJ,cAAU,aAAN,KAAK,iBAAG,AAAO,MAAD,cAAe,aAAJ,GAAG,iBAAG,AAAO,MAAD;AACC,YAAxC,WAAU,wBAAW;;;AAGvB,gBAAO,AAAI,GAAD,IAAI;;AAGZ,2BAAmB,aAAJ,GAAG,iBAAG,KAAK;AAC1B,wBAAoB,aAAR,iBAAU,YAAY;AACZ,QAA1B,sBAAgB,SAAS;AAGwC,QADjE,AAAQ,yBACE,aAAN,KAAK,IAAG,YAAY,EAAU,aAAR,iBAAU,YAAY,EAAE,eAAS,KAAK;AACJ,QAA5D,AAAQ,yBAAS,KAAK,EAAQ,aAAN,KAAK,IAAG,YAAY,EAAE,MAAM,EAAE,KAAK;AACxC,QAAnB,gBAAU,SAAS;MACrB;aAEgB,OAAS;;AACvB,YAAU,aAAN,KAAK,IAAG,KAAW,aAAN,KAAK,iBAAG;AACsB,UAA7C,WAAU,0BAAiB,KAAK,EAAE,GAAG;;AAEvC,YAAY,aAAR,8BAAU,AAAQ;AACoC,UAAxD,AAAQ,yBAAe,aAAN,KAAK,IAAG,GAAW,aAAR,iBAAU,GAAG,eAAS,KAAK;AAC/B,UAAxB,AAAO,qBAAC,KAAK,EAAI,OAAO;AACf,UAAT,gBAAO,aAAP,iBAAO;AACP;;AAEM,wBAAY,0BAAoB;AACH,QAArC,AAAU,SAAD,YAAU,GAAG,KAAK,EAAE;AAC6B,QAA1D,AAAU,SAAD,YAAgB,aAAN,KAAK,IAAG,GAAW,aAAR,iBAAU,GAAG,eAAS,KAAK;AAC/B,QAA1B,AAAS,SAAA,QAAC,KAAK,EAAI,OAAO;AACjB,QAAT,gBAAO,aAAP,iBAAO;AACY,QAAnB,gBAAU,SAAS;MACrB;wBAKyB;AACvB,YAAqB,aAAjB,gBAAgB,kBAAI,AAAQ,yBAAQ;AACpC,wBAAY,0BAAoB,gBAAgB;AACb,QAAvC,AAAU,SAAD,YAAU,GAAG,eAAS;AACZ,QAAnB,gBAAU,SAAS;MACrB;4BAQgC;AAC1B,wBAA2B,aAAf,AAAQ,0BAAS;AACjC,YAAI,gBAAgB,IAAI,QAAkB,aAAV,SAAS,iBAAG,gBAAgB;AAC9B,UAA5B,YAAY,gBAAgB;cACvB,KAAc,aAAV,SAAS;AACQ,UAA1B;;AAEF,cAAO,qBAAc,SAAS;MAChC;cAKe;;AACoD,QAAjE,sBAAU,0BAAoB,OAAO,cAAS,GAAG,MAAM,EAAE;MAC3D;eAEkB,OAAW,KAAiB,QAAa;;;AACzD,YAAQ,aAAJ,GAAG,iBAAG,gBAAS,AAA2C,WAAjC,0BAAiB,GAAG,EAAE,GAAG;AACd,QAAxC,gBAAU,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,SAAS;MACzC;kBAGmB,OAAW,KAAiB,QAAY;AACzD,YAAW,yBAAP,MAAM;AAC+C,UAAvD,AAAQ,yBAAS,KAAK,EAAE,GAAG,EAAE,AAAO,MAAD,WAAU,SAAS;;AAEP,UAA/C,AAAQ,yBAAS,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,SAAS;;MAElD;;AAI8B,cAAA,AAAa;MAAkB;;AAEpC,cAAQ,cAAR,8BAAU,AAAa;MAAkB;;AAEzC,cAAA,AAAa;MAAa;;AAQ1B,cAAA,AAAa;MAAM;;qCA5QnB;MACN,gBAAE,MAAM;MACR,gBAAE,AAAO,MAAD;;IAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAhBjB,6CAAc;;;;;;;AAySN;IAAC;;2CAFL;AAAU,sDAAM,MAAM;;EAAC;;;;;;;;;AAQhB;IAAG;;6CAFL;AAAU,wDAAM,MAAM;;EAAC;;;;;;;;oBAOrB;AAAS,YAAI,wCAAU,IAAI;IAAC;;4CADvC;;AAAsB,uDAAU,uCAAU,aAAa;;EAAE;;;;;;;;oBAM/C;AAAS,YAAI,uCAAS,IAAI;IAAC;;2CADtC;;AAAsB,sDAAU,sCAAS,aAAa;;EAAE;;;;;;;;oBAOrC;AAAS,YAAI,+CAAiB,IAAI;IAAC;;mDAF9C;;AAClB,8DAAU,8CAAiB,aAAa;;EAAE;;;;;;;;oBAMnB;AAAS,YAAI,yCAAW,IAAI;IAAC;;6CADxC;;AAAsB,wDAAU,wCAAW,aAAa;;EAAE;;;;;;;;oBAMhD;AAAS,YAAI,wCAAU,IAAI;IAAC;;4CADvC;;AAAsB,uDAAU,uCAAU,aAAa;;EAAE;;;;;;;;oBAM7C;AAAS,YAAI,yCAAW,IAAI;IAAC;;6CADxC;;AAAsB,wDAAU,wCAAW,aAAa;;EAAE;;;;;;;;oBAMhD;AAAS,YAAI,wCAAU,IAAI;IAAC;;4CADvC;;AAAsB,uDAAU,uCAAU,aAAa;;EAAE;;;;;;;;oBAM7C;AAAS,YAAI,2BAAW,IAAI;IAAC;;6CADxC;;AAAsB,wDAAU,0BAAW,aAAa;;EAAE;;;;;;;;oBAMhD;AAAS,YAAI,0BAAU,IAAI;IAAC;;4CADvC;;AAAsB,uDAAU,yBAAU,aAAa;;EAAE;;;;;;;;oBAO5C;AAAS,YAAI,0CAAY,IAAI;IAAC;;8CAFzC;;AACb,yDAAU,yCAAY,aAAa;;EAAE;;;;;;;;oBAOb;AAAS,YAAI,0CAAY,IAAI;IAAC;;8CAFzC;;AACb,yDAAU,yCAAY,aAAa;;EAAE;;;;;;;;;AAQd;IAAK;oBACJ;AAAS,YAAI,8CAAY,IAAI;IAAC;;8CAHzC;;AACb,yDAAU,6CAAY,aAAa;;EAAE;;;;;;;;;;;;MAF5B,iCAAK;YAAO,0CAAQ,GAAG,GAAG,GAAG;;;;;;AAUb,YAAI;IAAgB;oBACnB;AAAS,YAAI,gDAAc,IAAI;IAAC;;gDAH3C;;AACf,2DAAU,+CAAc,aAAa;;EAAE","file":"typed_buffers.ddc.js"}');
// Exports:
return {
typed_buffers: typed_buffers
};
});
//# sourceMappingURL=typed_buffers.ddc.js.map
|
import Env from './env'
let config = {
env: Env,
'development': {
'WEIBO_AUTH_URL': 'http://127.0.0.1:8080/api/auth/loginTest',
'domain': '127.0.0.1',
'QQ_AUTH_URL': 'http://127.0.0.1:8080/api/auth/loginTest',
env: Env
},
'production': {
'WEIBO_AUTH_URL': 'https://api.weibo.com/oauth2/authorize?client_id=1078042542&redirect_uri=https://gunxueqiu.site/api/auth/weibo/callback',
'domain': '.gunxueqiu.site',
'QQ_AUTH_URL': 'https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=1109532005&redirect_uri=https://gunxueqiu.site/api/auth/qq/callback',
env: Env
}
}[Env]
export default config
|
'use strict';
const UNIX_EPOCH = 'Thu, 01 Jan 1970 00:00:00 GMT';
const COOKIE_EXPIRE = 'Fri, 01 Jan 2100 00:00:00 GMT';
const COOKIE_DELETE = `=deleted; Expires=${UNIX_EPOCH}; Path=/; Domain=`;
const DEFAULT_ACCESS = {
guests: true, // allow access for non-authenticated connections
logged: true, // allow access for authenticated connections
http: true, // allow via HTTP
https: true, // allow via HTTPS
intro: false, // allow API introspection
virtual: false, // allow virtual folders if true or reply 404 if false
groups: [] // allow access for certain groups (empty list allows to all)
};
const STATUS_CODES = api.http.STATUS_CODES;
if (!STATUS_CODES[508]) STATUS_CODES[508] = 'Loop Detected';
const DEFAULT_SLOW_TIME = api.common.duration('2s');
// HTTP Client interface for Impress Application Server
// Properties:
// startTime <Date> client's creation time
// req <http.IncomingMessage>
// res <http.ServerResponse>
// websocket <Object> | <null> initialized
// while processing a websocket request
// socket <net.Socket> socket associated with the connection
// server <Object> server instance
// application <Application> instance of <Application>
// dynamicHandler <boolean> whether client has been dispatched, default: false
// query <Object> collection of key and value pairs from url query
// schema <string> `https` if server's transport is `tls`, otherwise - `http`
// method <string> the request method in lowercase
// access <Object> client access options
// fields <Object> parsed client data according to request content-type
// files <Object> file uploads object, where the property names
// are field names and the values are arrays of file objects
// slowTime <number> client slow time in milliseconds
// timedOut <boolean> whether the client hasn't been finished
// before server timeout, default: `false`
// finished <boolean> end response flag, default: `false`
// url <string> the path portion of the request url
// host <string> request host without port
// path <string> the path portion of the request url
// with trailing slash at the end if there isn't one
// pathDir <string> absolute path to path in request url
// in application's `www` directory
// (e.g. `/ias/applications/example/www/path/to/dir`)
// realPath <string> path to the nearest existent folder
// realPathDir <string> absolute path to the nearest existent folder
// in application's `www` directory
// execPath <string> path to the nearest directory
// execPathDir <string> absolute path to the nearest directory
// with handler script file for the request
// in application's `www` directory
// ext <string> extension of file in the path portion of the request url
// typeExt <string> extension type of returned data
// data <string> data received from client
// context <Object> client context
// ip <string> | <undefined> remote IP address
// cookies <Object> received cookies
// preparedCookies <string[]> prepared cookies to send
// ipInt <number> | <undefined> remote IP address converted to number,
// if no IP address - `undefined`
// local <boolean> local network interface flag
// session <Session> | <null> client session
// sessionCreated <boolean> session creation flag, default: `false`
// sessionModified <boolean> session modification flag, default: `false`
// logged <boolean> whether the user is logged in, default: `false`
// currentHandler <string> current handler name
// (e.g. `access`, `get`, `post` etc.)
class Client {
// Client constructor
// application <Application> instance of impress.Application
// req <http.IncomingMessage>
// res <http.ServerResponse>
constructor(application, req, res) {
const socket = req.socket || req.connection.socket;
const server = impress.server;
const url = api.url.parse(req.url);
const config = server.config;
req.connection.client = this;
this.startTime = Date.now();
this.req = req;
this.res = res;
this.websocket = null;
this.socket = socket;
this.server = server;
this.application = application;
this.dynamicHandler = false;
this.query = api.querystring.parse(url.query);
this.schema = config.transport === 'tls' ? 'https' : 'http';
this.method = req.method.toLowerCase();
this.access = { ...DEFAULT_ACCESS };
this.calculateAccess();
this.fields = null;
this.files = null;
this.slowTime = config.slowTime || DEFAULT_SLOW_TIME;
this.timedOut = false;
this.finished = false;
this.url = url.pathname;
this.host = api.common.parseHost(req.headers.host);
this.path = api.common.addTrailingSlash(this.url);
this.pathDir = api.path.join(application.dir, 'www', this.path);
this.realPath = this.path;
this.realPathDir = this.pathDir;
this.execPath = this.path;
this.execPathDir = this.pathDir;
this.ext = api.common.fileExt(this.path);
this.typeExt = this.ext || 'html';
this.data = '';
this.context = {};
this.chunks = [];
this.ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
socket.remoteAddress;
this.cookies = {};
this.preparedCookies = [];
if (res.setHeader) {
const contentType = impress.MIME_TYPES[this.typeExt];
if (contentType) res.setHeader('Content-Type', contentType);
res.setHeader('Cache-Control', 'public');
const timeout = Math.round(server.keepAlive / 1000);
res.setHeader('Keep-Alive', 'timeout=' + timeout);
}
if (this.ip) {
const ip = api.net.isIPv6(this.ip) ? this.ip.slice(7) : this.ip;
this.ipInt = api.common.ipToInt(ip);
application.emit('clientConnect', this);
this.local = api.common.localIPs().includes(this.ip);
} else {
this.ipInt = undefined;
this.local = false;
}
this.session = null;
this.sessionCreated = false;
this.sessionModified = false;
this.logged = false;
this.currentHandler = undefined;
// Socket leak workaround
res.on('finish', () => {
application.emit('clientDisconnect', this);
socket.removeAllListeners('timeout');
socket.setTimeout(server.keepAlive, () => {
socket.destroy();
});
});
}
// Convert cookie string from request's headers to `client.cookies` object
//
// Example: 'name=value; path=/' => { name: 'value', path: '/' }
parseCookies() {
const cookie = this.req.headers.cookie;
if (cookie) {
const cookies = cookie.split(';');
for (const item of cookies) {
const parts = item.split('=');
const key = parts[0].trim();
const val = parts[1] || '';
this.cookies[key] = val.trim();
}
}
}
// Set cookie by adding it to `client.preparedCookies`
// name <string> cookie name
// value <string> cookie value
// host <string> host name, optional, default: client.req.headers.host
// httpOnly <boolean> HttpOnly cookie modifier, optional, default: true
setCookie(name, value, hostname, httpOnly = true) {
const expires = `expires=${COOKIE_EXPIRE}`;
const hostport = hostname || this.req.headers.host;
const pos = hostport.indexOf(':');
const host = pos > -1 ? hostport.substring(0, pos) : hostport;
let cookie = `${name}=${value}; ${expires}; Path=/; Domain=${host}`;
if (httpOnly) cookie += '; HttpOnly';
this.preparedCookies.push(cookie);
}
// Delete cookie
// name <string> cookie name
// host <string> optional, default: client.req.headers.host
deleteCookie(name, host) {
let aHost = host || this.req.headers.host;
if (api.net.isIP(aHost) === 0) aHost = '.' + aHost;
this.preparedCookies.push(name + COOKIE_DELETE + aHost);
}
// Set all prepared cookies if headers have not been sent yet
sendCookie() {
const prepared = this.preparedCookies;
if (prepared && !this.res.headersSent) {
this.res.setHeader('Set-Cookie', prepared);
}
}
// Route request to external HTTP server
// hostname <string> forward request to host name or IP address
// port <number> request port
// path <string> request path
proxy(hostname, port, path) {
const target = { hostname, port, path, method: this.req.method };
const req = api.http.request(target, response => {
this.res.writeHead(response.statusCode, response.headers);
response.on('data', chunk => {
this.res.write(chunk);
});
response.on('end', () => {
this.end();
});
});
req.on('error', err => {
this.application.log.error(`Error proxying request: ${err.message}`);
});
req.end();
impress.stat.res++;
}
// Client dispatch.
// Check application firewall access, in case if access is allowed
// parse cookies, restore client session and process request.
// Otherwise following status codes can be sent:
// - `403 Forbidden` client error status response code if access denied
// - `429 Too Many Requests` response status code if access limited
// - `400 Bad Request` response status code in other cases
dispatch() {
this.dynamicHandler = true;
this.parseCookies();
// TODO: Temporary disable application firewall
// to refactor security subsystem and sessions
// const code = api.firewall.check(this);
// if (code === api.firewall.ACCESS_ALLOWED) {
this.application.security.restoreSession(this, () => {
this.detectRealPath(() => {
this.processing();
});
});
// } else if (code === api.firewall.ACCESS_DENIED) {
// this.error(403);
// } else if (code === api.firewall.ACCESS_LIMITED) {
// this.error(429);
// } else {
// this.error(400);
// }
}
// Add current client to deny list by IP and Token if session exists.
// Send `403 Forbidden` client error status response code afterwards
// msec <number> | <string> milliseconds or duration of client blocking
block(/*msec*/) {
this.error(403);
// TODO: Temporary disable application firewall
// to refactor security subsystem and sessions
// const duration = api.common.duration(msec) || 0;
// api.firewall.ip.deny(this.ipInt, duration);
// if (this.session) {
// api.firewall.token.deny(this.session.token, duration);
// }
}
// Process request.
// If requested page is already cached, send it and end response.
// Otherwise check client access and execute an appropriate
// handler file for request's method, end response accordingly
processing() {
const cache = this.application.cache.pages[this.realPath];
if (cache && this.startTime < cache.expireTime) {
this.sendCache(cache);
return;
}
if (!this.ext) {
this.ext = api.common.fileExt(this.realPath);
this.typeExt = this.ext || 'html';
}
this.defaultContentType();
if (this.ext === 'ws') {
api.websocket.initialize(this);
}
this.fileHandler('access', false, () => {
if (!this.access.allowed) {
this.error(403);
return;
}
if (this.path !== this.realPath && !this.access.virtual) {
this.error(404);
return;
}
this.execPath = this.realPath;
this.execPathDir = this.realPathDir;
this.fileHandler(this.method, false, err => {
if (this.finished) return;
if (err) {
this.error(404);
return;
}
if (this.access.auth && !this.local) {
this.basicAuth();
return;
}
if (this.ext === '' && this.access.intro) {
this.introspect();
return;
}
const ext = impress.extensions;
const extCase = ext[this.typeExt] || ext.html;
extCase(this);
});
});
}
// Handle basic access authentication.
// Check authorization base64 encoded credentials if
// client request contains `Authorization` header.
// In case check failed or `Authorization` header has not been set,
// send `401 Unauthorized` client error status response code along
// with `WWW-Authenticate` header.
// As long as base64 is a reversible encoding, the basic authentication
// is not secure, so HTTPS/TLS should be used in combination
// with basic authentication for additional security.
basicAuth() {
let authBase64 = this.req.headers.authorization;
let authAllowed = false;
if (authBase64) {
authBase64 = authBase64.substring(6);
const auth = Buffer.from(authBase64, 'base64');
authAllowed = this.access.auth === auth.toString();
}
if (!authAllowed) {
const realm = this.access.realm || 'Restricted';
this.res.setHeader('WWW-Authenticate', `Basic realm="${realm}"`);
this.error(401);
}
}
// Specify an allowed origin.
// Set `Access-Control-Allow-Origin` header
// if application config defines allowOrigin, default: not set
allowOrigin() {
const config = this.application.config.sections.application;
if (config) {
const origin = config.allowOrigin;
if (origin) {
const headers = 'origin, content-type, accept';
this.res.setHeader('Access-Control-Allow-Origin', origin);
this.res.setHeader('Access-Control-Allow-Headers', headers);
}
}
}
// Set `Content-Type` header with an appropriate MIME type of returned data
defaultContentType() {
const contentType = impress.MIME_TYPES[this.typeExt];
if (contentType) {
this.res.setHeader('Content-Type', contentType);
}
this.allowOrigin();
}
// Process HTML page by sending html template and ending response.
// If cannot read template file, `500 Internal Server Error`
// server error response code is sent
processingPage() {
this.execPath = this.realPath;
this.execPathDir = this.realPathDir;
this.template('html', (err, tpl) => {
if (err) {
this.error(500);
return;
}
this.end(tpl);
});
}
// Cache URL response
// timeout <number> | <string> milliseconds or duration
cache(timeout) {
this.context.cache = api.common.duration(timeout);
}
// End response
// output <string> | <Buffer> | <Object>
// stats <fs.Stats> instance of fs.Stats
// compressed <boolean> gzip compression flag
// data <Buffer> to send
end(output) {
if (this.finished) return;
this.finished = true;
const isString = typeof output === 'string';
const isBuffer = Buffer.isBuffer(output);
const isUndef = output === undefined;
const cache = isString || isBuffer || isUndef ? { data: output } : output;
const length = cache && cache.data ? cache.data.length : 0;
const done = () => {
const res = this.res;
this.sendCookie();
if (!res.headersSent) {
if (cache.stats) {
res.setHeader('Content-Length', cache.stats.size);
res.setHeader('Last-Modified', cache.stats.mtime.toUTCString());
}
if (cache.compressed) res.setHeader('Content-Encoding', 'gzip');
}
if (isString && length > impress.COMPRESS_ABOVE) {
if (res.headersSent) {
res.end();
return;
}
api.zlib.gzip(cache.data, (err, data) => {
if (err) {
this.error(500);
return;
}
res.setHeader('Content-Encoding', 'gzip');
res.setHeader('Content-Length', data.length);
res.end(data);
if (this.context && this.context.cache) this.saveCache(data);
});
} else {
res.end(cache.data);
if (this.context && this.context.cache) this.saveCache(cache.data);
}
impress.accessLog(this);
impress.stat.res++;
};
// TODO: impress.application
if (this.application === impress) {
done();
return;
}
this.application.security.saveSession(this, done);
}
// Save cache in `client.application.cache.pages`
// data <string>
saveCache(data) {
const now = new Date();
const mtime = now.getTime();
const time = now.toUTCString();
this.application.cache.pages[this.realPath] = {
expireTime: this.startTime + this.context.cache,
statusCode: this.res.statusCode,
contentType: this.res.getHeader('content-type'),
contentEncoding: this.res.getHeader('content-encoding'),
stats: { size: data.length, mtime, time },
data,
};
}
// Send cache data. Set appropriate headers and end response
// cache <Object>
// expireTime <number> cache expiration time
// statusCode <number> response status code
// contentType <string> data type, `Content-Type` header
// contentEncoding <string> data encoding, `Content-Encoding` header
// stats <Object>
// size <number> data length, `Content-Length` header
// mtime <number> | <BigInt> last modified in milliseconds
// time <string> `Last-Modified` header
// data <string>
sendCache(cache) {
const res = this.res;
res.statusCode = cache.statusCode;
const { contentType, contentEncoding, stats } = cache;
if (contentType) {
res.setHeader('Content-Type', contentType);
}
if (contentEncoding) {
res.setHeader('Content-Encoding', contentEncoding);
}
if (stats) {
res.setHeader('Content-Length', stats.size);
res.setHeader('Last-Modified', stats.time);
}
this.end(cache.data);
}
// End response with HTTP error code
// code <number> HTTP status code
// message <string> error message, optional
error(code, message = STATUS_CODES[code]) {
this.res.statusCode = code;
if (this.typeExt === 'json') {
this.end(`{"statusCode":${code},"message":"${message}"}`);
return;
}
if (!this.res.headersSent) {
this.res.setHeader('Content-Type', impress.MIME_TYPES.html);
}
const title = 'Error ' + code;
const template = impress.systemTemplates.error;
this.end(template(title, message));
}
// Redirect to specified location.
// `Location` header would be set in case headers have not sent yet.
// location <string> URL to redirect a page to
redirect(location) {
if (!this.res.headersSent) {
this.res.setHeader('Location', location);
this.res.statusCode = 302;
}
}
// Inherit behavior from parent directory
// callback <Function> after inherited handler
// err <Error>
inherited(callback) {
if (this.execPath === '/') {
callback(new Error('Handler is not found'));
return;
}
const path = api.common.dirname(this.execPath) + '/';
this.execPath = path;
this.execPathDir = api.path.join(this.application.dir, 'www', path);
this.fileHandler(this.currentHandler, true, callback);
}
// Execute handler script file for the request.
// Run an appropriate handler file for request method(get, post, put,
// delete, patch, head) or access handler for access configuration.
// Files should be named in accordance to method it handles (e.g. `get.js`)
// handler <string> handler name (e.g. `access`, `get`, `post` etc.)
// inheritance <boolean> flag, true if called from inherited
// callback <Function> after fileHandler executed
// err <Error>
fileHandler(handler, inheritance, callback) {
const application = this.application;
const fileName = handler + '.js';
const filePath = this.execPathDir + fileName;
const relPath = application.relative(filePath);
const fileCache = application.cache.files.get(relPath);
if (!inheritance) this.currentHandler = handler;
if (fileCache) {
if (fileCache === impress.FILE_EXISTS) {
this.runScript(handler, filePath, callback);
} else if (this.execPath !== '/') {
this.execPath = api.common.dirname(this.execPath);
this.execPathDir = api.path.join(application.dir, 'www', this.execPath);
this.fileHandler(handler, inheritance, callback);
} else {
callback(new Error('Handler not found'));
}
return;
}
api.fs.access(filePath, err => {
if (!err) {
application.cache.files.set(relPath, impress.FILE_EXISTS);
this.runScript(handler, filePath, callback);
application.cache.watch(api.path.dirname(relPath));
return;
}
application.cache.files.set(relPath, impress.FILE_NOT_FOUND);
if (this.execPath !== '/') {
this.execPath = api.common.dirname(this.execPath);
this.execPathDir = api.path.join(application.dir, 'www', this.execPath);
this.fileHandler(handler, inheritance, callback);
application.cache.watch('/www' + this.execPath);
return;
}
application.cache.watch(api.path.dirname(relPath));
callback(new Error('Handler not found'));
});
}
// Find nearest existent folder
// callback <Function> after path detected
detectRealPath(callback) {
const application = this.application;
const relPath = application.relative(this.realPathDir);
const folderCache = application.cache.folders.get(relPath);
const detected = folderCache &&
folderCache !== impress.DIR_NOT_EXISTS ||
this.realPath === '/';
if (detected) {
callback();
return;
}
api.fs.access(this.realPathDir, err => {
if (err) {
application.cache.folders.set(relPath, impress.DIR_NOT_EXISTS);
this.realPath = api.common.dirname(this.realPath);
this.realPathDir = api.path.join(application.dir, 'www', this.realPath);
this.detectRealPath(callback);
} else {
application.cache.folders.set(relPath, impress.DIR_EXISTS);
callback();
}
});
application.cache.watch(api.common.stripTrailingSlash(relPath));
}
// Check whether access is allowed or not based on `client.access` options.
// Default access options:
// - guests, allow access for non-authenticated connections - `true`
// - logged, allow access for authenticated connections - `true`
// - http, allow via HTTP - `true`
// - https, allow via HTTPS - `true`
// - intro, allow API introspection - `false`
// - virtual, allow virtual folders otherwise reply with 404 - `false`
// - groups, allow access for certain groups, empty allows for all - `[]`
calculateAccess() {
this.access.allowed = (
(!this.logged && this.access.guests) ||
(!!this.logged && this.access.logged)) && (
(this.schema === 'http' && this.access.http) ||
(this.schema === 'https' && this.access.https));
if (this.logged) {
this.access.allowed = this.access.allowed &&
(!this.access.groups || (this.access.groups && (
this.access.groups.length === 0 ||
this.access.groups.includes(this.session.group) ||
this.access.groups.includes('local') && this.local
)));
}
}
// Run script in client context if access is allowed.
// Configure access options if `access`.
// Otherwise execute function from handler file
// handler <string> handler name
// fileName <string> file name
// callback <Function> after handler executed
// err <Error>
runScript(handler, fileName, callback) {
impress.createScript(this.application, fileName, (err, fn) => {
if (err) {
this.application.log.error(impress.CANT_READ_FILE + fileName);
callback(err);
return;
}
if (handler === 'access') {
Object.assign(this.access, fn);
this.calculateAccess();
callback(null);
return;
}
if (!this.access.allowed) {
callback(null);
return;
}
this.executeFunction(fn, callback);
});
}
// Execute function in client context
// fn <Function> to be executed
// callback <Function>
// err <Error>
executeFunction(fn, callback) {
const application = this.application;
if (typeof fn !== 'function') {
const err = new Error('Invalid handler');
this.error(500);
application.logException(err);
callback(err);
return;
}
let waiting = true;
const done = (err, result) => {
if (waiting) {
waiting = false;
if (result) this.context.data = result;
if (err) {
if (this.res.statusCode === 200) {
this.error(500);
}
application.logException(err);
callback(err);
return;
}
callback(null);
}
};
if (Object.prototype.toString.call(fn) === '[object AsyncFunction]') {
fn(this).then(result => {
done(null, result);
}, err => {
done(err);
});
return;
}
try {
fn(this, done);
} catch (err) {
done(err);
}
}
// Send static file and close connection
// onNotServed <Function> execute if file is not static
static(onNotServed) {
const basePath = '/static';
let relPath = '/static/index.html';
if (this.path !== '/') {
const url = api.querystring.unescape(this.url);
const safePath = api.path.posix.join(basePath, url);
if (safePath.startsWith(basePath)) relPath = safePath;
}
if (!this.staticCache(relPath, onNotServed)) {
this.serveStatic(relPath, onNotServed);
}
}
// Send static data from `client.application.cache.static`
// relPath <string> relative path is a cash index
// onNotServed <Function> if not served
staticCache(relPath, onNotServed) {
const cache = this.application.cache.static.get(relPath);
const isNum = typeof cache === 'number';
const cached = cache && !isNum;
if (cached) this.buffer(cache);
else if (isNum) onNotServed();
return cached;
}
// Serve static file
// relPath <string> application relative path to file
// onNotServed <Function> if not static
serveStatic(relPath, onNotServed) {
const application = this.application;
const gz = '.gz';
const filePath = application.dir + relPath;
const isCompressed = impress.COMPRESSED_EXT.includes(this.ext);
const serveFile = (err, stats) => {
if (err) {
onNotServed();
application.cache.watch(api.path.dirname(relPath));
return;
}
if (stats.isDirectory()) {
if (!this.staticCache(relPath, onNotServed)) {
this.index(filePath);
}
return;
}
const { cacheMaxFileSize } = application.config.sections.files;
if (stats.size < cacheMaxFileSize) this.compress(filePath, stats);
else this.stream(filePath, stats);
};
const serveGzip = (err, stats) => {
if (err) api.fs.stat(filePath, serveFile);
else this.staticFile(filePath + gz, relPath + gz, stats);
};
if (isCompressed) api.fs.stat(filePath, serveFile);
else api.fs.stat(filePath + gz, serveGzip);
}
// Send compressed static file and end response.
// If the file cannot be read `404 Not Found`
// client error status response code is sent
// filePath <string> absolute path to file
// relPath <string> application relative path to file
// stats <fs.Stats> instance of fs.Stats
staticFile(filePath, relPath, stats) {
api.fs.readFile(filePath, (err, data) => {
if (err) {
this.error(404);
return;
}
const cache = { stats, compressed: true, data };
this.end(cache);
this.application.cache.static.add(relPath, cache);
});
}
// Send static buffer and end response.
// If cache was not modified `304 Not Modified`
// client redirection response code is sent
// cache <Object>
// stats <fs.Stats> instance of fs.Stats
// compressed <boolean> gzip compression flag
// data <Buffer> to send
buffer(cache) {
const time = this.req.headers['if-modified-since'];
const notMod = time && api.common.isTimeEqual(time, cache.stats.mtime);
if (notMod) this.error(304);
else this.end(cache);
}
// Refresh static in memory cache with compression and minification.
// If cache was not modified, `304 Not Modified` client redirection
// response code is sent. If cannot read file, `404 Not Found` client error
// status response code is sent
// filePath <string> path to handler (from application base directory)
// stats <fs.Stats> instance of fs.Stats
compress(filePath, stats) {
const time = this.req.headers['if-modified-since'];
const notMod = time && api.common.isTimeEqual(time, stats.mtime);
if (notMod) {
this.error(304);
return;
}
this.application.compress(filePath, stats, (err, data, compressed) => {
if (err) {
this.error(404);
return;
}
this.end({ stats, compressed, data });
});
}
// File upload and download utilities for Impress Application Server
// Generate HTTP file attachment
// attachmentName <string> name to save downloaded file
// size <number> set Content-Length header, optional
// lastModified <string> set Last-Modified header, optional
attachment(attachmentName, size, lastModified) {
const res = this.res;
res.setHeader('Content-Description', 'File Transfer');
res.setHeader('Content-Type', 'application/x-download');
const fileName = `attachment; filename="${attachmentName}"`;
res.setHeader('Content-Disposition', fileName);
res.setHeader('Expires', 0);
const cacheControl = 'no-cache, no-store, max-age=0, must-revalidate';
res.setHeader('Cache-Control', cacheControl);
res.setHeader('Pragma', 'no-cache');
if (size) {
res.setHeader('Content-Length', size);
res.setHeader('Content-Transfer-Encoding', 'binary');
}
if (lastModified) res.setHeader('Last-Modified', lastModified);
}
// Download file generating a file attachment.
// If cannot read file, `404 Not Found`
// client error status response code is sent
// filePath <string> file to download
// attachmentName <string> name to save downloaded file,
// optional, default: basename of filePath
// callback <Function> after file downloaded
download(filePath, attachmentName, callback) {
if (typeof attachmentName === 'function') {
callback = attachmentName;
attachmentName = api.path.basename(filePath);
}
callback = api.common.once(callback);
const fail = () => {
this.application.log.error(impress.CANT_READ_FILE + filePath);
this.error(404);
callback();
};
const done = () => {
this.finished = true;
callback();
};
api.fs.stat(filePath, (err, stats) => {
if (err) {
fail();
return;
}
this.attachment(attachmentName, stats.size, stats.mtime.toUTCString());
const stream = api.fs.createReadStream(filePath);
stream.on('error', fail);
this.res.on('finish', done);
stream.pipe(this.res);
});
}
// Upload file
// each <Function> on processing each file
// err <Error>
// data <Object>
// compressionFlag <string> how file was compressed
// `N`(not compressed), `Z`(zip compressed), `G`(gzip compressed)
// originalName <string> filename
// storageName <string> generated key
// storagePath <string> storage path
// originalHash <string> hash
// originalSize <number> size of file in bytes
// storageSize <number> size of file in bytes
// callback <Function>
// err <Error>
// count <number> amount of files
upload(each, callback) {
if (!this.files) {
callback(null, 0);
return;
}
let fileCount = 0;
let count = 0;
const done = (err, data) => {
count++;
if (each) each(err, data);
if (fileCount === count) callback(null, count);
};
for (const fieldName in this.files) {
const field = this.files[fieldName];
for (const key in field) {
const file = field[key];
fileCount++;
impress.uploadFile(this.application, file, done);
}
}
}
// Sending file stream
// filePath <string> absolute path to file
// stats <fs.Stats> instance of fs.Stats
stream(filePath, stats) {
const res = this.res;
let stream;
const range = this.req.headers.range;
if (range) {
const index = range.indexOf('-');
const start = parseInt(range.slice('bytes='.length, index), 10);
const end = index === range.length - 1 ?
stats.size - 1 :
parseInt(range.slice(index + 1), 10);
const chunkSize = (end - start) + 1;
res.statusCode = 206;
res.setHeader('Content-Range', stats.size);
res.setHeader('Content-Length', chunkSize);
const cRange = `bytes ${start}-${end}/${stats.size}`;
res.setHeader('Content-Range', cRange);
res.setHeader('Accept-Ranges', 'bytes');
stream = api.fs.createReadStream(filePath, { start, end });
} else {
this.allowOrigin();
res.setHeader('Content-Length', stats.size);
res.setHeader('Last-Modified', stats.mtime.toUTCString());
stream = api.fs.createReadStream(filePath);
}
stream.on('open', () => {
stream.pipe(this.res);
});
stream.on('error', () => {
this.application.log.error(impress.CANT_READ_FILE + filePath);
});
}
// Send HTML template with directory index, end response.
// If in application's static files configuration `index` is set
// to `false` (allowed displaying HTTP directory index for /static if true)
// `403 Forbidden` client error status response code is sent
// indexPath <string> path to directory
index(indexPath) {
const application = this.application;
if (!this.url.endsWith('/')) {
this.redirect(this.path);
this.end();
return;
}
this.execPath = this.realPath;
this.execPathDir = this.realPathDir;
this.fileHandler('access', false, err => {
if (err || !application.config.sections.files.index) {
this.error(403);
return;
}
if (!this.res.headersSent) {
this.res.setHeader('Content-Type', impress.MIME_TYPES.html);
}
impress.dirIndex(
application, indexPath, this.realPath, (err, files, dirs) => {
const template = impress.systemTemplates.index;
const fileTpl = impress.systemTemplates.file;
const rows = files.map(
({ name, path, size, mtime }) => fileTpl(name, path, size, mtime)
).join('');
const items = dirs.map(
({ name, path }) => `<a href="/${path}">${name}</a>`
).join('/');
this.end(template('Directory index', this.url, rows, items));
}
);
});
}
// Send HTML template with API introspection index, end response.
// Called if in client access configuration `intro` is set to `true`.
// If cannot read directory by client.path, `404 Not Found` client error
// status response code is sent
introspect() {
if (!this.req.url.endsWith('/')) {
this.redirect(this.path);
this.end();
return;
}
const application = this.application;
const path = this.path;
impress.dirIntrospect(application, path, (err, files, dirs) => {
if (err) {
this.error(404);
return;
}
const template = impress.systemTemplates.introspection;
const fileTpl = impress.systemTemplates.file;
const rows = files.map(
({ name, path, method, mtime }) => fileTpl(name, path, method, mtime)
).join('');
const items = dirs.map(
({ name, path }) => `<a href="/${path}">${name}</a>`
).join('/');
this.end(template('API Introspection index', this.url, rows, items));
});
}
// Render template from file or return template from cache if it exists
// file <string> template file name
// callback <Function>
// err <Error>
// res <string> requested template
template(file, callback) {
const application = this.application;
const fileName = file + '.template';
const filePath = this.execPathDir + fileName;
const relPath = application.relative(filePath);
const fileCache = application.cache.templates.get(relPath);
if (fileCache) {
callback(null, fileCache);
return;
}
api.fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
application.log.error(impress.CANT_READ_FILE + filePath);
callback(err);
return;
}
const tpl = api.common.removeBOM(data);
application.cache.templates.add(relPath, tpl);
callback(null, tpl);
});
application.cache.watch(api.path.dirname(relPath));
}
}
impress.Client = Client;
module.exports = { Client };
|
const {
serialize,
deserialize
} = require('../../../../lib/serializers/numberSerializer')
describe('Number Serializer', () => {
it('should correct serialize and deserialize numbers', () => {
expect(deserialize(serialize(0))).to.be.eql(0)
expect(deserialize(serialize(1.1))).to.be.eql(1.1)
expect(deserialize(serialize(1.12345))).to.be.eql(1.12345)
expect(deserialize(serialize(10000.12345))).to.be.eql(10000.12345)
expect(deserialize(serialize(Number.MAX_SAFE_INTEGER))).to.be.eql(
Number.MAX_SAFE_INTEGER
)
expect(deserialize(serialize(Number.POSITIVE_INFINITY))).to.be.eql(
Number.POSITIVE_INFINITY
)
expect(deserialize(serialize(Number.NEGATIVE_INFINITY))).to.be.eql(
Number.NEGATIVE_INFINITY
)
})
})
|
ClassicEditor
.create( document.querySelector( '#description' ), {
language: 'pt-br',
// toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ]
} )
.then( editor => {
window.editor = editor;
} )
.catch( err => {
console.error( err.stack );
} );
|
var gulp = require('gulp');
var gutil = require('gulp-util');
var jade = require('gulp-jade');
var gulpLiveScript = require('gulp-livescript');
var sass = require('gulp-sass');
var paths = {
jade: ['./jade/**/*.jade'],
ls: ['./livescripts/**/*.ls'],
sass: ['./sass/**/*.sass']
};
gulp.task('default', ['jade', 'ls', 'sass']);
gulp.task('jade', function (done) {
gulp.src(paths.jade)
.pipe(jade({pretty: true}))
.pipe(gulp.dest('./www/'))
.on('end', done);
});
gulp.task('ls', function(done) {
gulp.src(paths.ls)
.pipe(gulpLiveScript( { bare: true } )
.on('error', gutil.log))
.pipe(gulp.dest('./www/js/'))
.on('end', done);
});
gulp.task('sass', function(done) {
gulp.src(paths.sass)
.pipe(sass())
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
gulp.task('watch', function() {
gulp.watch(paths.jade, ['jade']);
gulp.watch(paths.ls, ['ls']);
gulp.watch(paths.sass, ['sass']);
});
|
import { rowsAir, tableRock } from "../../../utils";
import { getAttribute } from "@util/attribute";
let rowsA = [
{ key: "dmg1", chs: "1- Normal Attack Damage" },
{ key: "dmg2", chs: "2- Normal Attack Damage" },
];
let rowsB = [
{ key: "bDmg1", chs: "Charge Attack Damage -1" },
]
export default function (artifacts, configObject, enemy) {
let c = configObject.character;
let w = configObject.weapon;
let attribute = getAttribute(artifacts, c, w, configObject.buffs, configObject.artifactsConfig);
let a = tableRock(attribute, configObject, enemy, rowsA, "a");
let b = tableRock(attribute, configObject, enemy, rowsB, "b");
let air = tableRock(attribute, configObject, enemy, rowsAir, "air");
return {
a, b, air,
}
}
|
import {Feature} from "../../utils/feature.js";
export default new Feature({
id: 'bluetooth',
name: 'Bluetooth',
description: [
`The <b>Web Bluetooth API</b> is a low-level API allowing Web applications to pair with the nearby Bluetooth Low Energy-enabled peripheral devices and access their services exposed.`
],
api: `<dl>
<dt><code>navigator.bluetooth.requestDevice(serviceFilters)</code></dt>
<dd>Scans for the device in range supporting the requested services. Returns a <code>Promise</code>.</dd>
<dt><code>device.gatt.connect()</code></dt>
<dd>Returns a <code>Promise</code> resolved with the server object providing access to the services available on the device.</dd>
<dt><code>server.getPrimaryService(name)</code></dt>
<dd>Returns a <code>Promise</code> resolved with the particular Bluetooth service on the device.</dd>
<dt><code>service.getCharacteristic(name)</code></dt>
<dd>Returns a <code>Promise</code> resolved with the GATT characteristic object.</dd>
<dt><code>characteristic.readValue()</code></dt>
<dd>Returns a <code>Promise</code> resolved with a raw value from the GATT characteristic.</dd>
<dt><code>characteristic.writeValue(value)</code></dt>
<dd>Writes a new value for the GATT characteristic.</dd>
</dl>`,
tests: [Feature.navigatorContains('bluetooth')],
caniuse: 'web-bluetooth',
demo: {
html: `<p>
<button onclick="readBatteryLevel()">Read Bluetooth device's<br>battery level</button>
</p>
<p id="target"></p>
<p><small>Based on code snippets from <a href="https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web" target="_blank" rel="noopener">Google Developers</a>.</small></p>`,
js: `function readBatteryLevel() {
var $target = document.getElementById('target');
if (!('bluetooth' in navigator)) {
$target.innerText = 'Bluetooth API not supported.';
return;
}
navigator.bluetooth.requestDevice({
filters: [{
services: ['battery_service']
}]
})
.then(function (device) {
return device.gatt.connect();
})
.then(function (server) {
return server.getPrimaryService('battery_service');
})
.then(function (service) {
return service.getCharacteristic('battery_level');
})
.then(function (characteristic) {
return characteristic.readValue();
})
.then(function (value) {
$target.innerHTML = 'Battery percentage is <b>' + value.getUint8(0) + '</b>.';
})
.catch(function (error) {
$target.innerText = error;
});
}`
},
links: [
{url: 'https://webbluetoothcg.github.io/web-bluetooth/', title: 'Specification Draft'},
{
url: 'https://developers.google.com/web/updates/2015/07/interact-with-ble-devices-on-the-web',
title: 'Interact with BLE devices on the Web'
}
]
})
|
// This file handles various upgrade procedures
// when file syntax changes between versions.
// const util = require('./util.js');
// const fs = require('fs');
module.exports = {
// Takes inputs:
// fromVersion, which is the version we are upgrading from
// toVersion, which is the version we are upgrading to
// files, object containing paths to various json files (settings, etc.)
// callback, which is callback
upgrade: function (fromVersion, toVersion, files) {
// At the moment, not used for anything
// TODO: delet this?
}
};
|
// stage types
export const MAIN = 'MAIN';
export const QUALIFYING = 'QUALIFYING';
export const CONSOLATION = 'CONSOLATION';
export const VOLUNTARY_CONSOLATION = 'VOLUNTARY_CONSOLATION';
export const PLAY_OFF = 'PLAY_OFF';
export const validStages = [
MAIN,
QUALIFYING,
CONSOLATION,
PLAY_OFF,
VOLUNTARY_CONSOLATION,
];
export const stageOrder = {
[QUALIFYING]: 1,
[MAIN]: 2,
[PLAY_OFF]: 3,
[CONSOLATION]: 3,
[VOLUNTARY_CONSOLATION]: 4,
};
// seedingProfile
export const CLUSTER = 'CLUSTER';
export const SEPARATE = 'SEPARATE';
export const WATERFALL = 'WATERFALL';
// structureType
export const ITEM = 'ITEM';
export const CONTAINER = 'CONTAINER';
// positioningProfile
export const DRAW = 'DRAW';
export const RANDOM = 'RANDOM';
export const TOP_DOWN = 'TOP_DOWN';
export const BOTTOM_UP = 'BOTTOM_UP';
// Match and Link types
export const POSITION = 'POSITION'; // participant advances based on their finishing position
export const WINNER = 'WINNER'; // participant advances based on winning a matchUp
export const LOSER = 'LOSER'; // partticipant advances based on losing a matchUp
export const FIRST_MATCHUP = 'FIRST_MATCHUP'; // condition for valididty of link
// draw types
// PLAY_OFF is also a stage type
export const AD_HOC = 'AD_HOC';
export const FEED_IN = 'FEED_IN';
export const COMPASS = 'COMPASS';
export const OLYMPIC = 'OLYMPIC';
export const KNOCKOUT = 'SINGLE_ELIMINATION';
export const ELIMINATION = 'SINGLE_ELIMINATION';
export const SINGLE_ELIMINATION = 'SINGLE_ELIMINATION';
export const DOUBLE_ELIMINATION = 'DOUBLE_ELIMINATION';
export const FIRST_MATCH_LOSER_CONSOLATION = 'FIRST_MATCH_LOSER_CONSOLATION';
export const FIRST_ROUND_LOSER_CONSOLATION = 'FIRST_ROUND_LOSER_CONSOLATION';
export const LUCKY_DRAW = 'LUCKY_DRAW';
export const CURTIS = 'CURTIS_CONSOLATION';
export const CURTIS_CONSOLATION = 'CURTIS_CONSOLATION';
export const FICSF = 'FEED_IN_CHAMPIONSHIP_TO_SF';
export const FEED_IN_CHAMPIONSHIP_TO_SF = 'FEED_IN_CHAMPIONSHIP_TO_SF';
export const FICQF = 'FEED_IN_CHAMPIONSHIP_TO_QF';
export const FEED_IN_CHAMPIONSHIP_TO_QF = 'FEED_IN_CHAMPIONSHIP_TO_QF';
export const FICR16 = 'FEED_IN_CHAMPIONSHIP_TO_R16';
export const FEED_IN_CHAMPIONSHIP_TO_R16 = 'FEED_IN_CHAMPIONSHIP_TO_R16';
export const MFIC = 'MODIFIED_FEED_IN_CHAMPIONSHIP';
export const MODIFIED_FEED_IN_CHAMPIONSHIP = 'MODIFIED_FEED_IN_CHAMPIONSHIP';
export const FEED_IN_CHAMPIONSHIP = 'FEED_IN_CHAMPIONSHIP';
export const ROUND_ROBIN = 'ROUND_ROBIN';
export const ROUND_ROBIN_WITH_PLAYOFF = 'ROUND_ROBIN_WITH_PLAYOFF';
// structure naming
export const DECIDER = 'DECIDER';
export const BACKDRAW = 'BACKDRAW';
export const COMPASS_ATTRIBUTES = {
0: { name: 'EAST', abbreviation: 'E' },
'0-1': { name: 'WEST', abbreviation: 'W' },
'0-2': { name: 'NORTH', abbreviation: 'N' },
'0-3': { name: 'NORTHEAST', abbreviation: 'NE' },
'0-1-1': { name: 'SOUTH', abbreviation: 'S' },
'0-1-2': { name: 'SOUTHWEST', abbreviation: 'SW' },
'0-2-1': { name: 'NORTHWEST', abbreviation: 'NW' },
'0-1-1-1': { name: 'SOUTHEAST', abbreviation: 'SE' },
};
export const OLYMPIC_ATTRIBUTES = {
0: { name: 'EAST', abbreviation: 'E' },
'0-1': { name: 'WEST', abbreviation: 'W' },
'0-2': { name: 'NORTH', abbreviation: 'N' },
'0-1-1': { name: 'SOUTH', abbreviation: 'S' },
};
// finishingPosition determination
export const WIN_RATIO = 'WIN_RATIO';
export const ROUND_OUTCOME = 'ROUND_OUTCOME';
export const MULTI_STRUCTURE_DRAWS = [
COMPASS,
CURTIS,
FEED_IN_CHAMPIONSHIP_TO_QF,
FEED_IN_CHAMPIONSHIP_TO_R16,
FEED_IN_CHAMPIONSHIP_TO_SF,
FEED_IN_CHAMPIONSHIP,
FICQF,
FICR16,
FICSF,
FIRST_MATCH_LOSER_CONSOLATION,
FIRST_ROUND_LOSER_CONSOLATION,
LUCKY_DRAW,
MODIFIED_FEED_IN_CHAMPIONSHIP,
OLYMPIC,
PLAY_OFF,
ROUND_ROBIN_WITH_PLAYOFF,
];
export const generatedDrawTypes = [
AD_HOC,
COMPASS,
CURTIS,
DOUBLE_ELIMINATION,
FEED_IN_CHAMPIONSHIP_TO_QF,
FEED_IN_CHAMPIONSHIP_TO_R16,
FEED_IN_CHAMPIONSHIP_TO_SF,
FEED_IN_CHAMPIONSHIP,
FEED_IN,
FIRST_MATCH_LOSER_CONSOLATION,
FIRST_ROUND_LOSER_CONSOLATION,
LUCKY_DRAW,
MODIFIED_FEED_IN_CHAMPIONSHIP,
OLYMPIC,
PLAY_OFF,
ROUND_ROBIN,
ROUND_ROBIN_WITH_PLAYOFF,
SINGLE_ELIMINATION,
];
export const drawDefinitionConstants = {
MAIN,
QUALIFYING,
CONSOLATION,
ITEM,
CONTAINER,
FIRST_MATCHUP,
WINNER,
LOSER,
AD_HOC,
FEED_IN,
COMPASS,
PLAY_OFF,
OLYMPIC,
KNOCKOUT,
SINGLE_ELIMINATION,
DOUBLE_ELIMINATION,
CURTIS,
FICSF,
FICQF,
FICR16,
MFIC,
VOLUNTARY_CONSOLATION,
FIRST_MATCH_LOSER_CONSOLATION,
FIRST_ROUND_LOSER_CONSOLATION,
MODIFIED_FEED_IN_CHAMPIONSHIP,
FEED_IN_CHAMPIONSHIP_TO_R16,
FEED_IN_CHAMPIONSHIP_TO_QF,
FEED_IN_CHAMPIONSHIP_TO_SF,
FEED_IN_CHAMPIONSHIP,
ROUND_ROBIN_WITH_PLAYOFF,
ROUND_ROBIN,
DECIDER,
BACKDRAW,
COMPASS_ATTRIBUTES,
OLYMPIC_ATTRIBUTES,
DRAW,
RANDOM,
TOP_DOWN,
BOTTOM_UP,
WATERFALL,
WIN_RATIO,
ROUND_OUTCOME,
MULTI_STRUCTURE_DRAWS,
generatedDrawTypes,
stageOrder,
};
export default drawDefinitionConstants;
|
const connections = require("../app/database");
class LabelService {
async create(name) {
const statement = `INSERT INTO label (name) VALUES(?);`;
const [result] = await connections.execute(statement, [name]);
return result;
}
async getLabelByName(name) {
const statement = `SELECT * FROM label WHERE name = ?;`;
try {
const [result] = await connections.execute(statement, [name]);
if (!result[0]) {
throw new Error();
}
// 如果取到数据则返回true
return result[0];
} catch (error) {
console.log(error);
}
}
async getLabels(offset,limit) {
const statement = `SELECT * FROM label LIMIT ?,?;`;
const [result] = await connections.execute(statement,[offset,limit]);
return result
}
}
module.exports = new LabelService();
|
import styled from "styled-components"
const AwardsSectionWrapper = styled.div`
padding: 85px 0;
.heading {
padding-right: 103px;
}
.col:nth-of-type(odd) {
.awards-item {
margin-right: 10px;
}
}
.awards-item-wrapper {
display: inline-flex;
flex-wrap: wrap;
justify-content: space-between;
.awards-item {
display: flex;
width: 49%;
color: #fff;
align-items: center;
padding: 20px 0 20px 50px;
margin-bottom: 10px;
background: #2b1867;
border-radius: 5px;
cursor: pointer;
&.active,
&:hover {
background: rgb(32, 47, 213);
background: linear-gradient(
90deg,
rgba(32, 47, 213, 1) 0%,
rgba(139, 51, 224, 1) 57%,
rgba(195, 56, 231, 1) 100%
);
box-shadow: 0px 0px 17px #221156;
}
.award-icon {
margin-right: 50px;
font-size: 30px;
}
.counter-text {
span {
display: block;
&:first-child {
font-size: 30px;
font-weight: 700;
margin-bottom: 5px;
}
&.text {
margin: 0;
color: #beabdf;
font-family: Open sans;
}
}
}
}
}
@media only screen and (max-width: 1024px) {
.awards-item-wrapper {
.awards-item {
padding: 20px 0 20px 30px;
.award-icon {
margin-right: 30px;
}
}
}
}
@media only screen and (max-width: 912px) {
.awards-item-wrapper {
.awards-item {
padding: 20px 0 20px 15px;
.counter-text {
span:first-child {
font-size: 23px;
}
}
.award-icon {
margin-right: 15px;
}
}
}
}
@media only screen and (max-width: 736px) {
.title__wrapper {
margin-bottom: 50px;
}
.awards-item-wrapper {
.awards-item {
padding: 20px 0 20px 30px;
.counter-text {
span:first-child {
font-size: 30px;
}
}
.award-icon {
margin-right: 30px;
}
}
}
}
@media only screen and (max-width: 480px) {
padding: 50px 0;
}
@media only screen and (max-width: 480px) {
.heading {
padding-right: 0;
font-size: 30px;
}
.awards-col {
width: 100%;
}
.awards-item-wrapper {
flex-direction: column;
width: 100%;
.awards-item {
width: 100%;
margin-bottom: 30px;
}
}
}
@media only screen and (max-width: 375px) {
.heading {
font-size: 25px;
line-height: 35px;
}
}
`
export default AwardsSectionWrapper
|
'use strict';
let angular = require('angular');
module.exports = angular.module('spinnaker.core.deploymentStrategy.none', [])
.config(function(deploymentStrategyConfigProvider) {
deploymentStrategyConfigProvider.registerStrategy({
label: 'None',
description: 'Creates the next server group with no impact on existing server groups',
key: '',
});
});
|
import sum from './calculations/sum.js'
import validateAddends from './validations/validate-addends.js'
async function add(...addends) {
validateAddends(addends)
return sum(addends)
}
export default add
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('jquery')) :
typeof define === 'function' && define.amd ? define(['jquery'], factory) :
(global = global || self, global.BootstrapTable = factory(global.jQuery));
}(this, function ($) { 'use strict';
$ = $ && $.hasOwnProperty('default') ? $['default'] : $;
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var O = 'object';
var check = function (it) {
return it && it.Math == Math && it;
};
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global_1 =
// eslint-disable-next-line no-undef
check(typeof globalThis == O && globalThis) ||
check(typeof window == O && window) ||
check(typeof self == O && self) ||
check(typeof commonjsGlobal == O && commonjsGlobal) ||
// eslint-disable-next-line no-new-func
Function('return this')();
var fails = function (exec) {
try {
return !!exec();
} catch (error) {
return true;
}
};
// Thank's IE8 for his funny defineProperty
var descriptors = !fails(function () {
return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
});
var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// Nashorn ~ JDK8 bug
var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);
// `Object.prototype.propertyIsEnumerable` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
var descriptor = getOwnPropertyDescriptor(this, V);
return !!descriptor && descriptor.enumerable;
} : nativePropertyIsEnumerable;
var objectPropertyIsEnumerable = {
f: f
};
var createPropertyDescriptor = function (bitmap, value) {
return {
enumerable: !(bitmap & 1),
configurable: !(bitmap & 2),
writable: !(bitmap & 4),
value: value
};
};
var toString = {}.toString;
var classofRaw = function (it) {
return toString.call(it).slice(8, -1);
};
var split = ''.split;
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var indexedObject = fails(function () {
// throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
// eslint-disable-next-line no-prototype-builtins
return !Object('z').propertyIsEnumerable(0);
}) ? function (it) {
return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
} : Object;
// `RequireObjectCoercible` abstract operation
// https://tc39.github.io/ecma262/#sec-requireobjectcoercible
var requireObjectCoercible = function (it) {
if (it == undefined) throw TypeError("Can't call method on " + it);
return it;
};
// toObject with fallback for non-array-like ES3 strings
var toIndexedObject = function (it) {
return indexedObject(requireObjectCoercible(it));
};
var isObject = function (it) {
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
// `ToPrimitive` abstract operation
// https://tc39.github.io/ecma262/#sec-toprimitive
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
var toPrimitive = function (input, PREFERRED_STRING) {
if (!isObject(input)) return input;
var fn, val;
if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
throw TypeError("Can't convert object to primitive value");
};
var hasOwnProperty = {}.hasOwnProperty;
var has = function (it, key) {
return hasOwnProperty.call(it, key);
};
var document$1 = global_1.document;
// typeof document.createElement is 'object' in old IE
var EXISTS = isObject(document$1) && isObject(document$1.createElement);
var documentCreateElement = function (it) {
return EXISTS ? document$1.createElement(it) : {};
};
// Thank's IE8 for his funny defineProperty
var ie8DomDefine = !descriptors && !fails(function () {
return Object.defineProperty(documentCreateElement('div'), 'a', {
get: function () { return 7; }
}).a != 7;
});
var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
O = toIndexedObject(O);
P = toPrimitive(P, true);
if (ie8DomDefine) try {
return nativeGetOwnPropertyDescriptor(O, P);
} catch (error) { /* empty */ }
if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
};
var objectGetOwnPropertyDescriptor = {
f: f$1
};
var anObject = function (it) {
if (!isObject(it)) {
throw TypeError(String(it) + ' is not an object');
} return it;
};
var nativeDefineProperty = Object.defineProperty;
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if (ie8DomDefine) try {
return nativeDefineProperty(O, P, Attributes);
} catch (error) { /* empty */ }
if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
if ('value' in Attributes) O[P] = Attributes.value;
return O;
};
var objectDefineProperty = {
f: f$2
};
var hide = descriptors ? function (object, key, value) {
return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
} : function (object, key, value) {
object[key] = value;
return object;
};
var setGlobal = function (key, value) {
try {
hide(global_1, key, value);
} catch (error) {
global_1[key] = value;
} return value;
};
var shared = createCommonjsModule(function (module) {
var SHARED = '__core-js_shared__';
var store = global_1[SHARED] || setGlobal(SHARED, {});
(module.exports = function (key, value) {
return store[key] || (store[key] = value !== undefined ? value : {});
})('versions', []).push({
version: '3.1.3',
mode: 'global',
copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
});
});
var functionToString = shared('native-function-to-string', Function.toString);
var WeakMap = global_1.WeakMap;
var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(functionToString.call(WeakMap));
var id = 0;
var postfix = Math.random();
var uid = function (key) {
return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
};
var keys = shared('keys');
var sharedKey = function (key) {
return keys[key] || (keys[key] = uid(key));
};
var hiddenKeys = {};
var WeakMap$1 = global_1.WeakMap;
var set, get, has$1;
var enforce = function (it) {
return has$1(it) ? get(it) : set(it, {});
};
var getterFor = function (TYPE) {
return function (it) {
var state;
if (!isObject(it) || (state = get(it)).type !== TYPE) {
throw TypeError('Incompatible receiver, ' + TYPE + ' required');
} return state;
};
};
if (nativeWeakMap) {
var store = new WeakMap$1();
var wmget = store.get;
var wmhas = store.has;
var wmset = store.set;
set = function (it, metadata) {
wmset.call(store, it, metadata);
return metadata;
};
get = function (it) {
return wmget.call(store, it) || {};
};
has$1 = function (it) {
return wmhas.call(store, it);
};
} else {
var STATE = sharedKey('state');
hiddenKeys[STATE] = true;
set = function (it, metadata) {
hide(it, STATE, metadata);
return metadata;
};
get = function (it) {
return has(it, STATE) ? it[STATE] : {};
};
has$1 = function (it) {
return has(it, STATE);
};
}
var internalState = {
set: set,
get: get,
has: has$1,
enforce: enforce,
getterFor: getterFor
};
var redefine = createCommonjsModule(function (module) {
var getInternalState = internalState.get;
var enforceInternalState = internalState.enforce;
var TEMPLATE = String(functionToString).split('toString');
shared('inspectSource', function (it) {
return functionToString.call(it);
});
(module.exports = function (O, key, value, options) {
var unsafe = options ? !!options.unsafe : false;
var simple = options ? !!options.enumerable : false;
var noTargetGet = options ? !!options.noTargetGet : false;
if (typeof value == 'function') {
if (typeof key == 'string' && !has(value, 'name')) hide(value, 'name', key);
enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
}
if (O === global_1) {
if (simple) O[key] = value;
else setGlobal(key, value);
return;
} else if (!unsafe) {
delete O[key];
} else if (!noTargetGet && O[key]) {
simple = true;
}
if (simple) O[key] = value;
else hide(O, key, value);
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, 'toString', function toString() {
return typeof this == 'function' && getInternalState(this).source || functionToString.call(this);
});
});
var path = global_1;
var aFunction = function (variable) {
return typeof variable == 'function' ? variable : undefined;
};
var getBuiltIn = function (namespace, method) {
return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
: path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
};
var ceil = Math.ceil;
var floor = Math.floor;
// `ToInteger` abstract operation
// https://tc39.github.io/ecma262/#sec-tointeger
var toInteger = function (argument) {
return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
};
var min = Math.min;
// `ToLength` abstract operation
// https://tc39.github.io/ecma262/#sec-tolength
var toLength = function (argument) {
return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
};
var max = Math.max;
var min$1 = Math.min;
// Helper for a popular repeating case of the spec:
// Let integer be ? ToInteger(index).
// If integer < 0, let result be max((length + integer), 0); else let result be min(length, length).
var toAbsoluteIndex = function (index, length) {
var integer = toInteger(index);
return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
};
// `Array.prototype.{ indexOf, includes }` methods implementation
var createMethod = function (IS_INCLUDES) {
return function ($this, el, fromIndex) {
var O = toIndexedObject($this);
var length = toLength(O.length);
var index = toAbsoluteIndex(fromIndex, length);
var value;
// Array#includes uses SameValueZero equality algorithm
// eslint-disable-next-line no-self-compare
if (IS_INCLUDES && el != el) while (length > index) {
value = O[index++];
// eslint-disable-next-line no-self-compare
if (value != value) return true;
// Array#indexOf ignores holes, Array#includes - not
} else for (;length > index; index++) {
if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
var arrayIncludes = {
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
includes: createMethod(true),
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
indexOf: createMethod(false)
};
var indexOf = arrayIncludes.indexOf;
var objectKeysInternal = function (object, names) {
var O = toIndexedObject(object);
var i = 0;
var result = [];
var key;
for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while (names.length > i) if (has(O, key = names[i++])) {
~indexOf(result, key) || result.push(key);
}
return result;
};
// IE8- don't enum bug keys
var enumBugKeys = [
'constructor',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'toLocaleString',
'toString',
'valueOf'
];
var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
return objectKeysInternal(O, hiddenKeys$1);
};
var objectGetOwnPropertyNames = {
f: f$3
};
var f$4 = Object.getOwnPropertySymbols;
var objectGetOwnPropertySymbols = {
f: f$4
};
// all object keys, includes non-enumerable and symbols
var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
var keys = objectGetOwnPropertyNames.f(anObject(it));
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
};
var copyConstructorProperties = function (target, source) {
var keys = ownKeys(source);
var defineProperty = objectDefineProperty.f;
var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
}
};
var replacement = /#|\.prototype\./;
var isForced = function (feature, detection) {
var value = data[normalize(feature)];
return value == POLYFILL ? true
: value == NATIVE ? false
: typeof detection == 'function' ? fails(detection)
: !!detection;
};
var normalize = isForced.normalize = function (string) {
return String(string).replace(replacement, '.').toLowerCase();
};
var data = isForced.data = {};
var NATIVE = isForced.NATIVE = 'N';
var POLYFILL = isForced.POLYFILL = 'P';
var isForced_1 = isForced;
var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
/*
options.target - name of the target object
options.global - target is the global object
options.stat - export as static methods of target
options.proto - export as prototype methods of target
options.real - real prototype method for the `pure` version
options.forced - export even if the native feature is available
options.bind - bind methods to the target, required for the `pure` version
options.wrap - wrap constructors to preventing global pollution, required for the `pure` version
options.unsafe - use the simple assignment of property instead of delete + defineProperty
options.sham - add a flag to not completely full polyfills
options.enumerable - export as enumerable property
options.noTargetGet - prevent calling a getter on target
*/
var _export = function (options, source) {
var TARGET = options.target;
var GLOBAL = options.global;
var STATIC = options.stat;
var FORCED, target, key, targetProperty, sourceProperty, descriptor;
if (GLOBAL) {
target = global_1;
} else if (STATIC) {
target = global_1[TARGET] || setGlobal(TARGET, {});
} else {
target = (global_1[TARGET] || {}).prototype;
}
if (target) for (key in source) {
sourceProperty = source[key];
if (options.noTargetGet) {
descriptor = getOwnPropertyDescriptor$1(target, key);
targetProperty = descriptor && descriptor.value;
} else targetProperty = target[key];
FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
// contained in target
if (!FORCED && targetProperty !== undefined) {
if (typeof sourceProperty === typeof targetProperty) continue;
copyConstructorProperties(sourceProperty, targetProperty);
}
// add a flag to not completely full polyfills
if (options.sham || (targetProperty && targetProperty.sham)) {
hide(sourceProperty, 'sham', true);
}
// extend global
redefine(target, key, sourceProperty, options);
}
};
var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
// Chrome 38 Symbol has incorrect toString conversion
// eslint-disable-next-line no-undef
return !String(Symbol());
});
// `IsArray` abstract operation
// https://tc39.github.io/ecma262/#sec-isarray
var isArray = Array.isArray || function isArray(arg) {
return classofRaw(arg) == 'Array';
};
// `ToObject` abstract operation
// https://tc39.github.io/ecma262/#sec-toobject
var toObject = function (argument) {
return Object(requireObjectCoercible(argument));
};
// `Object.keys` method
// https://tc39.github.io/ecma262/#sec-object.keys
var objectKeys = Object.keys || function keys(O) {
return objectKeysInternal(O, enumBugKeys);
};
// `Object.defineProperties` method
// https://tc39.github.io/ecma262/#sec-object.defineproperties
var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
anObject(O);
var keys = objectKeys(Properties);
var length = keys.length;
var index = 0;
var key;
while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]);
return O;
};
var html = getBuiltIn('document', 'documentElement');
var IE_PROTO = sharedKey('IE_PROTO');
var PROTOTYPE = 'prototype';
var Empty = function () { /* empty */ };
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function () {
// Thrash, waste and sodomy: IE GC bug
var iframe = documentCreateElement('iframe');
var length = enumBugKeys.length;
var lt = '<';
var script = 'script';
var gt = '>';
var js = 'java' + script + ':';
var iframeDocument;
iframe.style.display = 'none';
html.appendChild(iframe);
iframe.src = String(js);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]];
return createDict();
};
// `Object.create` method
// https://tc39.github.io/ecma262/#sec-object.create
var objectCreate = Object.create || function create(O, Properties) {
var result;
if (O !== null) {
Empty[PROTOTYPE] = anObject(O);
result = new Empty();
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : objectDefineProperties(result, Properties);
};
hiddenKeys[IE_PROTO] = true;
var nativeGetOwnPropertyNames = objectGetOwnPropertyNames.f;
var toString$1 = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function (it) {
try {
return nativeGetOwnPropertyNames(it);
} catch (error) {
return windowNames.slice();
}
};
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var f$5 = function getOwnPropertyNames(it) {
return windowNames && toString$1.call(it) == '[object Window]'
? getWindowNames(it)
: nativeGetOwnPropertyNames(toIndexedObject(it));
};
var objectGetOwnPropertyNamesExternal = {
f: f$5
};
var Symbol$1 = global_1.Symbol;
var store$1 = shared('wks');
var wellKnownSymbol = function (name) {
return store$1[name] || (store$1[name] = nativeSymbol && Symbol$1[name]
|| (nativeSymbol ? Symbol$1 : uid)('Symbol.' + name));
};
var f$6 = wellKnownSymbol;
var wrappedWellKnownSymbol = {
f: f$6
};
var defineProperty = objectDefineProperty.f;
var defineWellKnownSymbol = function (NAME) {
var Symbol = path.Symbol || (path.Symbol = {});
if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {
value: wrappedWellKnownSymbol.f(NAME)
});
};
var defineProperty$1 = objectDefineProperty.f;
var TO_STRING_TAG = wellKnownSymbol('toStringTag');
var setToStringTag = function (it, TAG, STATIC) {
if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
defineProperty$1(it, TO_STRING_TAG, { configurable: true, value: TAG });
}
};
var aFunction$1 = function (it) {
if (typeof it != 'function') {
throw TypeError(String(it) + ' is not a function');
} return it;
};
// optional / simple context binding
var bindContext = function (fn, that, length) {
aFunction$1(fn);
if (that === undefined) return fn;
switch (length) {
case 0: return function () {
return fn.call(that);
};
case 1: return function (a) {
return fn.call(that, a);
};
case 2: return function (a, b) {
return fn.call(that, a, b);
};
case 3: return function (a, b, c) {
return fn.call(that, a, b, c);
};
}
return function (/* ...args */) {
return fn.apply(that, arguments);
};
};
var SPECIES = wellKnownSymbol('species');
// `ArraySpeciesCreate` abstract operation
// https://tc39.github.io/ecma262/#sec-arrayspeciescreate
var arraySpeciesCreate = function (originalArray, length) {
var C;
if (isArray(originalArray)) {
C = originalArray.constructor;
// cross-realm fallback
if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
else if (isObject(C)) {
C = C[SPECIES];
if (C === null) C = undefined;
}
} return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
};
var push = [].push;
// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
var createMethod$1 = function (TYPE) {
var IS_MAP = TYPE == 1;
var IS_FILTER = TYPE == 2;
var IS_SOME = TYPE == 3;
var IS_EVERY = TYPE == 4;
var IS_FIND_INDEX = TYPE == 6;
var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
return function ($this, callbackfn, that, specificCreate) {
var O = toObject($this);
var self = indexedObject(O);
var boundFunction = bindContext(callbackfn, that, 3);
var length = toLength(self.length);
var index = 0;
var create = specificCreate || arraySpeciesCreate;
var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
var value, result;
for (;length > index; index++) if (NO_HOLES || index in self) {
value = self[index];
result = boundFunction(value, index, O);
if (TYPE) {
if (IS_MAP) target[index] = result; // map
else if (result) switch (TYPE) {
case 3: return true; // some
case 5: return value; // find
case 6: return index; // findIndex
case 2: push.call(target, value); // filter
} else if (IS_EVERY) return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
};
};
var arrayIteration = {
// `Array.prototype.forEach` method
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
forEach: createMethod$1(0),
// `Array.prototype.map` method
// https://tc39.github.io/ecma262/#sec-array.prototype.map
map: createMethod$1(1),
// `Array.prototype.filter` method
// https://tc39.github.io/ecma262/#sec-array.prototype.filter
filter: createMethod$1(2),
// `Array.prototype.some` method
// https://tc39.github.io/ecma262/#sec-array.prototype.some
some: createMethod$1(3),
// `Array.prototype.every` method
// https://tc39.github.io/ecma262/#sec-array.prototype.every
every: createMethod$1(4),
// `Array.prototype.find` method
// https://tc39.github.io/ecma262/#sec-array.prototype.find
find: createMethod$1(5),
// `Array.prototype.findIndex` method
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
findIndex: createMethod$1(6)
};
var $forEach = arrayIteration.forEach;
var HIDDEN = sharedKey('hidden');
var SYMBOL = 'Symbol';
var PROTOTYPE$1 = 'prototype';
var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
var setInternalState = internalState.set;
var getInternalState = internalState.getterFor(SYMBOL);
var ObjectPrototype = Object[PROTOTYPE$1];
var $Symbol = global_1.Symbol;
var JSON$1 = global_1.JSON;
var nativeJSONStringify = JSON$1 && JSON$1.stringify;
var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
var nativeDefineProperty$1 = objectDefineProperty.f;
var nativeGetOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f;
var nativePropertyIsEnumerable$1 = objectPropertyIsEnumerable.f;
var AllSymbols = shared('symbols');
var ObjectPrototypeSymbols = shared('op-symbols');
var StringToSymbolRegistry = shared('string-to-symbol-registry');
var SymbolToStringRegistry = shared('symbol-to-string-registry');
var WellKnownSymbolsStore = shared('wks');
var QObject = global_1.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDescriptor = descriptors && fails(function () {
return objectCreate(nativeDefineProperty$1({}, 'a', {
get: function () { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; }
})).a != 7;
}) ? function (O, P, Attributes) {
var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$1(ObjectPrototype, P);
if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
nativeDefineProperty$1(O, P, Attributes);
if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
nativeDefineProperty$1(ObjectPrototype, P, ObjectPrototypeDescriptor);
}
} : nativeDefineProperty$1;
var wrap = function (tag, description) {
var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE$1]);
setInternalState(symbol, {
type: SYMBOL,
tag: tag,
description: description
});
if (!descriptors) symbol.description = description;
return symbol;
};
var isSymbol = nativeSymbol && typeof $Symbol.iterator == 'symbol' ? function (it) {
return typeof it == 'symbol';
} : function (it) {
return Object(it) instanceof $Symbol;
};
var $defineProperty = function defineProperty(O, P, Attributes) {
if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
anObject(O);
var key = toPrimitive(P, true);
anObject(Attributes);
if (has(AllSymbols, key)) {
if (!Attributes.enumerable) {
if (!has(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor(1, {}));
O[HIDDEN][key] = true;
} else {
if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
} return setSymbolDescriptor(O, key, Attributes);
} return nativeDefineProperty$1(O, key, Attributes);
};
var $defineProperties = function defineProperties(O, Properties) {
anObject(O);
var properties = toIndexedObject(Properties);
var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
$forEach(keys, function (key) {
if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
});
return O;
};
var $create = function create(O, Properties) {
return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties);
};
var $propertyIsEnumerable = function propertyIsEnumerable(V) {
var P = toPrimitive(V, true);
var enumerable = nativePropertyIsEnumerable$1.call(this, P);
if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
var it = toIndexedObject(O);
var key = toPrimitive(P, true);
if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
var descriptor = nativeGetOwnPropertyDescriptor$1(it, key);
if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
descriptor.enumerable = true;
}
return descriptor;
};
var $getOwnPropertyNames = function getOwnPropertyNames(O) {
var names = nativeGetOwnPropertyNames$1(toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
});
return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
var names = nativeGetOwnPropertyNames$1(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
var result = [];
$forEach(names, function (key) {
if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
result.push(AllSymbols[key]);
}
});
return result;
};
// `Symbol` constructor
// https://tc39.github.io/ecma262/#sec-symbol-constructor
if (!nativeSymbol) {
$Symbol = function Symbol() {
if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
var tag = uid(description);
var setter = function (value) {
if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
};
if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
return wrap(tag, description);
};
redefine($Symbol[PROTOTYPE$1], 'toString', function toString() {
return getInternalState(this).tag;
});
objectPropertyIsEnumerable.f = $propertyIsEnumerable;
objectDefineProperty.f = $defineProperty;
objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor;
objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames;
objectGetOwnPropertySymbols.f = $getOwnPropertySymbols;
if (descriptors) {
// https://github.com/tc39/proposal-Symbol-description
nativeDefineProperty$1($Symbol[PROTOTYPE$1], 'description', {
configurable: true,
get: function description() {
return getInternalState(this).description;
}
});
{
redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
}
}
wrappedWellKnownSymbol.f = function (name) {
return wrap(wellKnownSymbol(name), name);
};
}
_export({ global: true, wrap: true, forced: !nativeSymbol, sham: !nativeSymbol }, {
Symbol: $Symbol
});
$forEach(objectKeys(WellKnownSymbolsStore), function (name) {
defineWellKnownSymbol(name);
});
_export({ target: SYMBOL, stat: true, forced: !nativeSymbol }, {
// `Symbol.for` method
// https://tc39.github.io/ecma262/#sec-symbol.for
'for': function (key) {
var string = String(key);
if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
var symbol = $Symbol(string);
StringToSymbolRegistry[string] = symbol;
SymbolToStringRegistry[symbol] = string;
return symbol;
},
// `Symbol.keyFor` method
// https://tc39.github.io/ecma262/#sec-symbol.keyfor
keyFor: function keyFor(sym) {
if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
},
useSetter: function () { USE_SETTER = true; },
useSimple: function () { USE_SETTER = false; }
});
_export({ target: 'Object', stat: true, forced: !nativeSymbol, sham: !descriptors }, {
// `Object.create` method
// https://tc39.github.io/ecma262/#sec-object.create
create: $create,
// `Object.defineProperty` method
// https://tc39.github.io/ecma262/#sec-object.defineproperty
defineProperty: $defineProperty,
// `Object.defineProperties` method
// https://tc39.github.io/ecma262/#sec-object.defineproperties
defineProperties: $defineProperties,
// `Object.getOwnPropertyDescriptor` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
getOwnPropertyDescriptor: $getOwnPropertyDescriptor
});
_export({ target: 'Object', stat: true, forced: !nativeSymbol }, {
// `Object.getOwnPropertyNames` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertynames
getOwnPropertyNames: $getOwnPropertyNames,
// `Object.getOwnPropertySymbols` method
// https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
getOwnPropertySymbols: $getOwnPropertySymbols
});
// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
// https://bugs.chromium.org/p/v8/issues/detail?id=3443
_export({ target: 'Object', stat: true, forced: fails(function () { objectGetOwnPropertySymbols.f(1); }) }, {
getOwnPropertySymbols: function getOwnPropertySymbols(it) {
return objectGetOwnPropertySymbols.f(toObject(it));
}
});
// `JSON.stringify` method behavior with symbols
// https://tc39.github.io/ecma262/#sec-json.stringify
JSON$1 && _export({ target: 'JSON', stat: true, forced: !nativeSymbol || fails(function () {
var symbol = $Symbol();
// MS Edge converts symbol values to JSON as {}
return nativeJSONStringify([symbol]) != '[null]'
// WebKit converts symbol values to JSON as null
|| nativeJSONStringify({ a: symbol }) != '{}'
// V8 throws on boxed symbols
|| nativeJSONStringify(Object(symbol)) != '{}';
}) }, {
stringify: function stringify(it) {
var args = [it];
var index = 1;
var replacer, $replacer;
while (arguments.length > index) args.push(arguments[index++]);
$replacer = replacer = args[1];
if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
if (!isArray(replacer)) replacer = function (key, value) {
if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
if (!isSymbol(value)) return value;
};
args[1] = replacer;
return nativeJSONStringify.apply(JSON$1, args);
}
});
// `Symbol.prototype[@@toPrimitive]` method
// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
if (!$Symbol[PROTOTYPE$1][TO_PRIMITIVE]) hide($Symbol[PROTOTYPE$1], TO_PRIMITIVE, $Symbol[PROTOTYPE$1].valueOf);
// `Symbol.prototype[@@toStringTag]` property
// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
setToStringTag($Symbol, SYMBOL);
hiddenKeys[HIDDEN] = true;
var defineProperty$2 = objectDefineProperty.f;
var NativeSymbol = global_1.Symbol;
if (descriptors && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||
// Safari 12 bug
NativeSymbol().description !== undefined
)) {
var EmptyStringDescriptionStore = {};
// wrap Symbol constructor for correct work with undefined description
var SymbolWrapper = function Symbol() {
var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
var result = this instanceof SymbolWrapper
? new NativeSymbol(description)
// in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
: description === undefined ? NativeSymbol() : NativeSymbol(description);
if (description === '') EmptyStringDescriptionStore[result] = true;
return result;
};
copyConstructorProperties(SymbolWrapper, NativeSymbol);
var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
symbolPrototype.constructor = SymbolWrapper;
var symbolToString = symbolPrototype.toString;
var native = String(NativeSymbol('test')) == 'Symbol(test)';
var regexp = /^Symbol\((.*)\)[^)]+$/;
defineProperty$2(symbolPrototype, 'description', {
configurable: true,
get: function description() {
var symbol = isObject(this) ? this.valueOf() : this;
var string = symbolToString.call(symbol);
if (has(EmptyStringDescriptionStore, symbol)) return '';
var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');
return desc === '' ? undefined : desc;
}
});
_export({ global: true, forced: true }, {
Symbol: SymbolWrapper
});
}
// `Symbol.iterator` well-known symbol
// https://tc39.github.io/ecma262/#sec-symbol.iterator
defineWellKnownSymbol('iterator');
var createProperty = function (object, key, value) {
var propertyKey = toPrimitive(key);
if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
else object[propertyKey] = value;
};
var SPECIES$1 = wellKnownSymbol('species');
var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
return !fails(function () {
var array = [];
var constructor = array.constructor = {};
constructor[SPECIES$1] = function () {
return { foo: 1 };
};
return array[METHOD_NAME](Boolean).foo !== 1;
});
};
var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';
var IS_CONCAT_SPREADABLE_SUPPORT = !fails(function () {
var array = [];
array[IS_CONCAT_SPREADABLE] = false;
return array.concat()[0] !== array;
});
var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');
var isConcatSpreadable = function (O) {
if (!isObject(O)) return false;
var spreadable = O[IS_CONCAT_SPREADABLE];
return spreadable !== undefined ? !!spreadable : isArray(O);
};
var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;
// `Array.prototype.concat` method
// https://tc39.github.io/ecma262/#sec-array.prototype.concat
// with adding support of @@isConcatSpreadable and @@species
_export({ target: 'Array', proto: true, forced: FORCED }, {
concat: function concat(arg) { // eslint-disable-line no-unused-vars
var O = toObject(this);
var A = arraySpeciesCreate(O, 0);
var n = 0;
var i, k, length, len, E;
for (i = -1, length = arguments.length; i < length; i++) {
E = i === -1 ? O : arguments[i];
if (isConcatSpreadable(E)) {
len = toLength(E.length);
if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
} else {
if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
createProperty(A, n++, E);
}
}
A.length = n;
return A;
}
});
var $filter = arrayIteration.filter;
// `Array.prototype.filter` method
// https://tc39.github.io/ecma262/#sec-array.prototype.filter
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('filter') }, {
filter: function filter(callbackfn /* , thisArg */) {
return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
var UNSCOPABLES = wellKnownSymbol('unscopables');
var ArrayPrototype = Array.prototype;
// Array.prototype[@@unscopables]
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
if (ArrayPrototype[UNSCOPABLES] == undefined) {
hide(ArrayPrototype, UNSCOPABLES, objectCreate(null));
}
// add a key to Array.prototype[@@unscopables]
var addToUnscopables = function (key) {
ArrayPrototype[UNSCOPABLES][key] = true;
};
var $find = arrayIteration.find;
var FIND = 'find';
var SKIPS_HOLES = true;
// Shouldn't skip holes
if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });
// `Array.prototype.find` method
// https://tc39.github.io/ecma262/#sec-array.prototype.find
_export({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
find: function find(callbackfn /* , that = undefined */) {
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND);
var $findIndex = arrayIteration.findIndex;
var FIND_INDEX = 'findIndex';
var SKIPS_HOLES$1 = true;
// Shouldn't skip holes
if (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES$1 = false; });
// `Array.prototype.findIndex` method
// https://tc39.github.io/ecma262/#sec-array.prototype.findindex
_export({ target: 'Array', proto: true, forced: SKIPS_HOLES$1 }, {
findIndex: function findIndex(callbackfn /* , that = undefined */) {
return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables(FIND_INDEX);
var $includes = arrayIncludes.includes;
// `Array.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
_export({ target: 'Array', proto: true }, {
includes: function includes(el /* , fromIndex = 0 */) {
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('includes');
var sloppyArrayMethod = function (METHOD_NAME, argument) {
var method = [][METHOD_NAME];
return !method || !fails(function () {
// eslint-disable-next-line no-useless-call,no-throw-literal
method.call(null, argument || function () { throw 1; }, 1);
});
};
var $indexOf = arrayIncludes.indexOf;
var nativeIndexOf = [].indexOf;
var NEGATIVE_ZERO = !!nativeIndexOf && 1 / [1].indexOf(1, -0) < 0;
var SLOPPY_METHOD = sloppyArrayMethod('indexOf');
// `Array.prototype.indexOf` method
// https://tc39.github.io/ecma262/#sec-array.prototype.indexof
_export({ target: 'Array', proto: true, forced: NEGATIVE_ZERO || SLOPPY_METHOD }, {
indexOf: function indexOf(searchElement /* , fromIndex = 0 */) {
return NEGATIVE_ZERO
// convert -0 to +0
? nativeIndexOf.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments.length > 1 ? arguments[1] : undefined);
}
});
var correctPrototypeGetter = !fails(function () {
function F() { /* empty */ }
F.prototype.constructor = null;
return Object.getPrototypeOf(new F()) !== F.prototype;
});
var IE_PROTO$1 = sharedKey('IE_PROTO');
var ObjectPrototype$1 = Object.prototype;
// `Object.getPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.getprototypeof
var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) {
O = toObject(O);
if (has(O, IE_PROTO$1)) return O[IE_PROTO$1];
if (typeof O.constructor == 'function' && O instanceof O.constructor) {
return O.constructor.prototype;
} return O instanceof Object ? ObjectPrototype$1 : null;
};
var ITERATOR = wellKnownSymbol('iterator');
var BUGGY_SAFARI_ITERATORS = false;
var returnThis = function () { return this; };
// `%IteratorPrototype%` object
// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;
if ([].keys) {
arrayIterator = [].keys();
// Safari 8 has buggy iterators w/o `next`
if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
else {
PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
}
}
if (IteratorPrototype == undefined) IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
if ( !has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);
var iteratorsCore = {
IteratorPrototype: IteratorPrototype,
BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
};
var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;
var createIteratorConstructor = function (IteratorConstructor, NAME, next) {
var TO_STRING_TAG = NAME + ' Iterator';
IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) });
setToStringTag(IteratorConstructor, TO_STRING_TAG, false);
return IteratorConstructor;
};
var aPossiblePrototype = function (it) {
if (!isObject(it) && it !== null) {
throw TypeError("Can't set " + String(it) + ' as a prototype');
} return it;
};
// `Object.setPrototypeOf` method
// https://tc39.github.io/ecma262/#sec-object.setprototypeof
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
var CORRECT_SETTER = false;
var test = {};
var setter;
try {
setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
setter.call(test, []);
CORRECT_SETTER = test instanceof Array;
} catch (error) { /* empty */ }
return function setPrototypeOf(O, proto) {
anObject(O);
aPossiblePrototype(proto);
if (CORRECT_SETTER) setter.call(O, proto);
else O.__proto__ = proto;
return O;
};
}() : undefined);
var IteratorPrototype$2 = iteratorsCore.IteratorPrototype;
var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS;
var ITERATOR$1 = wellKnownSymbol('iterator');
var KEYS = 'keys';
var VALUES = 'values';
var ENTRIES = 'entries';
var returnThis$1 = function () { return this; };
var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
createIteratorConstructor(IteratorConstructor, NAME, next);
var getIterationMethod = function (KIND) {
if (KIND === DEFAULT && defaultIterator) return defaultIterator;
if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND];
switch (KIND) {
case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
} return function () { return new IteratorConstructor(this); };
};
var TO_STRING_TAG = NAME + ' Iterator';
var INCORRECT_VALUES_NAME = false;
var IterablePrototype = Iterable.prototype;
var nativeIterator = IterablePrototype[ITERATOR$1]
|| IterablePrototype['@@iterator']
|| DEFAULT && IterablePrototype[DEFAULT];
var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT);
var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
var CurrentIteratorPrototype, methods, KEY;
// fix native
if (anyNativeIterator) {
CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) {
if ( objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) {
if (objectSetPrototypeOf) {
objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2);
} else if (typeof CurrentIteratorPrototype[ITERATOR$1] != 'function') {
hide(CurrentIteratorPrototype, ITERATOR$1, returnThis$1);
}
}
// Set @@toStringTag to native iterators
setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
INCORRECT_VALUES_NAME = true;
defaultIterator = function values() { return nativeIterator.call(this); };
}
// define iterator
if ( IterablePrototype[ITERATOR$1] !== defaultIterator) {
hide(IterablePrototype, ITERATOR$1, defaultIterator);
}
// export additional methods
if (DEFAULT) {
methods = {
values: getIterationMethod(VALUES),
keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
entries: getIterationMethod(ENTRIES)
};
if (FORCED) for (KEY in methods) {
if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
redefine(IterablePrototype, KEY, methods[KEY]);
}
} else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods);
}
return methods;
};
var ARRAY_ITERATOR = 'Array Iterator';
var setInternalState$1 = internalState.set;
var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR);
// `Array.prototype.entries` method
// https://tc39.github.io/ecma262/#sec-array.prototype.entries
// `Array.prototype.keys` method
// https://tc39.github.io/ecma262/#sec-array.prototype.keys
// `Array.prototype.values` method
// https://tc39.github.io/ecma262/#sec-array.prototype.values
// `Array.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
// `CreateArrayIterator` internal method
// https://tc39.github.io/ecma262/#sec-createarrayiterator
var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) {
setInternalState$1(this, {
type: ARRAY_ITERATOR,
target: toIndexedObject(iterated), // target
index: 0, // next index
kind: kind // kind
});
// `%ArrayIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
}, function () {
var state = getInternalState$1(this);
var target = state.target;
var kind = state.kind;
var index = state.index++;
if (!target || index >= target.length) {
state.target = undefined;
return { value: undefined, done: true };
}
if (kind == 'keys') return { value: index, done: false };
if (kind == 'values') return { value: target[index], done: false };
return { value: [index, target[index]], done: false };
}, 'values');
// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
var nativeJoin = [].join;
var ES3_STRINGS = indexedObject != Object;
var SLOPPY_METHOD$1 = sloppyArrayMethod('join', ',');
// `Array.prototype.join` method
// https://tc39.github.io/ecma262/#sec-array.prototype.join
_export({ target: 'Array', proto: true, forced: ES3_STRINGS || SLOPPY_METHOD$1 }, {
join: function join(separator) {
return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
}
});
var SPECIES$2 = wellKnownSymbol('species');
var nativeSlice = [].slice;
var max$1 = Math.max;
// `Array.prototype.slice` method
// https://tc39.github.io/ecma262/#sec-array.prototype.slice
// fallback for not array-like ES3 strings and DOM objects
_export({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, {
slice: function slice(start, end) {
var O = toIndexedObject(this);
var length = toLength(O.length);
var k = toAbsoluteIndex(start, length);
var fin = toAbsoluteIndex(end === undefined ? length : end, length);
// inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
var Constructor, result, n;
if (isArray(O)) {
Constructor = O.constructor;
// cross-realm fallback
if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
Constructor = undefined;
} else if (isObject(Constructor)) {
Constructor = Constructor[SPECIES$2];
if (Constructor === null) Constructor = undefined;
}
if (Constructor === Array || Constructor === undefined) {
return nativeSlice.call(O, k, fin);
}
}
result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0));
for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
result.length = n;
return result;
}
});
var nativeSort = [].sort;
var test = [1, 2, 3];
// IE8-
var FAILS_ON_UNDEFINED = fails(function () {
test.sort(undefined);
});
// V8 bug
var FAILS_ON_NULL = fails(function () {
test.sort(null);
});
// Old WebKit
var SLOPPY_METHOD$2 = sloppyArrayMethod('sort');
var FORCED$1 = FAILS_ON_UNDEFINED || !FAILS_ON_NULL || SLOPPY_METHOD$2;
// `Array.prototype.sort` method
// https://tc39.github.io/ecma262/#sec-array.prototype.sort
_export({ target: 'Array', proto: true, forced: FORCED$1 }, {
sort: function sort(comparefn) {
return comparefn === undefined
? nativeSort.call(toObject(this))
: nativeSort.call(toObject(this), aFunction$1(comparefn));
}
});
var max$2 = Math.max;
var min$2 = Math.min;
var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF;
var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded';
// `Array.prototype.splice` method
// https://tc39.github.io/ecma262/#sec-array.prototype.splice
// with adding support of @@species
_export({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('splice') }, {
splice: function splice(start, deleteCount /* , ...items */) {
var O = toObject(this);
var len = toLength(O.length);
var actualStart = toAbsoluteIndex(start, len);
var argumentsLength = arguments.length;
var insertCount, actualDeleteCount, A, k, from, to;
if (argumentsLength === 0) {
insertCount = actualDeleteCount = 0;
} else if (argumentsLength === 1) {
insertCount = 0;
actualDeleteCount = len - actualStart;
} else {
insertCount = argumentsLength - 2;
actualDeleteCount = min$2(max$2(toInteger(deleteCount), 0), len - actualStart);
}
if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER$1) {
throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);
}
A = arraySpeciesCreate(O, actualDeleteCount);
for (k = 0; k < actualDeleteCount; k++) {
from = actualStart + k;
if (from in O) createProperty(A, k, O[from]);
}
A.length = actualDeleteCount;
if (insertCount < actualDeleteCount) {
for (k = actualStart; k < len - actualDeleteCount; k++) {
from = k + actualDeleteCount;
to = k + insertCount;
if (from in O) O[to] = O[from];
else delete O[to];
}
for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];
} else if (insertCount > actualDeleteCount) {
for (k = len - actualDeleteCount; k > actualStart; k--) {
from = k + actualDeleteCount - 1;
to = k + insertCount - 1;
if (from in O) O[to] = O[from];
else delete O[to];
}
}
for (k = 0; k < insertCount; k++) {
O[k + actualStart] = arguments[k + 2];
}
O.length = len - actualDeleteCount + insertCount;
return A;
}
});
// makes subclassing work correct for wrapped built-ins
var inheritIfRequired = function ($this, dummy, Wrapper) {
var NewTarget, NewTargetPrototype;
if (
// it can work only with native `setPrototypeOf`
objectSetPrototypeOf &&
// we haven't completely correct pre-ES6 way for getting `new.target`, so use this
typeof (NewTarget = dummy.constructor) == 'function' &&
NewTarget !== Wrapper &&
isObject(NewTargetPrototype = NewTarget.prototype) &&
NewTargetPrototype !== Wrapper.prototype
) objectSetPrototypeOf($this, NewTargetPrototype);
return $this;
};
// a string of all valid unicode whitespaces
// eslint-disable-next-line max-len
var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
var whitespace = '[' + whitespaces + ']';
var ltrim = RegExp('^' + whitespace + whitespace + '*');
var rtrim = RegExp(whitespace + whitespace + '*$');
// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
var createMethod$2 = function (TYPE) {
return function ($this) {
var string = String(requireObjectCoercible($this));
if (TYPE & 1) string = string.replace(ltrim, '');
if (TYPE & 2) string = string.replace(rtrim, '');
return string;
};
};
var stringTrim = {
// `String.prototype.{ trimLeft, trimStart }` methods
// https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
start: createMethod$2(1),
// `String.prototype.{ trimRight, trimEnd }` methods
// https://tc39.github.io/ecma262/#sec-string.prototype.trimend
end: createMethod$2(2),
// `String.prototype.trim` method
// https://tc39.github.io/ecma262/#sec-string.prototype.trim
trim: createMethod$2(3)
};
var getOwnPropertyNames = objectGetOwnPropertyNames.f;
var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f;
var defineProperty$3 = objectDefineProperty.f;
var trim = stringTrim.trim;
var NUMBER = 'Number';
var NativeNumber = global_1[NUMBER];
var NumberPrototype = NativeNumber.prototype;
// Opera ~12 has broken Object#toString
var BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER;
// `ToNumber` abstract operation
// https://tc39.github.io/ecma262/#sec-tonumber
var toNumber = function (argument) {
var it = toPrimitive(argument, false);
var first, third, radix, maxCode, digits, length, index, code;
if (typeof it == 'string' && it.length > 2) {
it = trim(it);
first = it.charCodeAt(0);
if (first === 43 || first === 45) {
third = it.charCodeAt(2);
if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if (first === 48) {
switch (it.charCodeAt(1)) {
case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i
case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i
default: return +it;
}
digits = it.slice(2);
length = digits.length;
for (index = 0; index < length; index++) {
code = digits.charCodeAt(index);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if (code < 48 || code > maxCode) return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
// `Number` constructor
// https://tc39.github.io/ecma262/#sec-number-constructor
if (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {
var NumberWrapper = function Number(value) {
var it = arguments.length < 1 ? 0 : value;
var dummy = this;
return dummy instanceof NumberWrapper
// check on 1..constructor(foo) case
&& (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER)
? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);
};
for (var keys$1 = descriptors ? getOwnPropertyNames(NativeNumber) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES2015 (in case, if modules with ES2015 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys$1.length > j; j++) {
if (has(NativeNumber, key = keys$1[j]) && !has(NumberWrapper, key)) {
defineProperty$3(NumberWrapper, key, getOwnPropertyDescriptor$2(NativeNumber, key));
}
}
NumberWrapper.prototype = NumberPrototype;
NumberPrototype.constructor = NumberWrapper;
redefine(global_1, NUMBER, NumberWrapper);
}
var nativeAssign = Object.assign;
// `Object.assign` method
// https://tc39.github.io/ecma262/#sec-object.assign
// should work with symbols and should have deterministic property order (V8 bug)
var objectAssign = !nativeAssign || fails(function () {
var A = {};
var B = {};
// eslint-disable-next-line no-undef
var symbol = Symbol();
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
}) ? function assign(target, source) { // eslint-disable-line no-unused-vars
var T = toObject(target);
var argumentsLength = arguments.length;
var index = 1;
var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
var propertyIsEnumerable = objectPropertyIsEnumerable.f;
while (argumentsLength > index) {
var S = indexedObject(arguments[index++]);
var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
var length = keys.length;
var j = 0;
var key;
while (length > j) {
key = keys[j++];
if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key];
}
} return T;
} : nativeAssign;
// `Object.assign` method
// https://tc39.github.io/ecma262/#sec-object.assign
_export({ target: 'Object', stat: true, forced: Object.assign !== objectAssign }, {
assign: objectAssign
});
var propertyIsEnumerable = objectPropertyIsEnumerable.f;
// `Object.{ entries, values }` methods implementation
var createMethod$3 = function (TO_ENTRIES) {
return function (it) {
var O = toIndexedObject(it);
var keys = objectKeys(O);
var length = keys.length;
var i = 0;
var result = [];
var key;
while (length > i) {
key = keys[i++];
if (!descriptors || propertyIsEnumerable.call(O, key)) {
result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
}
}
return result;
};
};
var objectToArray = {
// `Object.entries` method
// https://tc39.github.io/ecma262/#sec-object.entries
entries: createMethod$3(true),
// `Object.values` method
// https://tc39.github.io/ecma262/#sec-object.values
values: createMethod$3(false)
};
var $entries = objectToArray.entries;
// `Object.entries` method
// https://tc39.github.io/ecma262/#sec-object.entries
_export({ target: 'Object', stat: true }, {
entries: function entries(O) {
return $entries(O);
}
});
var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
// ES3 wrong here
var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function (it, key) {
try {
return it[key];
} catch (error) { /* empty */ }
};
// getting tag from ES6+ `Object.prototype.toString`
var classof = function (it) {
var O, tag, result;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$1)) == 'string' ? tag
// builtinTag case
: CORRECT_ARGUMENTS ? classofRaw(O)
// ES3 arguments fallback
: (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
};
var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
var test$1 = {};
test$1[TO_STRING_TAG$2] = 'z';
// `Object.prototype.toString` method implementation
// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
var objectToString = String(test$1) !== '[object z]' ? function toString() {
return '[object ' + classof(this) + ']';
} : test$1.toString;
var ObjectPrototype$2 = Object.prototype;
// `Object.prototype.toString` method
// https://tc39.github.io/ecma262/#sec-object.prototype.tostring
if (objectToString !== ObjectPrototype$2.toString) {
redefine(ObjectPrototype$2, 'toString', objectToString, { unsafe: true });
}
var trim$1 = stringTrim.trim;
var nativeParseFloat = global_1.parseFloat;
var FORCED$2 = 1 / nativeParseFloat(whitespaces + '-0') !== -Infinity;
// `parseFloat` method
// https://tc39.github.io/ecma262/#sec-parsefloat-string
var _parseFloat = FORCED$2 ? function parseFloat(string) {
var trimmedString = trim$1(String(string));
var result = nativeParseFloat(trimmedString);
return result === 0 && trimmedString.charAt(0) == '-' ? -0 : result;
} : nativeParseFloat;
// `parseFloat` method
// https://tc39.github.io/ecma262/#sec-parsefloat-string
_export({ global: true, forced: parseFloat != _parseFloat }, {
parseFloat: _parseFloat
});
var trim$2 = stringTrim.trim;
var nativeParseInt = global_1.parseInt;
var hex = /^[+-]?0[Xx]/;
var FORCED$3 = nativeParseInt(whitespaces + '08') !== 8 || nativeParseInt(whitespaces + '0x16') !== 22;
// `parseInt` method
// https://tc39.github.io/ecma262/#sec-parseint-string-radix
var _parseInt = FORCED$3 ? function parseInt(string, radix) {
var S = trim$2(String(string));
return nativeParseInt(S, (radix >>> 0) || (hex.test(S) ? 16 : 10));
} : nativeParseInt;
// `parseInt` method
// https://tc39.github.io/ecma262/#sec-parseint-string-radix
_export({ global: true, forced: parseInt != _parseInt }, {
parseInt: _parseInt
});
// `RegExp.prototype.flags` getter implementation
// https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
var regexpFlags = function () {
var that = anObject(this);
var result = '';
if (that.global) result += 'g';
if (that.ignoreCase) result += 'i';
if (that.multiline) result += 'm';
if (that.dotAll) result += 's';
if (that.unicode) result += 'u';
if (that.sticky) result += 'y';
return result;
};
var TO_STRING = 'toString';
var RegExpPrototype = RegExp.prototype;
var nativeToString = RegExpPrototype[TO_STRING];
var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });
// FF44- RegExp#toString has a wrong name
var INCORRECT_NAME = nativeToString.name != TO_STRING;
// `RegExp.prototype.toString` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype.tostring
if (NOT_GENERIC || INCORRECT_NAME) {
redefine(RegExp.prototype, TO_STRING, function toString() {
var R = anObject(this);
var p = String(R.source);
var rf = R.flags;
var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? regexpFlags.call(R) : rf);
return '/' + p + '/' + f;
}, { unsafe: true });
}
var MATCH = wellKnownSymbol('match');
// `IsRegExp` abstract operation
// https://tc39.github.io/ecma262/#sec-isregexp
var isRegexp = function (it) {
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp');
};
var notARegexp = function (it) {
if (isRegexp(it)) {
throw TypeError("The method doesn't accept regular expressions");
} return it;
};
var MATCH$1 = wellKnownSymbol('match');
var correctIsRegexpLogic = function (METHOD_NAME) {
var regexp = /./;
try {
'/./'[METHOD_NAME](regexp);
} catch (e) {
try {
regexp[MATCH$1] = false;
return '/./'[METHOD_NAME](regexp);
} catch (f) { /* empty */ }
} return false;
};
// `String.prototype.includes` method
// https://tc39.github.io/ecma262/#sec-string.prototype.includes
_export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, {
includes: function includes(searchString /* , position = 0 */) {
return !!~String(requireObjectCoercible(this))
.indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined);
}
});
// `String.prototype.{ codePointAt, at }` methods implementation
var createMethod$4 = function (CONVERT_TO_STRING) {
return function ($this, pos) {
var S = String(requireObjectCoercible($this));
var position = toInteger(pos);
var size = S.length;
var first, second;
if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
first = S.charCodeAt(position);
return first < 0xD800 || first > 0xDBFF || position + 1 === size
|| (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
? CONVERT_TO_STRING ? S.charAt(position) : first
: CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
};
};
var stringMultibyte = {
// `String.prototype.codePointAt` method
// https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
codeAt: createMethod$4(false),
// `String.prototype.at` method
// https://github.com/mathiasbynens/String.prototype.at
charAt: createMethod$4(true)
};
var charAt = stringMultibyte.charAt;
var STRING_ITERATOR = 'String Iterator';
var setInternalState$2 = internalState.set;
var getInternalState$2 = internalState.getterFor(STRING_ITERATOR);
// `String.prototype[@@iterator]` method
// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
defineIterator(String, 'String', function (iterated) {
setInternalState$2(this, {
type: STRING_ITERATOR,
string: String(iterated),
index: 0
});
// `%StringIteratorPrototype%.next` method
// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
}, function next() {
var state = getInternalState$2(this);
var string = state.string;
var index = state.index;
var point;
if (index >= string.length) return { value: undefined, done: true };
point = charAt(string, index);
state.index += point.length;
return { value: point, done: false };
});
var nativeExec = RegExp.prototype.exec;
// This always refers to the native implementation, because the
// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
// which loads this file before patching the method.
var nativeReplace = String.prototype.replace;
var patchedExec = nativeExec;
var UPDATES_LAST_INDEX_WRONG = (function () {
var re1 = /a/;
var re2 = /b*/g;
nativeExec.call(re1, 'a');
nativeExec.call(re2, 'a');
return re1.lastIndex !== 0 || re2.lastIndex !== 0;
})();
// nonparticipating capturing group, copied from es5-shim's String#split patch.
var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;
var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;
if (PATCH) {
patchedExec = function exec(str) {
var re = this;
var lastIndex, reCopy, match, i;
if (NPCG_INCLUDED) {
reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
}
if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;
match = nativeExec.call(re, str);
if (UPDATES_LAST_INDEX_WRONG && match) {
re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
}
if (NPCG_INCLUDED && match && match.length > 1) {
// Fix browsers whose `exec` methods don't consistently return `undefined`
// for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
nativeReplace.call(match[0], reCopy, function () {
for (i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) match[i] = undefined;
}
});
}
return match;
};
}
var regexpExec = patchedExec;
var SPECIES$3 = wellKnownSymbol('species');
var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
// #replace needs built-in support for named groups.
// #match works fine because it just return the exec results, even if it has
// a "grops" property.
var re = /./;
re.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(re, '$<a>') !== '7';
});
// Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
// Weex JS has frozen built-in prototypes, so use try / catch wrapper
var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
var re = /(?:)/;
var originalExec = re.exec;
re.exec = function () { return originalExec.apply(this, arguments); };
var result = 'ab'.split(re);
return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
});
var fixRegexpWellKnownSymbolLogic = function (KEY, length, exec, sham) {
var SYMBOL = wellKnownSymbol(KEY);
var DELEGATES_TO_SYMBOL = !fails(function () {
// String methods call symbol-named RegEp methods
var O = {};
O[SYMBOL] = function () { return 7; };
return ''[KEY](O) != 7;
});
var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
// Symbol-named RegExp methods call .exec
var execCalled = false;
var re = /a/;
re.exec = function () { execCalled = true; return null; };
if (KEY === 'split') {
// RegExp[@@split] doesn't call the regex's exec method, but first creates
// a new one. We need to return the patched regex when creating the new one.
re.constructor = {};
re.constructor[SPECIES$3] = function () { return re; };
}
re[SYMBOL]('');
return !execCalled;
});
if (
!DELEGATES_TO_SYMBOL ||
!DELEGATES_TO_EXEC ||
(KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
(KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
) {
var nativeRegExpMethod = /./[SYMBOL];
var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
if (regexp.exec === regexpExec) {
if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
// The native String method already delegates to @@method (this
// polyfilled function), leasing to infinite recursion.
// We avoid it by directly calling the native @@method method.
return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
}
return { done: true, value: nativeMethod.call(str, regexp, arg2) };
}
return { done: false };
});
var stringMethod = methods[0];
var regexMethod = methods[1];
redefine(String.prototype, KEY, stringMethod);
redefine(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function (string, arg) { return regexMethod.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function (string) { return regexMethod.call(string, this); }
);
if (sham) hide(RegExp.prototype[SYMBOL], 'sham', true);
}
};
var charAt$1 = stringMultibyte.charAt;
// `AdvanceStringIndex` abstract operation
// https://tc39.github.io/ecma262/#sec-advancestringindex
var advanceStringIndex = function (S, index, unicode) {
return index + (unicode ? charAt$1(S, index).length : 1);
};
// `RegExpExec` abstract operation
// https://tc39.github.io/ecma262/#sec-regexpexec
var regexpExecAbstract = function (R, S) {
var exec = R.exec;
if (typeof exec === 'function') {
var result = exec.call(R, S);
if (typeof result !== 'object') {
throw TypeError('RegExp exec method returned something other than an Object or null');
}
return result;
}
if (classofRaw(R) !== 'RegExp') {
throw TypeError('RegExp#exec called on incompatible receiver');
}
return regexpExec.call(R, S);
};
var max$3 = Math.max;
var min$3 = Math.min;
var floor$1 = Math.floor;
var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g;
var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g;
var maybeToString = function (it) {
return it === undefined ? it : String(it);
};
// @@replace logic
fixRegexpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative) {
return [
// `String.prototype.replace` method
// https://tc39.github.io/ecma262/#sec-string.prototype.replace
function replace(searchValue, replaceValue) {
var O = requireObjectCoercible(this);
var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
return replacer !== undefined
? replacer.call(searchValue, O, replaceValue)
: nativeReplace.call(String(O), searchValue, replaceValue);
},
// `RegExp.prototype[@@replace]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
function (regexp, replaceValue) {
var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var functionalReplace = typeof replaceValue === 'function';
if (!functionalReplace) replaceValue = String(replaceValue);
var global = rx.global;
if (global) {
var fullUnicode = rx.unicode;
rx.lastIndex = 0;
}
var results = [];
while (true) {
var result = regexpExecAbstract(rx, S);
if (result === null) break;
results.push(result);
if (!global) break;
var matchStr = String(result[0]);
if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
}
var accumulatedResult = '';
var nextSourcePosition = 0;
for (var i = 0; i < results.length; i++) {
result = results[i];
var matched = String(result[0]);
var position = max$3(min$3(toInteger(result.index), S.length), 0);
var captures = [];
// NOTE: This is equivalent to
// captures = result.slice(1).map(maybeToString)
// but for some reason `nativeSlice.call(result, 1, result.length)` (called in
// the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
// causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
var namedCaptures = result.groups;
if (functionalReplace) {
var replacerArgs = [matched].concat(captures, position, S);
if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
var replacement = String(replaceValue.apply(undefined, replacerArgs));
} else {
replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
}
if (position >= nextSourcePosition) {
accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
nextSourcePosition = position + matched.length;
}
}
return accumulatedResult + S.slice(nextSourcePosition);
}
];
// https://tc39.github.io/ecma262/#sec-getsubstitution
function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
var tailPos = position + matched.length;
var m = captures.length;
var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
if (namedCaptures !== undefined) {
namedCaptures = toObject(namedCaptures);
symbols = SUBSTITUTION_SYMBOLS;
}
return nativeReplace.call(replacement, symbols, function (match, ch) {
var capture;
switch (ch.charAt(0)) {
case '$': return '$';
case '&': return matched;
case '`': return str.slice(0, position);
case "'": return str.slice(tailPos);
case '<':
capture = namedCaptures[ch.slice(1, -1)];
break;
default: // \d\d?
var n = +ch;
if (n === 0) return match;
if (n > m) {
var f = floor$1(n / 10);
if (f === 0) return match;
if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
return match;
}
capture = captures[n - 1];
}
return capture === undefined ? '' : capture;
});
}
});
// `SameValue` abstract operation
// https://tc39.github.io/ecma262/#sec-samevalue
var sameValue = Object.is || function is(x, y) {
// eslint-disable-next-line no-self-compare
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
// @@search logic
fixRegexpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) {
return [
// `String.prototype.search` method
// https://tc39.github.io/ecma262/#sec-string.prototype.search
function search(regexp) {
var O = requireObjectCoercible(this);
var searcher = regexp == undefined ? undefined : regexp[SEARCH];
return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
},
// `RegExp.prototype[@@search]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
function (regexp) {
var res = maybeCallNative(nativeSearch, regexp, this);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var previousLastIndex = rx.lastIndex;
if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
var result = regexpExecAbstract(rx, S);
if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
return result === null ? -1 : result.index;
}
];
});
var SPECIES$4 = wellKnownSymbol('species');
// `SpeciesConstructor` abstract operation
// https://tc39.github.io/ecma262/#sec-speciesconstructor
var speciesConstructor = function (O, defaultConstructor) {
var C = anObject(O).constructor;
var S;
return C === undefined || (S = anObject(C)[SPECIES$4]) == undefined ? defaultConstructor : aFunction$1(S);
};
var arrayPush = [].push;
var min$4 = Math.min;
var MAX_UINT32 = 0xFFFFFFFF;
// babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); });
// @@split logic
fixRegexpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {
var internalSplit;
if (
'abbc'.split(/(b)*/)[1] == 'c' ||
'test'.split(/(?:)/, -1).length != 4 ||
'ab'.split(/(?:ab)*/).length != 2 ||
'.'.split(/(.?)(.?)/).length != 4 ||
'.'.split(/()()/).length > 1 ||
''.split(/.?/).length
) {
// based on es5-shim implementation, need to rework it
internalSplit = function (separator, limit) {
var string = String(requireObjectCoercible(this));
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
if (lim === 0) return [];
if (separator === undefined) return [string];
// If `separator` is not a regex, use native split
if (!isRegexp(separator)) {
return nativeSplit.call(string, separator, lim);
}
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var match, lastIndex, lastLength;
while (match = regexpExec.call(separatorCopy, string)) {
lastIndex = separatorCopy.lastIndex;
if (lastIndex > lastLastIndex) {
output.push(string.slice(lastLastIndex, match.index));
if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= lim) break;
}
if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
}
if (lastLastIndex === string.length) {
if (lastLength || !separatorCopy.test('')) output.push('');
} else output.push(string.slice(lastLastIndex));
return output.length > lim ? output.slice(0, lim) : output;
};
// Chakra, V8
} else if ('0'.split(undefined, 0).length) {
internalSplit = function (separator, limit) {
return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
};
} else internalSplit = nativeSplit;
return [
// `String.prototype.split` method
// https://tc39.github.io/ecma262/#sec-string.prototype.split
function split(separator, limit) {
var O = requireObjectCoercible(this);
var splitter = separator == undefined ? undefined : separator[SPLIT];
return splitter !== undefined
? splitter.call(separator, O, limit)
: internalSplit.call(String(O), separator, limit);
},
// `RegExp.prototype[@@split]` method
// https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
//
// NOTE: This cannot be properly polyfilled in engines that don't support
// the 'y' flag.
function (regexp, limit) {
var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);
if (res.done) return res.value;
var rx = anObject(regexp);
var S = String(this);
var C = speciesConstructor(rx, RegExp);
var unicodeMatching = rx.unicode;
var flags = (rx.ignoreCase ? 'i' : '') +
(rx.multiline ? 'm' : '') +
(rx.unicode ? 'u' : '') +
(SUPPORTS_Y ? 'y' : 'g');
// ^(? + rx + ) is needed, in combination with some S slicing, to
// simulate the 'y' flag.
var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
if (lim === 0) return [];
if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : [];
var p = 0;
var q = 0;
var A = [];
while (q < S.length) {
splitter.lastIndex = SUPPORTS_Y ? q : 0;
var z = regexpExecAbstract(splitter, SUPPORTS_Y ? S : S.slice(q));
var e;
if (
z === null ||
(e = min$4(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p
) {
q = advanceStringIndex(S, q, unicodeMatching);
} else {
A.push(S.slice(p, q));
if (A.length === lim) return A;
for (var i = 1; i <= z.length - 1; i++) {
A.push(z[i]);
if (A.length === lim) return A;
}
q = p = e;
}
}
A.push(S.slice(p));
return A;
}
];
}, !SUPPORTS_Y);
var non = '\u200B\u0085\u180E';
// check that a method works with the correct list
// of whitespaces and has a correct name
var forcedStringTrimMethod = function (METHOD_NAME) {
return fails(function () {
return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;
});
};
var $trim = stringTrim.trim;
// `String.prototype.trim` method
// https://tc39.github.io/ecma262/#sec-string.prototype.trim
_export({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, {
trim: function trim() {
return $trim(this);
}
});
// iterable DOM collections
// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
var domIterables = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
var $forEach$1 = arrayIteration.forEach;
// `Array.prototype.forEach` method implementation
// https://tc39.github.io/ecma262/#sec-array.prototype.foreach
var arrayForEach = sloppyArrayMethod('forEach') ? function forEach(callbackfn /* , thisArg */) {
return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
} : [].forEach;
for (var COLLECTION_NAME in domIterables) {
var Collection = global_1[COLLECTION_NAME];
var CollectionPrototype = Collection && Collection.prototype;
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try {
hide(CollectionPrototype, 'forEach', arrayForEach);
} catch (error) {
CollectionPrototype.forEach = arrayForEach;
}
}
var ITERATOR$2 = wellKnownSymbol('iterator');
var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag');
var ArrayValues = es_array_iterator.values;
for (var COLLECTION_NAME$1 in domIterables) {
var Collection$1 = global_1[COLLECTION_NAME$1];
var CollectionPrototype$1 = Collection$1 && Collection$1.prototype;
if (CollectionPrototype$1) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype$1[ITERATOR$2] !== ArrayValues) try {
hide(CollectionPrototype$1, ITERATOR$2, ArrayValues);
} catch (error) {
CollectionPrototype$1[ITERATOR$2] = ArrayValues;
}
if (!CollectionPrototype$1[TO_STRING_TAG$3]) hide(CollectionPrototype$1, TO_STRING_TAG$3, COLLECTION_NAME$1);
if (domIterables[COLLECTION_NAME$1]) for (var METHOD_NAME in es_array_iterator) {
// some Chrome versions have non-configurable methods on DOMTokenList
if (CollectionPrototype$1[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try {
hide(CollectionPrototype$1, METHOD_NAME, es_array_iterator[METHOD_NAME]);
} catch (error) {
CollectionPrototype$1[METHOD_NAME] = es_array_iterator[METHOD_NAME];
}
}
}
}
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a 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);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
var VERSION = '1.15.3';
var bootstrapVersion = 4;
try {
var rawVersion = $.fn.dropdown.Constructor.VERSION; // Only try to parse VERSION if it is defined.
// It is undefined in older versions of Bootstrap (tested with 3.1.1).
if (rawVersion !== undefined) {
bootstrapVersion = parseInt(rawVersion, 10);
}
} catch (e) {// ignore
}
var CONSTANTS = {
3: {
iconsPrefix: 'glyphicon',
icons: {
paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
refresh: 'glyphicon-refresh icon-refresh',
toggleOff: 'glyphicon-list-alt icon-list-alt',
toggleOn: 'glyphicon-list-alt icon-list-alt',
columns: 'glyphicon-th icon-th',
detailOpen: 'glyphicon-plus icon-plus',
detailClose: 'glyphicon-minus icon-minus',
fullscreen: 'glyphicon-fullscreen',
search: 'glyphicon-search',
clearSearch: 'glyphicon-trash'
},
classes: {
buttonsPrefix: 'btn',
buttons: 'default',
buttonsGroup: 'btn-group',
buttonsDropdown: 'btn-group',
pull: 'pull',
inputGroup: 'input-group',
input: 'form-control',
paginationDropdown: 'btn-group dropdown',
dropup: 'dropup',
dropdownActive: 'active',
paginationActive: 'active',
buttonActive: 'active'
},
html: {
toolbarDropdown: ['<ul class="dropdown-menu" role="menu">', '</ul>'],
toolbarDropdownItem: '<li role="menuitem"><label>%s</label></li>',
toolbarDropdownSeperator: '<li class="divider"></li>',
pageDropdown: ['<ul class="dropdown-menu" role="menu">', '</ul>'],
pageDropdownItem: '<li role="menuitem" class="%s"><a href="#">%s</a></li>',
dropdownCaret: '<span class="caret"></span>',
pagination: ['<ul class="pagination%s">', '</ul>'],
paginationItem: '<li class="page-item%s"><a class="page-link" aria-label="%s" href="javascript:void(0)">%s</a></li>',
icon: '<i class="%s %s"></i>',
inputGroup: '<div class="input-group">%s<span class="input-group-btn">%s</span></div>',
searchInput: '<input class="%s%s" type="text" placeholder="%s">',
searchButton: '<button class="btn btn-default" type="button" name="search" title="%s">%s %s</button>',
searchClearButton: '<button class="btn btn-default" type="button" name="clearSearch" title="%s">%s %s</button>'
}
},
4: {
iconsPrefix: 'fa',
icons: {
paginationSwitchDown: 'fa-caret-square-down',
paginationSwitchUp: 'fa-caret-square-up',
refresh: 'fa-sync',
toggleOff: 'fa-toggle-off',
toggleOn: 'fa-toggle-on',
columns: 'fa-th-list',
detailOpen: 'fa-plus',
detailClose: 'fa-minus',
fullscreen: 'fa-arrows-alt',
search: 'fa-search',
clearSearch: 'fa-trash'
},
classes: {
buttonsPrefix: 'btn',
buttons: 'secondary',
buttonsGroup: 'btn-group',
buttonsDropdown: 'btn-group',
pull: 'float',
inputGroup: 'btn-group',
input: 'form-control',
paginationDropdown: 'btn-group dropdown',
dropup: 'dropup',
dropdownActive: 'active',
paginationActive: 'active',
buttonActive: 'active'
},
html: {
toolbarDropdown: ['<div class="dropdown-menu dropdown-menu-right">', '</div>'],
toolbarDropdownItem: '<label class="dropdown-item">%s</label>',
pageDropdown: ['<div class="dropdown-menu">', '</div>'],
pageDropdownItem: '<a class="dropdown-item %s" href="#">%s</a>',
toolbarDropdownSeperator: '<div class="dropdown-divider"></div>',
dropdownCaret: '<span class="caret"></span>',
pagination: ['<ul class="pagination%s">', '</ul>'],
paginationItem: '<li class="page-item%s"><a class="page-link" aria-label="%s" href="javascript:void(0)">%s</a></li>',
icon: '<i class="%s %s"></i>',
inputGroup: '<div class="input-group">%s<div class="input-group-append">%s</div></div>',
searchInput: '<input class="%s%s" type="text" placeholder="%s">',
searchButton: '<button class="btn btn-secondary" type="button" name="search" title="%s">%s %s</button>',
searchClearButton: '<button class="btn btn-secondary" type="button" name="clearSearch" title="%s">%s %s</button>'
}
}
}[bootstrapVersion];
var DEFAULTS = {
height: undefined,
classes: 'table table-bordered table-hover',
theadClasses: '',
rowStyle: function rowStyle(row, index) {
return {};
},
rowAttributes: function rowAttributes(row, index) {
return {};
},
undefinedText: '-',
locale: undefined,
virtualScroll: false,
virtualScrollItemHeight: undefined,
sortable: true,
sortClass: undefined,
silentSort: true,
sortName: undefined,
sortOrder: 'asc',
sortStable: false,
rememberOrder: false,
customSort: undefined,
columns: [[]],
data: [],
url: undefined,
method: 'get',
cache: true,
contentType: 'application/json',
dataType: 'json',
ajax: undefined,
ajaxOptions: {},
queryParams: function queryParams(params) {
return params;
},
queryParamsType: 'limit',
// 'limit', undefined
responseHandler: function responseHandler(res) {
return res;
},
totalField: 'total',
totalNotFilteredField: 'totalNotFiltered',
dataField: 'rows',
pagination: false,
onlyInfoPagination: false,
showExtendedPagination: false,
paginationLoop: true,
sidePagination: 'client',
// client or server
totalRows: 0,
totalNotFiltered: 0,
pageNumber: 1,
pageSize: 10,
pageList: [10, 25, 50, 100],
paginationHAlign: 'right',
// right, left
paginationVAlign: 'bottom',
// bottom, top, both
paginationDetailHAlign: 'left',
// right, left
paginationPreText: '‹',
paginationNextText: '›',
paginationSuccessivelySize: 5,
// Maximum successively number of pages in a row
paginationPagesBySide: 1,
// Number of pages on each side (right, left) of the current page.
paginationUseIntermediate: false,
// Calculate intermediate pages for quick access
search: false,
searchOnEnterKey: false,
strictSearch: false,
visibleSearch: false,
showButtonIcons: true,
showButtonText: false,
showSearchButton: false,
showSearchClearButton: false,
trimOnSearch: true,
searchAlign: 'right',
searchTimeOut: 500,
searchText: '',
customSearch: undefined,
showHeader: true,
showFooter: false,
footerStyle: function footerStyle(row, index) {
return {};
},
showColumns: false,
showColumnsToggleAll: false,
minimumCountColumns: 1,
showPaginationSwitch: false,
showRefresh: false,
showToggle: false,
showFullscreen: false,
smartDisplay: true,
escape: false,
filterOptions: {
filterAlgorithm: 'and'
},
idField: undefined,
selectItemName: 'btSelectItem',
clickToSelect: false,
ignoreClickToSelectOn: function ignoreClickToSelectOn(_ref) {
var tagName = _ref.tagName;
return ['A', 'BUTTON'].includes(tagName);
},
singleSelect: false,
checkboxHeader: true,
maintainMetaData: false,
multipleSelectRow: false,
uniqueId: undefined,
cardView: false,
detailView: false,
detailViewIcon: true,
detailViewByClick: false,
detailFormatter: function detailFormatter(index, row) {
return '';
},
detailFilter: function detailFilter(index, row) {
return true;
},
toolbar: undefined,
toolbarAlign: 'left',
buttonsToolbar: undefined,
buttonsAlign: 'right',
buttonsPrefix: CONSTANTS.classes.buttonsPrefix,
buttonsClass: CONSTANTS.classes.buttons,
icons: CONSTANTS.icons,
html: CONSTANTS.html,
iconSize: undefined,
iconsPrefix: CONSTANTS.iconsPrefix,
// glyphicon or fa(font-awesome)
onAll: function onAll(name, args) {
return false;
},
onClickCell: function onClickCell(field, value, row, $element) {
return false;
},
onDblClickCell: function onDblClickCell(field, value, row, $element) {
return false;
},
onClickRow: function onClickRow(item, $element) {
return false;
},
onDblClickRow: function onDblClickRow(item, $element) {
return false;
},
onSort: function onSort(name, order) {
return false;
},
onCheck: function onCheck(row) {
return false;
},
onUncheck: function onUncheck(row) {
return false;
},
onCheckAll: function onCheckAll(rows) {
return false;
},
onUncheckAll: function onUncheckAll(rows) {
return false;
},
onCheckSome: function onCheckSome(rows) {
return false;
},
onUncheckSome: function onUncheckSome(rows) {
return false;
},
onLoadSuccess: function onLoadSuccess(data) {
return false;
},
onLoadError: function onLoadError(status) {
return false;
},
onColumnSwitch: function onColumnSwitch(field, checked) {
return false;
},
onPageChange: function onPageChange(number, size) {
return false;
},
onSearch: function onSearch(text) {
return false;
},
onToggle: function onToggle(cardView) {
return false;
},
onPreBody: function onPreBody(data) {
return false;
},
onPostBody: function onPostBody() {
return false;
},
onPostHeader: function onPostHeader() {
return false;
},
onPostFooter: function onPostFooter() {
return false;
},
onExpandRow: function onExpandRow(index, row, $detail) {
return false;
},
onCollapseRow: function onCollapseRow(index, row) {
return false;
},
onRefreshOptions: function onRefreshOptions(options) {
return false;
},
onRefresh: function onRefresh(params) {
return false;
},
onResetView: function onResetView() {
return false;
},
onScrollBody: function onScrollBody() {
return false;
}
};
var EN = {
formatLoadingMessage: function formatLoadingMessage() {
return 'Loading, please wait';
},
formatRecordsPerPage: function formatRecordsPerPage(pageNumber) {
return "".concat(pageNumber, " rows per page");
},
formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows, totalNotFiltered) {
if (totalNotFiltered !== undefined && totalNotFiltered > 0 && totalNotFiltered > totalRows) {
return "Showing ".concat(pageFrom, " to ").concat(pageTo, " of ").concat(totalRows, " rows (filtered from ").concat(totalNotFiltered, " total rows)");
}
return "Showing ".concat(pageFrom, " to ").concat(pageTo, " of ").concat(totalRows, " rows");
},
formatSRPaginationPreText: function formatSRPaginationPreText() {
return 'previous page';
},
formatSRPaginationPageText: function formatSRPaginationPageText(page) {
return "to page ".concat(page);
},
formatSRPaginationNextText: function formatSRPaginationNextText() {
return 'next page';
},
formatDetailPagination: function formatDetailPagination(totalRows) {
return "Showing ".concat(totalRows, " rows");
},
formatSearch: function formatSearch() {
return 'Search';
},
formatClearSearch: function formatClearSearch() {
return 'Clear Search';
},
formatNoMatches: function formatNoMatches() {
return 'No matching records found';
},
formatPaginationSwitch: function formatPaginationSwitch() {
return 'Hide/Show pagination';
},
formatPaginationSwitchDown: function formatPaginationSwitchDown() {
return 'Show pagination';
},
formatPaginationSwitchUp: function formatPaginationSwitchUp() {
return 'Hide pagination';
},
formatRefresh: function formatRefresh() {
return 'Refresh';
},
formatToggle: function formatToggle() {
return 'Toggle';
},
formatToggleOn: function formatToggleOn() {
return 'Show card view';
},
formatToggleOff: function formatToggleOff() {
return 'Hide card view';
},
formatColumns: function formatColumns() {
return 'Columns';
},
formatColumnsToggleAll: function formatColumnsToggleAll() {
return 'Toggle all';
},
formatFullscreen: function formatFullscreen() {
return 'Fullscreen';
},
formatAllRows: function formatAllRows() {
return 'All';
}
};
var COLUMN_DEFAULTS = {
field: undefined,
title: undefined,
titleTooltip: undefined,
'class': undefined,
width: undefined,
widthUnit: 'px',
rowspan: undefined,
colspan: undefined,
align: undefined,
// left, right, center
halign: undefined,
// left, right, center
falign: undefined,
// left, right, center
valign: undefined,
// top, middle, bottom
cellStyle: undefined,
radio: false,
checkbox: false,
checkboxEnabled: true,
clickToSelect: true,
showSelectTitle: false,
sortable: false,
sortName: undefined,
order: 'asc',
// asc, desc
sorter: undefined,
visible: true,
switchable: true,
cardVisible: true,
searchable: true,
formatter: undefined,
footerFormatter: undefined,
detailFormatter: undefined,
searchFormatter: true,
escape: false,
events: undefined
};
var METHODS = ['getOptions', 'refreshOptions', 'getData', 'getSelections', 'getAllSelections', 'load', 'append', 'prepend', 'remove', 'removeAll', 'insertRow', 'updateRow', 'getRowByUniqueId', 'updateByUniqueId', 'removeByUniqueId', 'updateCell', 'updateCellByUniqueId', 'showRow', 'hideRow', 'getHiddenRows', 'showColumn', 'hideColumn', 'getVisibleColumns', 'getHiddenColumns', 'showAllColumns', 'hideAllColumns', 'mergeCells', 'checkAll', 'uncheckAll', 'checkInvert', 'check', 'uncheck', 'checkBy', 'uncheckBy', 'refresh', 'destroy', 'resetView', 'resetWidth', 'showLoading', 'hideLoading', 'togglePagination', 'toggleFullscreen', 'toggleView', 'resetSearch', 'filterBy', 'scrollTo', 'getScrollPosition', 'selectPage', 'prevPage', 'nextPage', 'toggleDetailView', 'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows', 'updateColumnTitle', 'updateFormatText'];
var EVENTS = {
'all.bs.table': 'onAll',
'click-row.bs.table': 'onClickRow',
'dbl-click-row.bs.table': 'onDblClickRow',
'click-cell.bs.table': 'onClickCell',
'dbl-click-cell.bs.table': 'onDblClickCell',
'sort.bs.table': 'onSort',
'check.bs.table': 'onCheck',
'uncheck.bs.table': 'onUncheck',
'check-all.bs.table': 'onCheckAll',
'uncheck-all.bs.table': 'onUncheckAll',
'check-some.bs.table': 'onCheckSome',
'uncheck-some.bs.table': 'onUncheckSome',
'load-success.bs.table': 'onLoadSuccess',
'load-error.bs.table': 'onLoadError',
'column-switch.bs.table': 'onColumnSwitch',
'page-change.bs.table': 'onPageChange',
'search.bs.table': 'onSearch',
'toggle.bs.table': 'onToggle',
'pre-body.bs.table': 'onPreBody',
'post-body.bs.table': 'onPostBody',
'post-header.bs.table': 'onPostHeader',
'post-footer.bs.table': 'onPostFooter',
'expand-row.bs.table': 'onExpandRow',
'collapse-row.bs.table': 'onCollapseRow',
'refresh-options.bs.table': 'onRefreshOptions',
'reset-view.bs.table': 'onResetView',
'refresh.bs.table': 'onRefresh',
'scroll-body.bs.table': 'onScrollBody'
};
Object.assign(DEFAULTS, EN);
var Constants = {
VERSION: VERSION,
THEME: "bootstrap".concat(bootstrapVersion),
CONSTANTS: CONSTANTS,
DEFAULTS: DEFAULTS,
COLUMN_DEFAULTS: COLUMN_DEFAULTS,
METHODS: METHODS,
EVENTS: EVENTS,
LOCALES: {
en: EN,
'en-US': EN
}
};
// `FlattenIntoArray` abstract operation
// https://tc39.github.io/proposal-flatMap/#sec-FlattenIntoArray
var flattenIntoArray = function (target, original, source, sourceLen, start, depth, mapper, thisArg) {
var targetIndex = start;
var sourceIndex = 0;
var mapFn = mapper ? bindContext(mapper, thisArg, 3) : false;
var element;
while (sourceIndex < sourceLen) {
if (sourceIndex in source) {
element = mapFn ? mapFn(source[sourceIndex], sourceIndex, original) : source[sourceIndex];
if (depth > 0 && isArray(element)) {
targetIndex = flattenIntoArray(target, original, element, toLength(element.length), targetIndex, depth - 1) - 1;
} else {
if (targetIndex >= 0x1FFFFFFFFFFFFF) throw TypeError('Exceed the acceptable array length');
target[targetIndex] = element;
}
targetIndex++;
}
sourceIndex++;
}
return targetIndex;
};
var flattenIntoArray_1 = flattenIntoArray;
// `Array.prototype.flat` method
// https://github.com/tc39/proposal-flatMap
_export({ target: 'Array', proto: true }, {
flat: function flat(/* depthArg = 1 */) {
var depthArg = arguments.length ? arguments[0] : undefined;
var O = toObject(this);
var sourceLen = toLength(O.length);
var A = arraySpeciesCreate(O, 0);
A.length = flattenIntoArray_1(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
return A;
}
});
// this method was added to unscopables after implementation
// in popular engines, so it's moved to a separate module
addToUnscopables('flat');
var FAILS_ON_PRIMITIVES = fails(function () { objectKeys(1); });
// `Object.keys` method
// https://tc39.github.io/ecma262/#sec-object.keys
_export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
keys: function keys(it) {
return objectKeys(toObject(it));
}
});
var Utils = {
// it only does '%s', and return '' when arguments are undefined
sprintf: function sprintf(_str) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var flag = true;
var i = 0;
var str = _str.replace(/%s/g, function () {
var arg = args[i++];
if (typeof arg === 'undefined') {
flag = false;
return '';
}
return arg;
});
return flag ? str : '';
},
isEmptyObject: function isEmptyObject() {
var obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return Object.entries(obj).length === 0 && obj.constructor === Object;
},
isNumeric: function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
},
getFieldTitle: function getFieldTitle(list, value) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var item = _step.value;
if (item.field === value) {
return item.title;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return '';
},
setFieldIndex: function setFieldIndex(columns) {
var totalCol = 0;
var flag = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = columns[0][Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var column = _step2.value;
totalCol += column.colspan || 1;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
for (var i = 0; i < columns.length; i++) {
flag[i] = [];
for (var j = 0; j < totalCol; j++) {
flag[i][j] = false;
}
}
for (var _i = 0; _i < columns.length; _i++) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = columns[_i][Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var r = _step3.value;
var rowspan = r.rowspan || 1;
var colspan = r.colspan || 1;
var index = flag[_i].indexOf(false);
r.colspanIndex = index;
if (colspan === 1) {
r.fieldIndex = index; // when field is undefined, use index instead
if (typeof r.field === 'undefined') {
r.field = index;
}
} else {
r.colspanGroup = r.colspan;
}
for (var k = 0; k < rowspan; k++) {
flag[_i + k][index] = true;
}
for (var _k = 0; _k < colspan; _k++) {
flag[_i][index + _k] = true;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
},
updateFieldGroup: function updateFieldGroup(columns) {
var allColumns = columns.flat();
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = columns[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var c = _step4.value;
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = c[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var r = _step5.value;
if (r.colspanGroup > 1) {
var colspan = 0;
var _loop = function _loop(i) {
var column = allColumns.find(function (col) {
return col.fieldIndex === i;
});
if (column.visible) {
colspan++;
}
};
for (var i = r.colspanIndex; i < r.colspanIndex + r.colspanGroup; i++) {
_loop(i);
}
r.colspan = colspan;
r.visible = colspan > 0;
}
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
},
getScrollBarWidth: function getScrollBarWidth() {
if (this.cachedWidth === undefined) {
var $inner = $('<div/>').addClass('fixed-table-scroll-inner');
var $outer = $('<div/>').addClass('fixed-table-scroll-outer');
$outer.append($inner);
$('body').append($outer);
var w1 = $inner[0].offsetWidth;
$outer.css('overflow', 'scroll');
var w2 = $inner[0].offsetWidth;
if (w1 === w2) {
w2 = $outer[0].clientWidth;
}
$outer.remove();
this.cachedWidth = w1 - w2;
}
return this.cachedWidth;
},
calculateObjectValue: function calculateObjectValue(self, name, args, defaultValue) {
var func = name;
if (typeof name === 'string') {
// support obj.func1.func2
var names = name.split('.');
if (names.length > 1) {
func = window;
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = names[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var f = _step6.value;
func = func[f];
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
} else {
func = window[name];
}
}
if (func !== null && _typeof(func) === 'object') {
return func;
}
if (typeof func === 'function') {
return func.apply(self, args || []);
}
if (!func && typeof name === 'string' && this.sprintf.apply(this, [name].concat(_toConsumableArray(args)))) {
return this.sprintf.apply(this, [name].concat(_toConsumableArray(args)));
}
return defaultValue;
},
compareObjects: function compareObjects(objectA, objectB, compareLength) {
var aKeys = Object.keys(objectA);
var bKeys = Object.keys(objectB);
if (compareLength && aKeys.length !== bKeys.length) {
return false;
}
for (var _i2 = 0, _aKeys = aKeys; _i2 < _aKeys.length; _i2++) {
var key = _aKeys[_i2];
if (bKeys.includes(key) && objectA[key] !== objectB[key]) {
return false;
}
}
return true;
},
escapeHTML: function escapeHTML(text) {
if (typeof text === 'string') {
return text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/`/g, '`');
}
return text;
},
getRealDataAttr: function getRealDataAttr(dataAttr) {
for (var _i3 = 0, _Object$entries = Object.entries(dataAttr); _i3 < _Object$entries.length; _i3++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i3], 2),
attr = _Object$entries$_i[0],
value = _Object$entries$_i[1];
var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase();
if (auxAttr !== attr) {
dataAttr[auxAttr] = value;
delete dataAttr[attr];
}
}
return dataAttr;
},
getItemField: function getItemField(item, field, escape) {
var value = item;
if (typeof field !== 'string' || item.hasOwnProperty(field)) {
return escape ? this.escapeHTML(item[field]) : item[field];
}
var props = field.split('.');
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = props[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var p = _step7.value;
value = value && value[p];
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
return escape ? this.escapeHTML(value) : value;
},
isIEBrowser: function isIEBrowser() {
return navigator.userAgent.includes('MSIE ') || /Trident.*rv:11\./.test(navigator.userAgent);
},
findIndex: function findIndex(items, item) {
var _iteratorNormalCompletion8 = true;
var _didIteratorError8 = false;
var _iteratorError8 = undefined;
try {
for (var _iterator8 = items[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
var it = _step8.value;
if (JSON.stringify(it) === JSON.stringify(item)) {
return items.indexOf(it);
}
}
} catch (err) {
_didIteratorError8 = true;
_iteratorError8 = err;
} finally {
try {
if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
_iterator8.return();
}
} finally {
if (_didIteratorError8) {
throw _iteratorError8;
}
}
}
return -1;
},
trToData: function trToData(columns, $els) {
var _this = this;
var data = [];
var m = [];
$els.each(function (y, el) {
var row = {}; // save tr's id, class and data-* attributes
row._id = $(el).attr('id');
row._class = $(el).attr('class');
row._data = _this.getRealDataAttr($(el).data());
$(el).find('>td,>th').each(function (_x, el) {
var cspan = +$(el).attr('colspan') || 1;
var rspan = +$(el).attr('rowspan') || 1;
var x = _x; // skip already occupied cells in current row
for (; m[y] && m[y][x]; x++) {} // ignore
// mark matrix elements occupied by current cell with true
for (var tx = x; tx < x + cspan; tx++) {
for (var ty = y; ty < y + rspan; ty++) {
if (!m[ty]) {
// fill missing rows
m[ty] = [];
}
m[ty][tx] = true;
}
}
var field = columns[x].field;
row[field] = $(el).html().trim(); // save td's id, class and data-* attributes
row["_".concat(field, "_id")] = $(el).attr('id');
row["_".concat(field, "_class")] = $(el).attr('class');
row["_".concat(field, "_rowspan")] = $(el).attr('rowspan');
row["_".concat(field, "_colspan")] = $(el).attr('colspan');
row["_".concat(field, "_title")] = $(el).attr('title');
row["_".concat(field, "_data")] = _this.getRealDataAttr($(el).data());
});
data.push(row);
});
return data;
},
sort: function sort(a, b, order, sortStable) {
if (a === undefined || a === null) {
a = '';
}
if (b === undefined || b === null) {
b = '';
}
if (sortStable && a === b) {
a = a._position;
b = b._position;
} // If both values are numeric, do a numeric comparison
if (this.isNumeric(a) && this.isNumeric(b)) {
// Convert numerical values form string to float.
a = parseFloat(a);
b = parseFloat(b);
if (a < b) {
return order * -1;
}
if (a > b) {
return order;
}
return 0;
}
if (a === b) {
return 0;
} // If value is not a string, convert to string
if (typeof a !== 'string') {
a = a.toString();
}
if (a.localeCompare(b) === -1) {
return order * -1;
}
return order;
}
};
var BLOCK_ROWS = 50;
var CLUSTER_BLOCKS = 4;
var VirtualScroll =
/*#__PURE__*/
function () {
function VirtualScroll(options) {
var _this = this;
_classCallCheck(this, VirtualScroll);
this.rows = options.rows;
this.scrollEl = options.scrollEl;
this.contentEl = options.contentEl;
this.callback = options.callback;
this.itemHeight = options.itemHeight;
this.cache = {};
this.scrollTop = this.scrollEl.scrollTop;
this.initDOM(this.rows);
this.scrollEl.scrollTop = this.scrollTop;
this.lastCluster = 0;
var onScroll = function onScroll() {
if (_this.lastCluster !== (_this.lastCluster = _this.getNum())) {
_this.initDOM(_this.rows);
_this.callback();
}
};
this.scrollEl.addEventListener('scroll', onScroll, false);
this.destroy = function () {
_this.contentEl.innerHtml = '';
_this.scrollEl.removeEventListener('scroll', onScroll, false);
};
}
_createClass(VirtualScroll, [{
key: "initDOM",
value: function initDOM(rows) {
if (typeof this.clusterHeight === 'undefined') {
this.cache.data = this.contentEl.innerHTML = rows[0] + rows[0] + rows[0];
this.getRowsHeight(rows);
}
var data = this.initData(rows, this.getNum());
var thisRows = data.rows.join('');
var dataChanged = this.checkChanges('data', thisRows);
var topOffsetChanged = this.checkChanges('top', data.topOffset);
var bottomOffsetChanged = this.checkChanges('bottom', data.bottomOffset);
var html = [];
if (dataChanged && topOffsetChanged) {
if (data.topOffset) {
html.push(this.getExtra('top', data.topOffset));
}
html.push(thisRows);
if (data.bottomOffset) {
html.push(this.getExtra('bottom', data.bottomOffset));
}
this.contentEl.innerHTML = html.join('');
} else if (bottomOffsetChanged) {
this.contentEl.lastChild.style.height = "".concat(data.bottomOffset, "px");
}
}
}, {
key: "getRowsHeight",
value: function getRowsHeight() {
if (typeof this.itemHeight === 'undefined') {
var nodes = this.contentEl.children;
var node = nodes[Math.floor(nodes.length / 2)];
this.itemHeight = node.offsetHeight;
}
this.blockHeight = this.itemHeight * BLOCK_ROWS;
this.clusterRows = BLOCK_ROWS * CLUSTER_BLOCKS;
this.clusterHeight = this.blockHeight * CLUSTER_BLOCKS;
}
}, {
key: "getNum",
value: function getNum() {
this.scrollTop = this.scrollEl.scrollTop;
return Math.floor(this.scrollTop / (this.clusterHeight - this.blockHeight)) || 0;
}
}, {
key: "initData",
value: function initData(rows, num) {
if (rows.length < BLOCK_ROWS) {
return {
topOffset: 0,
bottomOffset: 0,
rowsAbove: 0,
rows: rows
};
}
var start = Math.max((this.clusterRows - BLOCK_ROWS) * num, 0);
var end = start + this.clusterRows;
var topOffset = Math.max(start * this.itemHeight, 0);
var bottomOffset = Math.max((rows.length - end) * this.itemHeight, 0);
var thisRows = [];
var rowsAbove = start;
if (topOffset < 1) {
rowsAbove++;
}
for (var i = start; i < end; i++) {
rows[i] && thisRows.push(rows[i]);
}
return {
topOffset: topOffset,
bottomOffset: bottomOffset,
rowsAbove: rowsAbove,
rows: thisRows
};
}
}, {
key: "checkChanges",
value: function checkChanges(type, value) {
var changed = value !== this.cache[type];
this.cache[type] = value;
return changed;
}
}, {
key: "getExtra",
value: function getExtra(className, height) {
var tag = document.createElement('tr');
tag.className = "virtual-scroll-".concat(className);
if (height) {
tag.style.height = "".concat(height, "px");
}
return tag.outerHTML;
}
}]);
return VirtualScroll;
}();
var BootstrapTable =
/*#__PURE__*/
function () {
function BootstrapTable(el, options) {
_classCallCheck(this, BootstrapTable);
this.options = options;
this.$el = $(el);
this.$el_ = this.$el.clone();
this.timeoutId_ = 0;
this.timeoutFooter_ = 0;
this.init();
}
_createClass(BootstrapTable, [{
key: "init",
value: function init() {
this.initConstants();
this.initLocale();
this.initContainer();
this.initTable();
this.initHeader();
this.initData();
this.initHiddenRows();
this.initToolbar();
this.initPagination();
this.initBody();
this.initSearchText();
this.initServer();
}
}, {
key: "initConstants",
value: function initConstants() {
var o = this.options;
this.constants = Constants.CONSTANTS;
this.constants.theme = $.fn.bootstrapTable.theme;
var buttonsPrefix = o.buttonsPrefix ? "".concat(o.buttonsPrefix, "-") : '';
this.constants.buttonsClass = [o.buttonsPrefix, buttonsPrefix + o.buttonsClass, Utils.sprintf("".concat(buttonsPrefix, "%s"), o.iconSize)].join(' ').trim();
}
}, {
key: "initLocale",
value: function initLocale() {
if (this.options.locale) {
var locales = $.fn.bootstrapTable.locales;
var parts = this.options.locale.split(/-|_/);
parts[0] = parts[0].toLowerCase();
if (parts[1]) {
parts[1] = parts[1].toUpperCase();
}
if (locales[this.options.locale]) {
$.extend(this.options, locales[this.options.locale]);
} else if (locales[parts.join('-')]) {
$.extend(this.options, locales[parts.join('-')]);
} else if (locales[parts[0]]) {
$.extend(this.options, locales[parts[0]]);
}
}
}
}, {
key: "initContainer",
value: function initContainer() {
var topPagination = ['top', 'both'].includes(this.options.paginationVAlign) ? '<div class="fixed-table-pagination clearfix"></div>' : '';
var bottomPagination = ['bottom', 'both'].includes(this.options.paginationVAlign) ? '<div class="fixed-table-pagination"></div>' : '';
this.$container = $("\n <div class=\"bootstrap-table ".concat(this.constants.theme, "\">\n <div class=\"fixed-table-toolbar\"></div>\n ").concat(topPagination, "\n <div class=\"fixed-table-container\">\n <div class=\"fixed-table-header\"><table></table></div>\n <div class=\"fixed-table-body\">\n <div class=\"fixed-table-loading\">\n <span class=\"loading-wrap\">\n <span class=\"loading-text\">").concat(this.options.formatLoadingMessage(), "</span>\n <span class=\"animation-wrap\"><span class=\"animation-dot\"></span></span>\n </span>\n </div>\n </div>\n <div class=\"fixed-table-footer\"><table><thead><tr></tr></thead></table></div>\n </div>\n ").concat(bottomPagination, "\n </div>\n "));
this.$container.insertAfter(this.$el);
this.$tableContainer = this.$container.find('.fixed-table-container');
this.$tableHeader = this.$container.find('.fixed-table-header');
this.$tableBody = this.$container.find('.fixed-table-body');
this.$tableLoading = this.$container.find('.fixed-table-loading');
this.$tableFooter = this.$el.find('tfoot'); // checking if custom table-toolbar exists or not
if (this.options.buttonsToolbar) {
this.$toolbar = $('body').find(this.options.buttonsToolbar);
} else {
this.$toolbar = this.$container.find('.fixed-table-toolbar');
}
this.$pagination = this.$container.find('.fixed-table-pagination');
this.$tableBody.append(this.$el);
this.$container.after('<div class="clearfix"></div>');
this.$el.addClass(this.options.classes);
this.$tableLoading.addClass(this.options.classes);
if (this.options.height) {
this.$tableContainer.addClass('fixed-height');
if (this.options.showFooter) {
this.$tableContainer.addClass('has-footer');
}
if (this.options.classes.split(' ').includes('table-bordered')) {
this.$tableBody.append('<div class="fixed-table-border"></div>');
this.$tableBorder = this.$tableBody.find('.fixed-table-border');
this.$tableLoading.addClass('fixed-table-border');
}
this.$tableFooter = this.$container.find('.fixed-table-footer');
} else {
if (!this.$tableFooter.length) {
this.$el.append('<tfoot><tr></tr></tfoot>');
this.$tableFooter = this.$el.find('tfoot');
}
}
}
}, {
key: "initTable",
value: function initTable() {
var _this = this;
var columns = [];
var data = [];
this.$header = this.$el.find('>thead');
if (!this.$header.length) {
this.$header = $("<thead class=\"".concat(this.options.theadClasses, "\"></thead>")).appendTo(this.$el);
} else if (this.options.theadClasses) {
this.$header.addClass(this.options.theadClasses);
}
this.$header.find('tr').each(function (i, el) {
var column = [];
$(el).find('th').each(function (i, el) {
// #2014: getFieldIndex and elsewhere assume this is string, causes issues if not
if (typeof $(el).data('field') !== 'undefined') {
$(el).data('field', "".concat($(el).data('field')));
}
column.push($.extend({}, {
title: $(el).html(),
'class': $(el).attr('class'),
titleTooltip: $(el).attr('title'),
rowspan: $(el).attr('rowspan') ? +$(el).attr('rowspan') : undefined,
colspan: $(el).attr('colspan') ? +$(el).attr('colspan') : undefined
}, $(el).data()));
});
columns.push(column);
});
if (!Array.isArray(this.options.columns[0])) {
this.options.columns = [this.options.columns];
}
this.options.columns = $.extend(true, [], columns, this.options.columns);
this.columns = [];
this.fieldsColumnsIndex = [];
Utils.setFieldIndex(this.options.columns);
this.options.columns.forEach(function (columns, i) {
columns.forEach(function (_column, j) {
var column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, _column);
if (typeof column.fieldIndex !== 'undefined') {
_this.columns[column.fieldIndex] = column;
_this.fieldsColumnsIndex[column.field] = column.fieldIndex;
}
_this.options.columns[i][j] = column;
});
}); // if options.data is setting, do not process tbody and tfoot data
if (!this.options.data.length) {
this.options.data = Utils.trToData(this.columns, this.$el.find('>tbody>tr'));
if (data.length) {
this.fromHtml = true;
}
}
this.footerData = Utils.trToData(this.columns, this.$el.find('>tfoot>tr'));
if (this.footerData) {
this.$el.find('tfoot').html('<tr></tr>');
}
if (!this.options.showFooter || this.options.cardView) {
this.$tableFooter.hide();
} else {
this.$tableFooter.show();
}
}
}, {
key: "initHeader",
value: function initHeader() {
var _this2 = this;
var visibleColumns = {};
var html = [];
this.header = {
fields: [],
styles: [],
classes: [],
formatters: [],
detailFormatters: [],
events: [],
sorters: [],
sortNames: [],
cellStyles: [],
searchables: []
};
Utils.updateFieldGroup(this.options.columns);
this.options.columns.forEach(function (columns, i) {
html.push('<tr>');
if (i === 0 && !_this2.options.cardView && _this2.options.detailView && _this2.options.detailViewIcon) {
html.push("<th class=\"detail\" rowspan=\"".concat(_this2.options.columns.length, "\">\n <div class=\"fht-cell\"></div>\n </th>\n "));
}
columns.forEach(function (column, j) {
if (!column.visible) {
return;
}
var class_ = Utils.sprintf(' class="%s"', column['class']);
var unitWidth = column.widthUnit;
var width = parseFloat(column.width);
var halign = Utils.sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
var align = Utils.sprintf('text-align: %s; ', column.align);
var style = Utils.sprintf('vertical-align: %s; ', column.valign);
style += Utils.sprintf('width: %s; ', (column.checkbox || column.radio) && !width ? !column.showSelectTitle ? '36px' : undefined : width ? width + unitWidth : undefined);
if (typeof column.fieldIndex !== 'undefined') {
_this2.header.fields[column.fieldIndex] = column.field;
_this2.header.styles[column.fieldIndex] = align + style;
_this2.header.classes[column.fieldIndex] = class_;
_this2.header.formatters[column.fieldIndex] = column.formatter;
_this2.header.detailFormatters[column.fieldIndex] = column.detailFormatter;
_this2.header.events[column.fieldIndex] = column.events;
_this2.header.sorters[column.fieldIndex] = column.sorter;
_this2.header.sortNames[column.fieldIndex] = column.sortName;
_this2.header.cellStyles[column.fieldIndex] = column.cellStyle;
_this2.header.searchables[column.fieldIndex] = column.searchable;
if (_this2.options.cardView && !column.cardVisible) {
return;
}
visibleColumns[column.field] = column;
}
html.push("<th".concat(Utils.sprintf(' title="%s"', column.titleTooltip)), column.checkbox || column.radio ? Utils.sprintf(' class="bs-checkbox %s"', column['class'] || '') : class_, Utils.sprintf(' style="%s"', halign + style), Utils.sprintf(' rowspan="%s"', column.rowspan), Utils.sprintf(' colspan="%s"', column.colspan), Utils.sprintf(' data-field="%s"', column.field), // If `column` is not the first element of `this.options.columns[0]`, then className 'data-not-first-th' should be added.
j === 0 && i > 0 ? ' data-not-first-th' : '', '>');
html.push(Utils.sprintf('<div class="th-inner %s">', _this2.options.sortable && column.sortable ? 'sortable both' : ''));
var text = _this2.options.escape ? Utils.escapeHTML(column.title) : column.title;
var title = text;
if (column.checkbox) {
text = '';
if (!_this2.options.singleSelect && _this2.options.checkboxHeader) {
text = '<label><input name="btSelectAll" type="checkbox" /><span></span></label>';
}
_this2.header.stateField = column.field;
}
if (column.radio) {
text = '';
_this2.header.stateField = column.field;
_this2.options.singleSelect = true;
}
if (!text && column.showSelectTitle) {
text += title;
}
html.push(text);
html.push('</div>');
html.push('<div class="fht-cell"></div>');
html.push('</div>');
html.push('</th>');
});
html.push('</tr>');
});
this.$header.html(html.join(''));
this.$header.find('th[data-field]').each(function (i, el) {
$(el).data(visibleColumns[$(el).data('field')]);
});
this.$container.off('click', '.th-inner').on('click', '.th-inner', function (e) {
var $this = $(e.currentTarget);
if (_this2.options.detailView && !$this.parent().hasClass('bs-checkbox')) {
if ($this.closest('.bootstrap-table')[0] !== _this2.$container[0]) {
return false;
}
}
if (_this2.options.sortable && $this.parent().data().sortable) {
_this2.onSort(e);
}
});
this.$header.children().children().off('keypress').on('keypress', function (e) {
if (_this2.options.sortable && $(e.currentTarget).data().sortable) {
var code = e.keyCode || e.which;
if (code === 13) {
// Enter keycode
_this2.onSort(e);
}
}
});
var resizeEvent = "resize.bootstrap-table".concat(this.$el.attr('id') || '');
$(window).off(resizeEvent);
if (!this.options.showHeader || this.options.cardView) {
this.$header.hide();
this.$tableHeader.hide();
this.$tableLoading.css('top', 0);
} else {
this.$header.show();
this.$tableHeader.show();
this.$tableLoading.css('top', this.$header.outerHeight() + 1); // Assign the correct sortable arrow
this.getCaret();
$(window).on(resizeEvent, function (e) {
return _this2.resetWidth(e);
});
}
this.$selectAll = this.$header.find('[name="btSelectAll"]');
this.$selectAll.off('click').on('click', function (_ref) {
var currentTarget = _ref.currentTarget;
var checked = $(currentTarget).prop('checked');
_this2[checked ? 'checkAll' : 'uncheckAll']();
_this2.updateSelected();
});
}
}, {
key: "initData",
value: function initData(data, type) {
if (type === 'append') {
this.options.data = this.options.data.concat(data);
} else if (type === 'prepend') {
this.options.data = [].concat(data).concat(this.options.data);
} else {
this.options.data = data || this.options.data;
}
this.data = this.options.data;
if (this.options.sidePagination === 'server') {
return;
}
this.initSort();
}
}, {
key: "initSort",
value: function initSort() {
var _this3 = this;
var name = this.options.sortName;
var order = this.options.sortOrder === 'desc' ? -1 : 1;
var index = this.header.fields.indexOf(this.options.sortName);
var timeoutId = 0;
if (index !== -1) {
if (this.options.sortStable) {
this.data.forEach(function (row, i) {
if (!row.hasOwnProperty('_position')) {
row._position = i;
}
});
}
if (this.options.customSort) {
Utils.calculateObjectValue(this.options, this.options.customSort, [this.options.sortName, this.options.sortOrder, this.data]);
} else {
this.data.sort(function (a, b) {
if (_this3.header.sortNames[index]) {
name = _this3.header.sortNames[index];
}
var aa = Utils.getItemField(a, name, _this3.options.escape);
var bb = Utils.getItemField(b, name, _this3.options.escape);
var value = Utils.calculateObjectValue(_this3.header, _this3.header.sorters[index], [aa, bb, a, b]);
if (value !== undefined) {
if (_this3.options.sortStable && value === 0) {
return order * (a._position - b._position);
}
return order * value;
}
return Utils.sort(aa, bb, order, _this3.options.sortStable);
});
}
if (this.options.sortClass !== undefined) {
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
_this3.$el.removeClass(_this3.options.sortClass);
var index = _this3.$header.find("[data-field=\"".concat(_this3.options.sortName, "\"]")).index();
_this3.$el.find("tr td:nth-child(".concat(index + 1, ")")).addClass(_this3.options.sortClass);
}, 250);
}
}
}
}, {
key: "onSort",
value: function onSort(_ref2) {
var type = _ref2.type,
currentTarget = _ref2.currentTarget;
var $this = type === 'keypress' ? $(currentTarget) : $(currentTarget).parent();
var $this_ = this.$header.find('th').eq($this.index());
this.$header.add(this.$header_).find('span.order').remove();
if (this.options.sortName === $this.data('field')) {
this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
} else {
this.options.sortName = $this.data('field');
if (this.options.rememberOrder) {
this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
} else {
this.options.sortOrder = this.columns[this.fieldsColumnsIndex[$this.data('field')]].sortOrder || this.columns[this.fieldsColumnsIndex[$this.data('field')]].order;
}
}
this.trigger('sort', this.options.sortName, this.options.sortOrder);
$this.add($this_).data('order', this.options.sortOrder); // Assign the correct sortable arrow
this.getCaret();
if (this.options.sidePagination === 'server') {
this.options.pageNumber = 1;
this.initServer(this.options.silentSort);
return;
}
this.initSort();
this.initBody();
}
}, {
key: "initToolbar",
value: function initToolbar() {
var _this4 = this;
var o = this.options;
var html = [];
var timeoutId = 0;
var $keepOpen;
var $search;
var switchableCount = 0;
if (this.$toolbar.find('.bs-bars').children().length) {
$('body').append($(o.toolbar));
}
this.$toolbar.html('');
if (typeof o.toolbar === 'string' || _typeof(o.toolbar) === 'object') {
$(Utils.sprintf('<div class="bs-bars %s-%s"></div>', this.constants.classes.pull, o.toolbarAlign)).appendTo(this.$toolbar).append($(o.toolbar));
} // showColumns, showToggle, showRefresh
html = ["<div class=\"".concat(['columns', "columns-".concat(o.buttonsAlign), this.constants.classes.buttonsGroup, "".concat(this.constants.classes.pull, "-").concat(o.buttonsAlign)].join(' '), "\">")];
if (typeof o.icons === 'string') {
o.icons = Utils.calculateObjectValue(null, o.icons);
}
if (o.showPaginationSwitch) {
html.push("<button class=\"".concat(this.constants.buttonsClass, "\" type=\"button\" name=\"paginationSwitch\"\n aria-label=\"Pagination Switch\" title=\"").concat(o.formatPaginationSwitch(), "\">\n ").concat(o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.paginationSwitchDown) : '', "\n ").concat(o.showButtonText ? o.formatPaginationSwitchUp() : '', "\n </button>"));
}
if (o.showRefresh) {
html.push("<button class=\"".concat(this.constants.buttonsClass, "\" type=\"button\" name=\"refresh\"\n aria-label=\"Refresh\" title=\"").concat(o.formatRefresh(), "\">\n ").concat(o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.refresh) : '', "\n ").concat(o.showButtonText ? o.formatRefresh() : '', "\n </button>"));
}
if (o.showToggle) {
html.push("<button class=\"".concat(this.constants.buttonsClass, "\" type=\"button\" name=\"toggle\"\n aria-label=\"Toggle\" title=\"").concat(o.formatToggle(), "\">\n ").concat(o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.toggleOff) : '', "\n ").concat(o.showButtonText ? o.formatToggleOn() : '', "\n </button>"));
}
if (o.showFullscreen) {
html.push("<button class=\"".concat(this.constants.buttonsClass, "\" type=\"button\" name=\"fullscreen\"\n aria-label=\"Fullscreen\" title=\"").concat(o.formatFullscreen(), "\">\n ").concat(o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.fullscreen) : '', "\n ").concat(o.showButtonText ? o.formatFullscreen() : '', "\n </button>"));
}
if (o.showColumns) {
html.push("<div class=\"keep-open ".concat(this.constants.classes.buttonsDropdown, "\" title=\"").concat(o.formatColumns(), "\">\n <button class=\"").concat(this.constants.buttonsClass, " dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\"\n aria-label=\"Columns\" title=\"").concat(o.formatColumns(), "\">\n ").concat(o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.columns) : '', "\n ").concat(o.showButtonText ? o.formatColumns() : '', "\n ").concat(this.constants.html.dropdownCaret, "\n </button>\n ").concat(this.constants.html.toolbarDropdown[0]));
if (o.showColumnsToggleAll) {
var allFieldsVisible = this.getVisibleColumns().length === this.columns.length;
html.push(Utils.sprintf(this.constants.html.toolbarDropdownItem, Utils.sprintf('<input type="checkbox" class="toggle-all" %s> <span>%s</span>', allFieldsVisible ? 'checked="checked"' : '', o.formatColumnsToggleAll())));
html.push(this.constants.html.toolbarDropdownSeperator);
}
this.columns.forEach(function (column, i) {
if (column.radio || column.checkbox) {
return;
}
if (o.cardView && !column.cardVisible) {
return;
}
var checked = column.visible ? ' checked="checked"' : '';
if (column.switchable) {
html.push(Utils.sprintf(_this4.constants.html.toolbarDropdownItem, Utils.sprintf('<input type="checkbox" data-field="%s" value="%s"%s> <span>%s</span>', column.field, i, checked, column.title)));
switchableCount++;
}
});
html.push(this.constants.html.toolbarDropdown[1], '</div>');
}
html.push('</div>'); // Fix #188: this.showToolbar is for extensions
if (this.showToolbar || html.length > 2) {
this.$toolbar.append(html.join(''));
}
if (o.showPaginationSwitch) {
this.$toolbar.find('button[name="paginationSwitch"]').off('click').on('click', function () {
return _this4.togglePagination();
});
}
if (o.showFullscreen) {
this.$toolbar.find('button[name="fullscreen"]').off('click').on('click', function () {
return _this4.toggleFullscreen();
});
}
if (o.showRefresh) {
this.$toolbar.find('button[name="refresh"]').off('click').on('click', function () {
return _this4.refresh();
});
}
if (o.showToggle) {
this.$toolbar.find('button[name="toggle"]').off('click').on('click', function () {
_this4.toggleView();
});
}
if (o.showColumns) {
$keepOpen = this.$toolbar.find('.keep-open');
var $checkboxes = $keepOpen.find('input:not(".toggle-all")');
var $toggleAll = $keepOpen.find('input.toggle-all');
if (switchableCount <= o.minimumCountColumns) {
$keepOpen.find('input').prop('disabled', true);
}
$keepOpen.find('li, label').off('click').on('click', function (e) {
e.stopImmediatePropagation();
});
$checkboxes.off('click').on('click', function (_ref3) {
var currentTarget = _ref3.currentTarget;
var $this = $(currentTarget);
_this4._toggleColumn($this.val(), $this.prop('checked'), false);
_this4.trigger('column-switch', $this.data('field'), $this.prop('checked'));
$toggleAll.prop('checked', $checkboxes.filter(':checked').length === _this4.columns.length);
});
$toggleAll.off('click').on('click', function (_ref4) {
var currentTarget = _ref4.currentTarget;
_this4._toggleAllColumns($(currentTarget).prop('checked'));
});
}
if (o.search) {
html = [];
var showSearchButton = Utils.sprintf(this.constants.html.searchButton, o.formatSearch(), o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.search) : '', o.showButtonText ? o.formatSearch() : '');
var showSearchClearButton = Utils.sprintf(this.constants.html.searchClearButton, o.formatClearSearch(), o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.clearSearch) : '', o.showButtonText ? o.formatClearSearch() : '');
var searchInputHtml = "<input class=\"".concat(this.constants.classes.input).concat(Utils.sprintf(' input-%s', o.iconSize), " search-input\" type=\"text\" placeholder=\"").concat(o.formatSearch(), "\">");
var searchInputFinalHtml = searchInputHtml;
if (o.showSearchButton || o.showSearchClearButton) {
searchInputFinalHtml = Utils.sprintf(this.constants.html.inputGroup, searchInputHtml, (o.showSearchButton ? showSearchButton : '') + (o.showSearchClearButton ? showSearchClearButton : ''));
}
html.push(Utils.sprintf("\n <div class=\"".concat(this.constants.classes.pull, "-").concat(o.searchAlign, " search ").concat(this.constants.classes.inputGroup, "\">\n %s\n </div>\n "), searchInputFinalHtml));
this.$toolbar.append(html.join(''));
var $searchInput = this.$toolbar.find('.search input');
$search = o.showSearchButton ? this.$toolbar.find('.search button[name=search]') : $searchInput;
var eventTriggers = o.showSearchButton ? 'click' : Utils.isIEBrowser() ? 'mouseup' : 'keyup drop blur';
$search.off(eventTriggers).on(eventTriggers, function (event) {
if (o.searchOnEnterKey && event.keyCode !== 13) {
return;
}
if ([37, 38, 39, 40].includes(event.keyCode)) {
return;
}
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(function () {
_this4.onSearch(o.showSearchButton ? {
currentTarget: $searchInput
} : event);
}, o.searchTimeOut);
});
if (o.showSearchClearButton) {
this.$toolbar.find('.search button[name=clearSearch]').click(function () {
_this4.resetSearch();
_this4.onSearch({
currentTarget: _this4.$toolbar.find('.search input')
});
});
}
}
}
}, {
key: "onSearch",
value: function onSearch() {
var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
currentTarget = _ref5.currentTarget,
firedByInitSearchText = _ref5.firedByInitSearchText;
var overwriteSearchText = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
if (currentTarget !== undefined && overwriteSearchText) {
var text = $(currentTarget).val().trim();
if (this.options.trimOnSearch && $(currentTarget).val() !== text) {
$(currentTarget).val(text);
}
if (this.searchText === text) {
return;
}
if ($(currentTarget).hasClass('search-input')) {
this.searchText = text;
this.options.searchText = text;
}
}
if (!firedByInitSearchText) {
this.options.pageNumber = 1;
}
this.initSearch();
if (firedByInitSearchText) {
if (this.options.sidePagination === 'client') {
this.updatePagination();
}
} else {
this.updatePagination();
}
this.trigger('search', this.searchText);
}
}, {
key: "initSearch",
value: function initSearch() {
var _this5 = this;
this.filterOptions = this.filterOptions || this.options.filterOptions;
if (this.options.sidePagination !== 'server') {
if (this.options.customSearch) {
this.data = Utils.calculateObjectValue(this.options, this.options.customSearch, [this.options.data, this.searchText]);
return;
}
var s = this.searchText && (this.options.escape ? Utils.escapeHTML(this.searchText) : this.searchText).toLowerCase();
var f = Utils.isEmptyObject(this.filterColumns) ? null : this.filterColumns; // Check filter
if (typeof this.filterOptions.filterAlgorithm === 'function') {
this.data = this.options.data.filter(function (item, i) {
return _this5.filterOptions.filterAlgorithm.apply(null, [item, f]);
});
} else if (typeof this.filterOptions.filterAlgorithm === 'string') {
this.data = f ? this.options.data.filter(function (item, i) {
var filterAlgorithm = _this5.filterOptions.filterAlgorithm;
if (filterAlgorithm === 'and') {
for (var key in f) {
if (Array.isArray(f[key]) && !f[key].includes(item[key]) || !Array.isArray(f[key]) && item[key] !== f[key]) {
return false;
}
}
} else if (filterAlgorithm === 'or') {
var match = false;
for (var _key in f) {
if (Array.isArray(f[_key]) && f[_key].includes(item[_key]) || !Array.isArray(f[_key]) && item[_key] === f[_key]) {
match = true;
}
}
return match;
}
return true;
}) : this.options.data;
}
var visibleFields = this.getVisibleFields();
this.data = s ? this.data.filter(function (item, i) {
for (var j = 0; j < _this5.header.fields.length; j++) {
if (!_this5.header.searchables[j] || _this5.options.visibleSearch && visibleFields.indexOf(_this5.header.fields[j]) === -1) {
continue;
}
var key = Utils.isNumeric(_this5.header.fields[j]) ? parseInt(_this5.header.fields[j], 10) : _this5.header.fields[j];
var column = _this5.columns[_this5.fieldsColumnsIndex[key]];
var value = void 0;
if (typeof key === 'string') {
value = item;
var props = key.split('.');
for (var _i = 0; _i < props.length; _i++) {
if (value[props[_i]] !== null) {
value = value[props[_i]];
}
}
} else {
value = item[key];
} // Fix #142: respect searchFormatter boolean
if (column && column.searchFormatter) {
value = Utils.calculateObjectValue(column, _this5.header.formatters[j], [value, item, i, column.field], value);
}
if (typeof value === 'string' || typeof value === 'number') {
if (_this5.options.strictSearch) {
if ("".concat(value).toLowerCase() === s) {
return true;
}
} else {
var largerSmallerEqualsRegex = /(?:(<=|=>|=<|>=|>|<)(?:\s+)?(\d+)?|(\d+)?(\s+)?(<=|=>|=<|>=|>|<))/gm;
var matches = largerSmallerEqualsRegex.exec(s);
var comparisonCheck = false;
if (matches) {
var operator = matches[1] || "".concat(matches[5], "l");
var comparisonValue = matches[2] || matches[3];
var int = parseInt(value, 10);
var comparisonInt = parseInt(comparisonValue, 10);
switch (operator) {
case '>':
case '<l':
comparisonCheck = int > comparisonInt;
break;
case '<':
case '>l':
comparisonCheck = int < comparisonInt;
break;
case '<=':
case '=<':
case '>=l':
case '=>l':
comparisonCheck = int <= comparisonInt;
break;
case '>=':
case '=>':
case '<=l':
case '=<l':
comparisonCheck = int >= comparisonInt;
break;
default:
break;
}
}
if (comparisonCheck || "".concat(value).toLowerCase().includes(s)) {
return true;
}
}
}
}
return false;
}) : this.data;
}
}
}, {
key: "initPagination",
value: function initPagination() {
var _this6 = this;
var o = this.options;
if (!o.pagination) {
this.$pagination.hide();
return;
}
this.$pagination.show();
var html = [];
var $allSelected = false;
var i;
var from;
var to;
var $pageList;
var $pre;
var $next;
var $number;
var data = this.getData({
includeHiddenRows: false
});
var pageList = o.pageList;
if (o.sidePagination !== 'server') {
o.totalRows = data.length;
}
this.totalPages = 0;
if (o.totalRows) {
if (o.pageSize === o.formatAllRows()) {
o.pageSize = o.totalRows;
$allSelected = true;
} else if (o.pageSize === o.totalRows) {
// Fix #667 Table with pagination,
// multiple pages and a search this matches to one page throws exception
var pageLst = typeof o.pageList === 'string' ? o.pageList.replace('[', '').replace(']', '').replace(/ /g, '').toLowerCase().split(',') : o.pageList;
if (pageLst.includes(o.formatAllRows().toLowerCase())) {
$allSelected = true;
}
}
this.totalPages = ~~((o.totalRows - 1) / o.pageSize) + 1;
o.totalPages = this.totalPages;
}
if (this.totalPages > 0 && o.pageNumber > this.totalPages) {
o.pageNumber = this.totalPages;
}
this.pageFrom = (o.pageNumber - 1) * o.pageSize + 1;
this.pageTo = o.pageNumber * o.pageSize;
if (this.pageTo > o.totalRows) {
this.pageTo = o.totalRows;
}
if (this.options.pagination && this.options.sidePagination !== 'server') {
this.options.totalNotFiltered = this.options.data.length;
}
if (!this.options.showExtendedPagination) {
this.options.totalNotFiltered = undefined;
}
var paginationInfo = o.onlyInfoPagination ? o.formatDetailPagination(o.totalRows) : o.formatShowingRows(this.pageFrom, this.pageTo, o.totalRows, o.totalNotFiltered);
html.push("<div class=\"".concat(this.constants.classes.pull, "-").concat(o.paginationDetailHAlign, " pagination-detail\">\n <span class=\"pagination-info\">\n ").concat(paginationInfo, "\n </span>"));
if (!o.onlyInfoPagination) {
html.push('<span class="page-list">');
var pageNumber = ["<span class=\"".concat(this.constants.classes.paginationDropdown, "\">\n <button class=\"").concat(this.constants.buttonsClass, " dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\">\n <span class=\"page-size\">\n ").concat($allSelected ? o.formatAllRows() : o.pageSize, "\n </span>\n ").concat(this.constants.html.dropdownCaret, "\n </button>\n ").concat(this.constants.html.pageDropdown[0])];
if (typeof o.pageList === 'string') {
var list = o.pageList.replace('[', '').replace(']', '').replace(/ /g, '').split(',');
pageList = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var value = _step.value;
pageList.push(value.toLowerCase() === o.formatAllRows().toLowerCase() || ['all', 'unlimited'].includes(value.toLowerCase()) ? o.formatAllRows() : +value);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
pageList.forEach(function (page, i) {
if (!o.smartDisplay || i === 0 || pageList[i - 1] < o.totalRows) {
var active;
if ($allSelected) {
active = page === o.formatAllRows() ? _this6.constants.classes.dropdownActive : '';
} else {
active = page === o.pageSize ? _this6.constants.classes.dropdownActive : '';
}
pageNumber.push(Utils.sprintf(_this6.constants.html.pageDropdownItem, active, page));
}
});
pageNumber.push("".concat(this.constants.html.pageDropdown[1], "</span>"));
html.push(o.formatRecordsPerPage(pageNumber.join('')));
html.push('</span></div>');
html.push("<div class=\"".concat(this.constants.classes.pull, "-").concat(o.paginationHAlign, " pagination\">"), Utils.sprintf(this.constants.html.pagination[0], Utils.sprintf(' pagination-%s', o.iconSize)), Utils.sprintf(this.constants.html.paginationItem, ' page-pre', o.formatSRPaginationPreText(), o.paginationPreText));
if (this.totalPages < o.paginationSuccessivelySize) {
from = 1;
to = this.totalPages;
} else {
from = o.pageNumber - o.paginationPagesBySide;
to = from + o.paginationPagesBySide * 2;
}
if (o.pageNumber < o.paginationSuccessivelySize - 1) {
to = o.paginationSuccessivelySize;
}
if (o.paginationSuccessivelySize > this.totalPages - from) {
from = from - (o.paginationSuccessivelySize - (this.totalPages - from)) + 1;
}
if (from < 1) {
from = 1;
}
if (to > this.totalPages) {
to = this.totalPages;
}
var middleSize = Math.round(o.paginationPagesBySide / 2);
var pageItem = function pageItem(i) {
var classes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return Utils.sprintf(_this6.constants.html.paginationItem, classes + (i === o.pageNumber ? " ".concat(_this6.constants.classes.paginationActive) : ''), o.formatSRPaginationPageText(i), i);
};
if (from > 1) {
var max = o.paginationPagesBySide;
if (max >= from) max = from - 1;
for (i = 1; i <= max; i++) {
html.push(pageItem(i));
}
if (from - 1 === max + 1) {
i = from - 1;
html.push(pageItem(i));
} else {
if (from - 1 > max) {
if (from - o.paginationPagesBySide * 2 > o.paginationPagesBySide && o.paginationUseIntermediate) {
i = Math.round((from - middleSize) / 2 + middleSize);
html.push(pageItem(i, ' page-intermediate'));
} else {
html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-first-separator disabled', '', '...'));
}
}
}
}
for (i = from; i <= to; i++) {
html.push(pageItem(i));
}
if (this.totalPages > to) {
var min = this.totalPages - (o.paginationPagesBySide - 1);
if (to >= min) min = to + 1;
if (to + 1 === min - 1) {
i = to + 1;
html.push(pageItem(i));
} else {
if (min > to + 1) {
if (this.totalPages - to > o.paginationPagesBySide * 2 && o.paginationUseIntermediate) {
i = Math.round((this.totalPages - middleSize - to) / 2 + to);
html.push(pageItem(i, ' page-intermediate'));
} else {
html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-last-separator disabled', '', '...'));
}
}
}
for (i = min; i <= this.totalPages; i++) {
html.push(pageItem(i));
}
}
html.push(Utils.sprintf(this.constants.html.paginationItem, ' page-next', o.formatSRPaginationNextText(), o.paginationNextText));
html.push(this.constants.html.pagination[1], '</div>');
}
this.$pagination.html(html.join(''));
var dropupClass = ['bottom', 'both'].includes(o.paginationVAlign) ? " ".concat(this.constants.classes.dropup) : '';
this.$pagination.last().find('.page-list > span').addClass(dropupClass);
if (!o.onlyInfoPagination) {
$pageList = this.$pagination.find('.page-list a');
$pre = this.$pagination.find('.page-pre');
$next = this.$pagination.find('.page-next');
$number = this.$pagination.find('.page-item').not('.page-next, .page-pre, .page-last-separator, .page-first-separator');
if (this.totalPages <= 1) {
this.$pagination.find('div.pagination').hide();
}
if (o.smartDisplay) {
if (pageList.length < 2 || o.totalRows <= pageList[0]) {
this.$pagination.find('span.page-list').hide();
}
} // when data is empty, hide the pagination
this.$pagination[this.getData().length ? 'show' : 'hide']();
if (!o.paginationLoop) {
if (o.pageNumber === 1) {
$pre.addClass('disabled');
}
if (o.pageNumber === this.totalPages) {
$next.addClass('disabled');
}
}
if ($allSelected) {
o.pageSize = o.formatAllRows();
} // removed the events for last and first, onPageNumber executeds the same logic
$pageList.off('click').on('click', function (e) {
return _this6.onPageListChange(e);
});
$pre.off('click').on('click', function (e) {
return _this6.onPagePre(e);
});
$next.off('click').on('click', function (e) {
return _this6.onPageNext(e);
});
$number.off('click').on('click', function (e) {
return _this6.onPageNumber(e);
});
}
}
}, {
key: "updatePagination",
value: function updatePagination(event) {
// Fix #171: IE disabled button can be clicked bug.
if (event && $(event.currentTarget).hasClass('disabled')) {
return;
}
if (!this.options.maintainMetaData) {
this.resetRows();
}
this.initPagination();
if (this.options.sidePagination === 'server') {
this.initServer();
} else {
this.initBody();
}
this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
}
}, {
key: "onPageListChange",
value: function onPageListChange(event) {
event.preventDefault();
var $this = $(event.currentTarget);
$this.parent().addClass(this.constants.classes.dropdownActive).siblings().removeClass(this.constants.classes.dropdownActive);
this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ? this.options.formatAllRows() : +$this.text();
this.$toolbar.find('.page-size').text(this.options.pageSize);
this.updatePagination(event);
return false;
}
}, {
key: "onPagePre",
value: function onPagePre(event) {
event.preventDefault();
if (this.options.pageNumber - 1 === 0) {
this.options.pageNumber = this.options.totalPages;
} else {
this.options.pageNumber--;
}
this.updatePagination(event);
return false;
}
}, {
key: "onPageNext",
value: function onPageNext(event) {
event.preventDefault();
if (this.options.pageNumber + 1 > this.options.totalPages) {
this.options.pageNumber = 1;
} else {
this.options.pageNumber++;
}
this.updatePagination(event);
return false;
}
}, {
key: "onPageNumber",
value: function onPageNumber(event) {
event.preventDefault();
if (this.options.pageNumber === +$(event.currentTarget).text()) {
return;
}
this.options.pageNumber = +$(event.currentTarget).text();
this.updatePagination(event);
return false;
}
}, {
key: "initRow",
value: function initRow(item, i, data, trFragments) {
var _this7 = this;
var html = [];
var style = {};
var csses = [];
var data_ = '';
var attributes = {};
var htmlAttributes = [];
if (Utils.findIndex(this.hiddenRows, item) > -1) {
return;
}
style = Utils.calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
if (style && style.css) {
for (var _i2 = 0, _Object$entries = Object.entries(style.css); _i2 < _Object$entries.length; _i2++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i2], 2),
key = _Object$entries$_i[0],
value = _Object$entries$_i[1];
csses.push("".concat(key, ": ").concat(value));
}
}
attributes = Utils.calculateObjectValue(this.options, this.options.rowAttributes, [item, i], attributes);
if (attributes) {
for (var _i3 = 0, _Object$entries2 = Object.entries(attributes); _i3 < _Object$entries2.length; _i3++) {
var _Object$entries2$_i = _slicedToArray(_Object$entries2[_i3], 2),
key = _Object$entries2$_i[0],
value = _Object$entries2$_i[1];
htmlAttributes.push("".concat(key, "=\"").concat(Utils.escapeHTML(value), "\""));
}
}
if (item._data && !Utils.isEmptyObject(item._data)) {
for (var _i4 = 0, _Object$entries3 = Object.entries(item._data); _i4 < _Object$entries3.length; _i4++) {
var _Object$entries3$_i = _slicedToArray(_Object$entries3[_i4], 2),
k = _Object$entries3$_i[0],
v = _Object$entries3$_i[1];
// ignore data-index
if (k === 'index') {
return;
}
data_ += " data-".concat(k, "='").concat(_typeof(v) === 'object' ? JSON.stringify(v) : v, "'");
}
}
html.push('<tr', Utils.sprintf(' %s', htmlAttributes.length ? htmlAttributes.join(' ') : undefined), Utils.sprintf(' id="%s"', Array.isArray(item) ? undefined : item._id), Utils.sprintf(' class="%s"', style.classes || (Array.isArray(item) ? undefined : item._class)), " data-index=\"".concat(i, "\""), Utils.sprintf(' data-uniqueid="%s"', Utils.getItemField(item, this.options.uniqueId, false)), Utils.sprintf(' data-has-detail-view="%s"', !this.options.cardView && this.options.detailView && Utils.calculateObjectValue(null, this.options.detailFilter, [i, item]) ? 'true' : undefined), Utils.sprintf('%s', data_), '>');
if (this.options.cardView) {
html.push("<td colspan=\"".concat(this.header.fields.length, "\"><div class=\"card-views\">"));
}
if (!this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
html.push('<td>');
if (Utils.calculateObjectValue(null, this.options.detailFilter, [i, item])) {
html.push("\n <a class=\"detail-icon\" href=\"#\">\n ".concat(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen), "\n </a>\n "));
}
html.push('</td>');
}
this.header.fields.forEach(function (field, j) {
var text = '';
var value_ = Utils.getItemField(item, field, _this7.options.escape);
var value = '';
var type = '';
var cellStyle = {};
var id_ = '';
var class_ = _this7.header.classes[j];
var style_ = '';
var data_ = '';
var rowspan_ = '';
var colspan_ = '';
var title_ = '';
var column = _this7.columns[j];
if (_this7.fromHtml && typeof value_ === 'undefined') {
if (!column.checkbox && !column.radio) {
return;
}
}
if (!column.visible) {
return;
}
if (_this7.options.cardView && !column.cardVisible) {
return;
}
if (column.escape) {
value_ = Utils.escapeHTML(value_);
}
if (csses.concat([_this7.header.styles[j]]).length) {
style_ = " style=\"".concat(csses.concat([_this7.header.styles[j]]).join('; '), "\"");
} // handle td's id and class
if (item["_".concat(field, "_id")]) {
id_ = Utils.sprintf(' id="%s"', item["_".concat(field, "_id")]);
}
if (item["_".concat(field, "_class")]) {
class_ = Utils.sprintf(' class="%s"', item["_".concat(field, "_class")]);
}
if (item["_".concat(field, "_rowspan")]) {
rowspan_ = Utils.sprintf(' rowspan="%s"', item["_".concat(field, "_rowspan")]);
}
if (item["_".concat(field, "_colspan")]) {
colspan_ = Utils.sprintf(' colspan="%s"', item["_".concat(field, "_colspan")]);
}
if (item["_".concat(field, "_title")]) {
title_ = Utils.sprintf(' title="%s"', item["_".concat(field, "_title")]);
}
cellStyle = Utils.calculateObjectValue(_this7.header, _this7.header.cellStyles[j], [value_, item, i, field], cellStyle);
if (cellStyle.classes) {
class_ = " class=\"".concat(cellStyle.classes, "\"");
}
if (cellStyle.css) {
var csses_ = [];
for (var _i5 = 0, _Object$entries4 = Object.entries(cellStyle.css); _i5 < _Object$entries4.length; _i5++) {
var _Object$entries4$_i = _slicedToArray(_Object$entries4[_i5], 2),
key = _Object$entries4$_i[0],
_value = _Object$entries4$_i[1];
csses_.push("".concat(key, ": ").concat(_value));
}
style_ = " style=\"".concat(csses_.concat(_this7.header.styles[j]).join('; '), "\"");
}
value = Utils.calculateObjectValue(column, _this7.header.formatters[j], [value_, item, i, field], value_);
if (item["_".concat(field, "_data")] && !Utils.isEmptyObject(item["_".concat(field, "_data")])) {
for (var _i6 = 0, _Object$entries5 = Object.entries(item["_".concat(field, "_data")]); _i6 < _Object$entries5.length; _i6++) {
var _Object$entries5$_i = _slicedToArray(_Object$entries5[_i6], 2),
k = _Object$entries5$_i[0],
v = _Object$entries5$_i[1];
// ignore data-index
if (k === 'index') {
return;
}
data_ += " data-".concat(k, "=\"").concat(v, "\"");
}
}
if (column.checkbox || column.radio) {
type = column.checkbox ? 'checkbox' : type;
type = column.radio ? 'radio' : type;
var c = column['class'] || '';
var isChecked = (value === true || value_ || value && value.checked) && value !== false;
var isDisabled = !column.checkboxEnabled || value && value.disabled;
text = [_this7.options.cardView ? "<div class=\"card-view ".concat(c, "\">") : "<td class=\"bs-checkbox ".concat(c, "\"").concat(class_).concat(style_, ">"), "<label>\n <input\n data-index=\"".concat(i, "\"\n name=\"").concat(_this7.options.selectItemName, "\"\n type=\"").concat(type, "\"\n ").concat(Utils.sprintf('value="%s"', item[_this7.options.idField]), "\n ").concat(Utils.sprintf('checked="%s"', isChecked ? 'checked' : undefined), "\n ").concat(Utils.sprintf('disabled="%s"', isDisabled ? 'disabled' : undefined), " />\n <span></span>\n </label>"), _this7.header.formatters[j] && typeof value === 'string' ? value : '', _this7.options.cardView ? '</div>' : '</td>'].join('');
item[_this7.header.stateField] = value === true || !!value_ || value && value.checked;
} else {
value = typeof value === 'undefined' || value === null ? _this7.options.undefinedText : value;
if (_this7.options.cardView) {
var cardTitle = _this7.options.showHeader ? "<span class=\"card-view-title\"".concat(style_, ">").concat(Utils.getFieldTitle(_this7.columns, field), "</span>") : '';
text = "<div class=\"card-view\">".concat(cardTitle, "<span class=\"card-view-value\">").concat(value, "</span></div>");
if (_this7.options.smartDisplay && value === '') {
text = '<div class="card-view"></div>';
}
} else {
text = "<td".concat(id_).concat(class_).concat(style_).concat(data_).concat(rowspan_).concat(colspan_).concat(title_, ">").concat(value, "</td>");
}
}
html.push(text);
});
if (this.options.cardView) {
html.push('</div></td>');
}
html.push('</tr>');
return html.join('');
}
}, {
key: "initBody",
value: function initBody(fixedScroll) {
var _this8 = this;
var data = this.getData();
this.trigger('pre-body', data);
this.$body = this.$el.find('>tbody');
if (!this.$body.length) {
this.$body = $('<tbody></tbody>').appendTo(this.$el);
} // Fix #389 Bootstrap-table-flatJSON is not working
if (!this.options.pagination || this.options.sidePagination === 'server') {
this.pageFrom = 1;
this.pageTo = data.length;
}
var rows = [];
var trFragments = $(document.createDocumentFragment());
var hasTr = false;
for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
var item = data[i];
var tr = this.initRow(item, i, data, trFragments);
hasTr = hasTr || !!tr;
if (tr && typeof tr === 'string') {
if (!this.options.virtualScroll) {
trFragments.append(tr);
} else {
rows.push(tr);
}
}
} // show no records
if (!hasTr) {
this.$body.html("<tr class=\"no-records-found\">".concat(Utils.sprintf('<td colspan="%s">%s</td>', this.$header.find('th').length, this.options.formatNoMatches()), "</tr>"));
} else {
if (!this.options.virtualScroll) {
this.$body.html(trFragments);
} else {
if (this.virtualScroll) {
this.virtualScroll.destroy();
}
this.virtualScroll = new VirtualScroll({
rows: rows,
scrollEl: this.$tableBody[0],
contentEl: this.$body[0],
itemHeight: this.options.virtualScrollItemHeight,
callback: function callback() {
_this8.fitHeader();
}
});
}
}
if (!fixedScroll) {
this.scrollTo(0);
} // click to select by column
this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
var $td = $(e.currentTarget);
var $tr = $td.parent();
var $cardViewArr = $(e.target).parents('.card-views').children();
var $cardViewTarget = $(e.target).parents('.card-view');
var rowIndex = $tr.data('index');
var item = _this8.data[rowIndex];
var index = _this8.options.cardView ? $cardViewArr.index($cardViewTarget) : $td[0].cellIndex;
var fields = _this8.getVisibleFields();
var field = fields[_this8.options.detailView && _this8.detailViewIcon && !_this8.options.cardView ? index - 1 : index];
var column = _this8.columns[_this8.fieldsColumnsIndex[field]];
var value = Utils.getItemField(item, field, _this8.options.escape);
if ($td.find('.detail-icon').length) {
return;
}
_this8.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
_this8.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr, field); // if click to select - then trigger the checkbox/radio click
if (e.type === 'click' && _this8.options.clickToSelect && column.clickToSelect && !Utils.calculateObjectValue(_this8.options, _this8.options.ignoreClickToSelectOn, [e.target])) {
var $selectItem = $tr.find(Utils.sprintf('[name="%s"]', _this8.options.selectItemName));
if ($selectItem.length) {
$selectItem[0].click();
}
}
if (e.type === 'click' && _this8.options.detailViewByClick) {
_this8.toggleDetailView(rowIndex, _this8.header.detailFormatters[_this8.fieldsColumnsIndex[field]]);
}
}).off('mousedown').on('mousedown', function (e) {
// https://github.com/jquery/jquery/issues/1741
_this8.multipleSelectRowCtrlKey = e.ctrlKey || e.metaKey;
_this8.multipleSelectRowShiftKey = e.shiftKey;
});
this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function (e) {
e.preventDefault();
_this8.toggleDetailView($(e.currentTarget).parent().parent().data('index'));
return false;
});
this.$selectItem = this.$body.find(Utils.sprintf('[name="%s"]', this.options.selectItemName));
this.$selectItem.off('click').on('click', function (e) {
e.stopImmediatePropagation();
var $this = $(e.currentTarget);
_this8._toggleCheck($this.prop('checked'), $this.data('index'));
});
this.header.events.forEach(function (_events, i) {
var events = _events;
if (!events) {
return;
} // fix bug, if events is defined with namespace
if (typeof events === 'string') {
events = Utils.calculateObjectValue(null, events);
}
var field = _this8.header.fields[i];
var fieldIndex = _this8.getVisibleFields().indexOf(field);
if (fieldIndex === -1) {
return;
}
if (_this8.options.detailView && !_this8.options.cardView) {
fieldIndex += 1;
}
var _loop = function _loop(key) {
if (!events.hasOwnProperty(key)) {
return "continue";
}
var event = events[key];
_this8.$body.find('>tr:not(.no-records-found)').each(function (i, tr) {
var $tr = $(tr);
var $td = $tr.find(_this8.options.cardView ? '.card-view' : 'td').eq(fieldIndex);
var index = key.indexOf(' ');
var name = key.substring(0, index);
var el = key.substring(index + 1);
$td.find(el).off(name).on(name, function (e) {
var index = $tr.data('index');
var row = _this8.data[index];
var value = row[field];
event.apply(_this8, [e, value, row, index]);
});
});
};
for (var key in events) {
var _ret = _loop(key);
if (_ret === "continue") continue;
}
});
this.updateSelected();
this.initFooter();
this.resetView();
if (this.options.sidePagination !== 'server') {
this.options.totalRows = data.length;
}
this.trigger('post-body', data);
}
}, {
key: "initServer",
value: function initServer(silent, query, url) {
var _this9 = this;
var data = {};
var index = this.header.fields.indexOf(this.options.sortName);
var params = {
searchText: this.searchText,
sortName: this.options.sortName,
sortOrder: this.options.sortOrder
};
if (this.header.sortNames[index]) {
params.sortName = this.header.sortNames[index];
}
if (this.options.pagination && this.options.sidePagination === 'server') {
params.pageSize = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize;
params.pageNumber = this.options.pageNumber;
}
if (!(url || this.options.url) && !this.options.ajax) {
return;
}
if (this.options.queryParamsType === 'limit') {
params = {
search: params.searchText,
sort: params.sortName,
order: params.sortOrder
};
if (this.options.pagination && this.options.sidePagination === 'server') {
params.offset = this.options.pageSize === this.options.formatAllRows() ? 0 : this.options.pageSize * (this.options.pageNumber - 1);
params.limit = this.options.pageSize === this.options.formatAllRows() ? this.options.totalRows : this.options.pageSize;
if (params.limit === 0) {
delete params.limit;
}
}
}
if (!Utils.isEmptyObject(this.filterColumnsPartial)) {
params.filter = JSON.stringify(this.filterColumnsPartial, null);
}
data = Utils.calculateObjectValue(this.options, this.options.queryParams, [params], data);
$.extend(data, query || {}); // false to stop request
if (data === false) {
return;
}
if (!silent) {
this.showLoading();
}
var request = $.extend({}, Utils.calculateObjectValue(null, this.options.ajaxOptions), {
type: this.options.method,
url: url || this.options.url,
data: this.options.contentType === 'application/json' && this.options.method === 'post' ? JSON.stringify(data) : data,
cache: this.options.cache,
contentType: this.options.contentType,
dataType: this.options.dataType,
success: function success(_res) {
var res = Utils.calculateObjectValue(_this9.options, _this9.options.responseHandler, [_res], _res);
_this9.load(res);
_this9.trigger('load-success', res);
if (!silent) {
_this9.hideLoading();
}
},
error: function error(jqXHR) {
var data = [];
if (_this9.options.sidePagination === 'server') {
data = {};
data[_this9.options.totalField] = 0;
data[_this9.options.dataField] = [];
}
_this9.load(data);
_this9.trigger('load-error', jqXHR.status, jqXHR);
if (!silent) _this9.$tableLoading.hide();
}
});
if (this.options.ajax) {
Utils.calculateObjectValue(this, this.options.ajax, [request], null);
} else {
if (this._xhr && this._xhr.readyState !== 4) {
this._xhr.abort();
}
this._xhr = $.ajax(request);
}
return data;
}
}, {
key: "initSearchText",
value: function initSearchText() {
if (this.options.search) {
this.searchText = '';
if (this.options.searchText !== '') {
var $search = this.$toolbar.find('.search input');
$search.val(this.options.searchText);
this.onSearch({
currentTarget: $search,
firedByInitSearchText: true
});
}
}
}
}, {
key: "getCaret",
value: function getCaret() {
var _this10 = this;
this.$header.find('th').each(function (i, th) {
$(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === _this10.options.sortName ? _this10.options.sortOrder : 'both');
});
}
}, {
key: "updateSelected",
value: function updateSelected() {
var checkAll = this.$selectItem.filter(':enabled').length && this.$selectItem.filter(':enabled').length === this.$selectItem.filter(':enabled').filter(':checked').length;
this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
this.$selectItem.each(function (i, el) {
$(el).closest('tr')[$(el).prop('checked') ? 'addClass' : 'removeClass']('selected');
});
}
}, {
key: "updateRows",
value: function updateRows() {
var _this11 = this;
this.$selectItem.each(function (i, el) {
_this11.data[$(el).data('index')][_this11.header.stateField] = $(el).prop('checked');
});
}
}, {
key: "resetRows",
value: function resetRows() {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.data[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var row = _step2.value;
this.$selectAll.prop('checked', false);
this.$selectItem.prop('checked', false);
if (this.header.stateField) {
row[this.header.stateField] = false;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.initHiddenRows();
}
}, {
key: "trigger",
value: function trigger(_name) {
var _this$options;
var name = "".concat(_name, ".bs.table");
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key2 = 1; _key2 < _len; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
(_this$options = this.options)[BootstrapTable.EVENTS[name]].apply(_this$options, args);
this.$el.trigger($.Event(name), args);
this.options.onAll(name, args);
this.$el.trigger($.Event('all.bs.table'), [name, args]);
}
}, {
key: "resetHeader",
value: function resetHeader() {
var _this12 = this;
// fix #61: the hidden table reset header bug.
// fix bug: get $el.css('width') error sometime (height = 500)
clearTimeout(this.timeoutId_);
this.timeoutId_ = setTimeout(function () {
return _this12.fitHeader();
}, this.$el.is(':hidden') ? 100 : 0);
}
}, {
key: "fitHeader",
value: function fitHeader() {
var _this13 = this;
if (this.$el.is(':hidden')) {
this.timeoutId_ = setTimeout(function () {
return _this13.fitHeader();
}, 100);
return;
}
var fixedBody = this.$tableBody.get(0);
var scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth && fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ? Utils.getScrollBarWidth() : 0;
this.$el.css('margin-top', -this.$header.outerHeight());
var focused = $(':focus');
if (focused.length > 0) {
var $th = focused.parents('th');
if ($th.length > 0) {
var dataField = $th.attr('data-field');
if (dataField !== undefined) {
var $headerTh = this.$header.find("[data-field='".concat(dataField, "']"));
if ($headerTh.length > 0) {
$headerTh.find(':input').addClass('focus-temp');
}
}
}
}
this.$header_ = this.$header.clone(true, true);
this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
this.$tableHeader.css('margin-right', scrollWidth).find('table').css('width', this.$el.outerWidth()).html('').attr('class', this.$el.attr('class')).append(this.$header_);
this.$tableLoading.css('width', this.$el.outerWidth());
var focusedTemp = $('.focus-temp:visible:eq(0)');
if (focusedTemp.length > 0) {
focusedTemp.focus();
this.$header.find('.focus-temp').removeClass('focus-temp');
} // fix bug: $.data() is not working as expected after $.append()
this.$header.find('th[data-field]').each(function (i, el) {
_this13.$header_.find(Utils.sprintf('th[data-field="%s"]', $(el).data('field'))).data($(el).data());
});
var visibleFields = this.getVisibleFields();
var $ths = this.$header_.find('th');
var $tr = this.$body.find('>tr:not(.no-records-found,.virtual-scroll-top)').eq(0);
while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
$tr = $tr.next();
}
$tr.find('> *').each(function (i, el) {
var $this = $(el);
var index = i;
if (_this13.options.detailView && _this13.options.detailViewIcon && !_this13.options.cardView) {
if (i === 0) {
var $thDetail = $ths.filter('.detail');
var _zoomWidth = $thDetail.width() - $thDetail.find('.fht-cell').width();
$thDetail.find('.fht-cell').width($this.innerWidth() - _zoomWidth);
}
index = i - 1;
}
if (index === -1) {
return;
}
var $th = _this13.$header_.find(Utils.sprintf('th[data-field="%s"]', visibleFields[index]));
if ($th.length > 1) {
$th = $($ths[$this[0].cellIndex]);
}
var zoomWidth = $th.width() - $th.find('.fht-cell').width();
$th.find('.fht-cell').width($this.innerWidth() - zoomWidth);
});
this.horizontalScroll();
this.trigger('post-header');
}
}, {
key: "initFooter",
value: function initFooter() {
if (!this.options.showFooter || this.options.cardView) {
// do nothing
return;
}
var data = this.getData();
var html = [];
if (!this.options.cardView && this.options.detailView && this.options.detailViewIcon) {
html.push('<th class="detail"><div class="th-inner"></div><div class="fht-cell"></div></th>');
}
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this.columns[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var column = _step3.value;
var falign = '';
var valign = '';
var csses = [];
var style = {};
var class_ = Utils.sprintf(' class="%s"', column['class']);
if (!column.visible) {
continue;
}
if (this.options.cardView && !column.cardVisible) {
return;
}
falign = Utils.sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
valign = Utils.sprintf('vertical-align: %s; ', column.valign);
style = Utils.calculateObjectValue(null, this.options.footerStyle, [column]);
if (style && style.css) {
for (var _i7 = 0, _Object$entries6 = Object.entries(style.css); _i7 < _Object$entries6.length; _i7++) {
var _Object$entries6$_i = _slicedToArray(_Object$entries6[_i7], 2),
key = _Object$entries6$_i[0],
value = _Object$entries6$_i[1];
csses.push("".concat(key, ": ").concat(value));
}
}
if (style && style.classes) {
class_ = Utils.sprintf(' class="%s"', column['class'] ? [column['class'], style.classes].join(' ') : style.classes);
}
html.push('<th', class_, Utils.sprintf(' style="%s"', falign + valign + csses.concat().join('; ')), '>');
html.push('<div class="th-inner">');
html.push(Utils.calculateObjectValue(column, column.footerFormatter, [data], this.footerData[0] && this.footerData[0][column.field] || ''));
html.push('</div>');
html.push('<div class="fht-cell"></div>');
html.push('</div>');
html.push('</th>');
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
this.$tableFooter.find('tr').html(html.join(''));
this.trigger('post-footer', this.$tableFooter);
}
}, {
key: "fitFooter",
value: function fitFooter() {
var _this14 = this;
if (this.$el.is(':hidden')) {
setTimeout(function () {
return _this14.fitFooter();
}, 100);
return;
}
var fixedBody = this.$tableBody.get(0);
var scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth && fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ? Utils.getScrollBarWidth() : 0;
this.$tableFooter.css('margin-right', scrollWidth).find('table').css('width', this.$el.outerWidth()).attr('class', this.$el.attr('class'));
var visibleFields = this.getVisibleFields();
var $ths = this.$tableFooter.find('th');
var $tr = this.$body.find('>tr:first-child:not(.no-records-found)');
while ($tr.length && $tr.find('>td[colspan]:not([colspan="1"])').length) {
$tr = $tr.next();
}
$tr.find('> *').each(function (i, el) {
var $this = $(el);
var index = i;
if (_this14.options.detailView && !_this14.options.cardView) {
if (i === 0) {
var $thDetail = $ths.filter('.detail');
var _zoomWidth2 = $thDetail.width() - $thDetail.find('.fht-cell').width();
$thDetail.find('.fht-cell').width($this.innerWidth() - _zoomWidth2);
}
index = i - 1;
}
if (index === -1) {
return;
}
var $th = $ths.eq(i);
var zoomWidth = $th.width() - $th.find('.fht-cell').width();
$th.find('.fht-cell').width($this.innerWidth() - zoomWidth);
});
this.horizontalScroll();
}
}, {
key: "horizontalScroll",
value: function horizontalScroll() {
var _this15 = this;
// horizontal scroll event
// TODO: it's probably better improving the layout than binding to scroll event
this.trigger('scroll-body');
this.$tableBody.off('scroll').on('scroll', function (_ref6) {
var currentTarget = _ref6.currentTarget;
if (_this15.options.showHeader && _this15.options.height) {
_this15.$tableHeader.scrollLeft($(currentTarget).scrollLeft());
}
if (_this15.options.showFooter && !_this15.options.cardView) {
_this15.$tableFooter.scrollLeft($(currentTarget).scrollLeft());
}
});
}
}, {
key: "getVisibleFields",
value: function getVisibleFields() {
var visibleFields = [];
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = this.header.fields[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var field = _step4.value;
var column = this.columns[this.fieldsColumnsIndex[field]];
if (!column || !column.visible) {
continue;
}
visibleFields.push(field);
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
return visibleFields;
}
}, {
key: "initHiddenRows",
value: function initHiddenRows() {
this.hiddenRows = [];
} // PUBLIC FUNCTION DEFINITION
// =======================
}, {
key: "getOptions",
value: function getOptions() {
// deep copy and remove data
var options = $.extend({}, this.options);
delete options.data;
return $.extend(true, {}, options);
}
}, {
key: "refreshOptions",
value: function refreshOptions(options) {
// If the objects are equivalent then avoid the call of destroy / init methods
if (Utils.compareObjects(this.options, options, true)) {
return;
}
this.options = $.extend(this.options, options);
this.trigger('refresh-options', this.options);
this.destroy();
this.init();
}
}, {
key: "getData",
value: function getData(params) {
var data = this.options.data;
if (this.searchText || this.options.sortName || !Utils.isEmptyObject(this.filterColumns) || !Utils.isEmptyObject(this.filterColumnsPartial)) {
data = this.data;
}
if (params && params.useCurrentPage) {
data = data.slice(this.pageFrom - 1, this.pageTo);
}
if (params && !params.includeHiddenRows) {
var hiddenRows = this.getHiddenRows();
data = data.filter(function (row) {
return Utils.findIndex(hiddenRows, row) === -1;
});
}
return data;
}
}, {
key: "getSelections",
value: function getSelections() {
var _this16 = this;
// fix #2424: from html with checkbox
return this.data.filter(function (row) {
return row[_this16.header.stateField] === true;
});
}
}, {
key: "getAllSelections",
value: function getAllSelections() {
var _this17 = this;
return this.options.data.filter(function (row) {
return row[_this17.header.stateField] === true;
});
}
}, {
key: "load",
value: function load(_data) {
var fixedScroll = false;
var data = _data; // #431: support pagination
if (this.options.pagination && this.options.sidePagination === 'server') {
this.options.totalRows = data[this.options.totalField];
}
if (this.options.pagination && this.options.sidePagination === 'server') {
this.options.totalNotFiltered = data[this.options.totalNotFilteredField];
}
fixedScroll = data.fixedScroll;
data = Array.isArray(data) ? data : data[this.options.dataField];
this.initData(data);
this.initSearch();
this.initPagination();
this.initBody(fixedScroll);
}
}, {
key: "append",
value: function append(data) {
this.initData(data, 'append');
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
}
}, {
key: "prepend",
value: function prepend(data) {
this.initData(data, 'prepend');
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
}
}, {
key: "remove",
value: function remove(params) {
var len = this.options.data.length;
var i;
var row;
if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
return;
}
for (i = len - 1; i >= 0; i--) {
row = this.options.data[i];
if (!row.hasOwnProperty(params.field)) {
continue;
}
if (params.values.includes(row[params.field])) {
this.options.data.splice(i, 1);
if (this.options.sidePagination === 'server') {
this.options.totalRows -= 1;
}
}
}
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
}
}, {
key: "removeAll",
value: function removeAll() {
if (this.options.data.length > 0) {
this.options.data.splice(0, this.options.data.length);
this.initSearch();
this.initPagination();
this.initBody(true);
}
}
}, {
key: "insertRow",
value: function insertRow(params) {
if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
return;
}
this.options.data.splice(params.index, 0, params.row);
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
}
}, {
key: "updateRow",
value: function updateRow(params) {
var allParams = Array.isArray(params) ? params : [params];
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = allParams[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var _params = _step5.value;
if (!_params.hasOwnProperty('index') || !_params.hasOwnProperty('row')) {
continue;
}
$.extend(this.options.data[_params.index], _params.row);
if (_params.hasOwnProperty('replace') && _params.replace) {
this.options.data[_params.index] = _params.row;
} else {
$.extend(this.options.data[_params.index], _params.row);
}
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
}
}, {
key: "getRowByUniqueId",
value: function getRowByUniqueId(_id) {
var uniqueId = this.options.uniqueId;
var len = this.options.data.length;
var id = _id;
var dataRow = null;
var i;
var row;
var rowUniqueId;
for (i = len - 1; i >= 0; i--) {
row = this.options.data[i];
if (row.hasOwnProperty(uniqueId)) {
// uniqueId is a column
rowUniqueId = row[uniqueId];
} else if (row._data && row._data.hasOwnProperty(uniqueId)) {
// uniqueId is a row data property
rowUniqueId = row._data[uniqueId];
} else {
continue;
}
if (typeof rowUniqueId === 'string') {
id = id.toString();
} else if (typeof rowUniqueId === 'number') {
if (Number(rowUniqueId) === rowUniqueId && rowUniqueId % 1 === 0) {
id = parseInt(id);
} else if (rowUniqueId === Number(rowUniqueId) && rowUniqueId !== 0) {
id = parseFloat(id);
}
}
if (rowUniqueId === id) {
dataRow = row;
break;
}
}
return dataRow;
}
}, {
key: "updateByUniqueId",
value: function updateByUniqueId(params) {
var allParams = Array.isArray(params) ? params : [params];
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = allParams[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var _params2 = _step6.value;
if (!_params2.hasOwnProperty('id') || !_params2.hasOwnProperty('row')) {
continue;
}
var rowId = this.options.data.indexOf(this.getRowByUniqueId(_params2.id));
if (rowId === -1) {
continue;
}
if (_params2.hasOwnProperty('replace') && _params2.replace) {
this.options.data[rowId] = _params2.row;
} else {
$.extend(this.options.data[rowId], _params2.row);
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
_iterator6.return();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
}
}, {
key: "removeByUniqueId",
value: function removeByUniqueId(id) {
var len = this.options.data.length;
var row = this.getRowByUniqueId(id);
if (row) {
this.options.data.splice(this.options.data.indexOf(row), 1);
}
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initBody(true);
}
}, {
key: "updateCell",
value: function updateCell(params) {
if (!params.hasOwnProperty('index') || !params.hasOwnProperty('field') || !params.hasOwnProperty('value')) {
return;
}
this.data[params.index][params.field] = params.value;
if (params.reinit === false) {
return;
}
this.initSort();
this.initBody(true);
}
}, {
key: "updateCellByUniqueId",
value: function updateCellByUniqueId(params) {
var _this18 = this;
if (!params.hasOwnProperty('id') || !params.hasOwnProperty('field') || !params.hasOwnProperty('value')) {
return;
}
var allParams = Array.isArray(params) ? params : [params];
allParams.forEach(function (_ref7) {
var id = _ref7.id,
field = _ref7.field,
value = _ref7.value;
var rowId = _this18.options.data.indexOf(_this18.getRowByUniqueId(id));
if (rowId === -1) {
return;
}
_this18.options.data[rowId][field] = value;
});
if (params.reinit === false) {
return;
}
this.initSort();
this.initBody(true);
}
}, {
key: "showRow",
value: function showRow(params) {
this._toggleRow(params, true);
}
}, {
key: "hideRow",
value: function hideRow(params) {
this._toggleRow(params, false);
}
}, {
key: "_toggleRow",
value: function _toggleRow(params, visible) {
var row;
if (params.hasOwnProperty('index')) {
row = this.getData()[params.index];
} else if (params.hasOwnProperty('uniqueId')) {
row = this.getRowByUniqueId(params.uniqueId);
}
if (!row) {
return;
}
var index = Utils.findIndex(this.hiddenRows, row);
if (!visible && index === -1) {
this.hiddenRows.push(row);
} else if (visible && index > -1) {
this.hiddenRows.splice(index, 1);
}
if (visible) {
this.updatePagination();
} else {
this.initBody(true);
this.initPagination();
}
}
}, {
key: "getHiddenRows",
value: function getHiddenRows(show) {
if (show) {
this.initHiddenRows();
this.initBody(true);
return;
}
var data = this.getData();
var rows = [];
var _iteratorNormalCompletion7 = true;
var _didIteratorError7 = false;
var _iteratorError7 = undefined;
try {
for (var _iterator7 = data[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
var row = _step7.value;
if (this.hiddenRows.includes(row)) {
rows.push(row);
}
}
} catch (err) {
_didIteratorError7 = true;
_iteratorError7 = err;
} finally {
try {
if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
_iterator7.return();
}
} finally {
if (_didIteratorError7) {
throw _iteratorError7;
}
}
}
this.hiddenRows = rows;
return rows;
}
}, {
key: "showColumn",
value: function showColumn(field) {
var _this19 = this;
var fields = Array.isArray(field) ? field : [field];
fields.forEach(function (field) {
_this19._toggleColumn(_this19.fieldsColumnsIndex[field], true, true);
});
}
}, {
key: "hideColumn",
value: function hideColumn(field) {
var _this20 = this;
var fields = Array.isArray(field) ? field : [field];
fields.forEach(function (field) {
_this20._toggleColumn(_this20.fieldsColumnsIndex[field], false, true);
});
}
}, {
key: "_toggleColumn",
value: function _toggleColumn(index, checked, needUpdate) {
if (index === -1 || this.columns[index].visible === checked) {
return;
}
this.columns[index].visible = checked;
this.initHeader();
this.initSearch();
this.initPagination();
this.initBody();
if (this.options.showColumns) {
var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
if (needUpdate) {
$items.filter(Utils.sprintf('[value="%s"]', index)).prop('checked', checked);
}
if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
$items.filter(':checked').prop('disabled', true);
}
}
}
}, {
key: "getVisibleColumns",
value: function getVisibleColumns() {
return this.columns.filter(function (_ref8) {
var visible = _ref8.visible;
return visible;
});
}
}, {
key: "getHiddenColumns",
value: function getHiddenColumns() {
return this.columns.filter(function (_ref9) {
var visible = _ref9.visible;
return !visible;
});
}
}, {
key: "showAllColumns",
value: function showAllColumns() {
this._toggleAllColumns(true);
}
}, {
key: "hideAllColumns",
value: function hideAllColumns() {
this._toggleAllColumns(false);
}
}, {
key: "_toggleAllColumns",
value: function _toggleAllColumns(visible) {
var _this21 = this;
var _iteratorNormalCompletion8 = true;
var _didIteratorError8 = false;
var _iteratorError8 = undefined;
try {
for (var _iterator8 = this.columns.slice().reverse()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
var column = _step8.value;
if (column.switchable) {
if (!visible && this.options.showColumns && this.getVisibleColumns().length === this.options.minimumCountColumns) {
continue;
}
column.visible = visible;
}
}
} catch (err) {
_didIteratorError8 = true;
_iteratorError8 = err;
} finally {
try {
if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
_iterator8.return();
}
} finally {
if (_didIteratorError8) {
throw _iteratorError8;
}
}
}
this.initHeader();
this.initSearch();
this.initPagination();
this.initBody();
if (this.options.showColumns) {
var $items = this.$toolbar.find('.keep-open input:not(".toggle-all")').prop('disabled', false);
if (visible) {
$items.prop('checked', visible);
} else {
$items.get().reverse().forEach(function (item) {
if ($items.filter(':checked').length > _this21.options.minimumCountColumns) {
$(item).prop('checked', visible);
}
});
}
if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
$items.filter(':checked').prop('disabled', true);
}
}
}
}, {
key: "mergeCells",
value: function mergeCells(options) {
var row = options.index;
var col = this.getVisibleFields().indexOf(options.field);
var rowspan = options.rowspan || 1;
var colspan = options.colspan || 1;
var i;
var j;
var $tr = this.$body.find('>tr');
if (this.options.detailView && !this.options.cardView) {
col += 1;
}
var $td = $tr.eq(row).find('>td').eq(col);
if (row < 0 || col < 0 || row >= this.data.length) {
return;
}
for (i = row; i < row + rowspan; i++) {
for (j = col; j < col + colspan; j++) {
$tr.eq(i).find('>td').eq(j).hide();
}
}
$td.attr('rowspan', rowspan).attr('colspan', colspan).show();
}
}, {
key: "checkAll",
value: function checkAll() {
this._toggleCheckAll(true);
}
}, {
key: "uncheckAll",
value: function uncheckAll() {
this._toggleCheckAll(false);
}
}, {
key: "_toggleCheckAll",
value: function _toggleCheckAll(checked) {
var rowsBefore = this.getSelections();
this.$selectAll.add(this.$selectAll_).prop('checked', checked);
this.$selectItem.filter(':enabled').prop('checked', checked);
this.updateRows();
var rowsAfter = this.getSelections();
if (checked) {
this.trigger('check-all', rowsAfter, rowsBefore);
return;
}
this.trigger('uncheck-all', rowsAfter, rowsBefore);
}
}, {
key: "checkInvert",
value: function checkInvert() {
var $items = this.$selectItem.filter(':enabled');
var checked = $items.filter(':checked');
$items.each(function (i, el) {
$(el).prop('checked', !$(el).prop('checked'));
});
this.updateRows();
this.updateSelected();
this.trigger('uncheck-some', checked);
checked = this.getSelections();
this.trigger('check-some', checked);
}
}, {
key: "check",
value: function check(index) {
this._toggleCheck(true, index);
}
}, {
key: "uncheck",
value: function uncheck(index) {
this._toggleCheck(false, index);
}
}, {
key: "_toggleCheck",
value: function _toggleCheck(checked, index) {
var $el = this.$selectItem.filter("[data-index=\"".concat(index, "\"]"));
var row = this.data[index];
if ($el.is(':radio') || this.options.singleSelect || this.options.multipleSelectRow && !this.multipleSelectRowCtrlKey && !this.multipleSelectRowShiftKey) {
var _iteratorNormalCompletion9 = true;
var _didIteratorError9 = false;
var _iteratorError9 = undefined;
try {
for (var _iterator9 = this.options.data[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
var r = _step9.value;
r[this.header.stateField] = false;
}
} catch (err) {
_didIteratorError9 = true;
_iteratorError9 = err;
} finally {
try {
if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
_iterator9.return();
}
} finally {
if (_didIteratorError9) {
throw _iteratorError9;
}
}
}
this.$selectItem.filter(':checked').not($el).prop('checked', false);
}
row[this.header.stateField] = checked;
if (this.options.multipleSelectRow) {
if (this.multipleSelectRowShiftKey && this.multipleSelectRowLastSelectedIndex >= 0) {
var indexes = [this.multipleSelectRowLastSelectedIndex, index].sort();
for (var i = indexes[0] + 1; i < indexes[1]; i++) {
this.data[i][this.header.stateField] = true;
this.$selectItem.filter("[data-index=\"".concat(i, "\"]")).prop('checked', true);
}
}
this.multipleSelectRowCtrlKey = false;
this.multipleSelectRowShiftKey = false;
this.multipleSelectRowLastSelectedIndex = checked ? index : -1;
}
$el.prop('checked', checked);
this.updateSelected();
this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
}
}, {
key: "checkBy",
value: function checkBy(obj) {
this._toggleCheckBy(true, obj);
}
}, {
key: "uncheckBy",
value: function uncheckBy(obj) {
this._toggleCheckBy(false, obj);
}
}, {
key: "_toggleCheckBy",
value: function _toggleCheckBy(checked, obj) {
var _this22 = this;
if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
return;
}
var rows = [];
this.data.forEach(function (row, i) {
if (!row.hasOwnProperty(obj.field)) {
return false;
}
if (obj.values.includes(row[obj.field])) {
var $el = _this22.$selectItem.filter(':enabled').filter(Utils.sprintf('[data-index="%s"]', i)).prop('checked', checked);
row[_this22.header.stateField] = checked;
rows.push(row);
_this22.trigger(checked ? 'check' : 'uncheck', row, $el);
}
});
this.updateSelected();
this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
}
}, {
key: "refresh",
value: function refresh(params) {
if (params && params.url) {
this.options.url = params.url;
}
if (params && params.pageNumber) {
this.options.pageNumber = params.pageNumber;
}
if (params && params.pageSize) {
this.options.pageSize = params.pageSize;
}
this.trigger('refresh', this.initServer(params && params.silent, params && params.query, params && params.url));
}
}, {
key: "destroy",
value: function destroy() {
this.$el.insertBefore(this.$container);
$(this.options.toolbar).insertBefore(this.$el);
this.$container.next().remove();
this.$container.remove();
this.$el.html(this.$el_.html()).css('margin-top', '0').attr('class', this.$el_.attr('class') || ''); // reset the class
}
}, {
key: "resetView",
value: function resetView(params) {
var padding = 0;
if (params && params.height) {
this.options.height = params.height;
}
this.$selectAll.prop('checked', this.$selectItem.length > 0 && this.$selectItem.length === this.$selectItem.filter(':checked').length);
this.$tableContainer.toggleClass('has-card-view', this.options.cardView);
if (!this.options.cardView && this.options.showHeader && this.options.height) {
this.$tableHeader.show();
this.resetHeader();
padding += this.$header.outerHeight(true);
} else {
this.$tableHeader.hide();
this.trigger('post-header');
}
if (!this.options.cardView && this.options.showFooter) {
this.$tableFooter.show();
this.fitFooter();
if (this.options.height) {
padding += this.$tableFooter.outerHeight(true);
}
}
if (this.options.height) {
var toolbarHeight = this.$toolbar.outerHeight(true);
var paginationHeight = this.$pagination.outerHeight(true);
var height = this.options.height - toolbarHeight - paginationHeight;
var tableHeight = this.$tableBody.find('table').outerHeight(true);
this.$tableContainer.css('height', "".concat(height, "px"));
this.$tableBorder && this.$tableBorder.css('height', "".concat(height - tableHeight - padding - 1, "px"));
}
if (this.options.cardView) {
// remove the element css
this.$el.css('margin-top', '0');
this.$tableContainer.css('padding-bottom', '0');
this.$tableFooter.hide();
} else {
// Assign the correct sortable arrow
this.getCaret();
this.$tableContainer.css('padding-bottom', "".concat(padding, "px"));
}
this.trigger('reset-view');
}
}, {
key: "resetWidth",
value: function resetWidth() {
if (this.options.showHeader && this.options.height) {
this.fitHeader();
}
if (this.options.showFooter && !this.options.cardView) {
this.fitFooter();
}
}
}, {
key: "showLoading",
value: function showLoading() {
this.$tableLoading.css('display', 'flex');
}
}, {
key: "hideLoading",
value: function hideLoading() {
this.$tableLoading.css('display', 'none');
}
}, {
key: "togglePagination",
value: function togglePagination() {
this.options.pagination = !this.options.pagination;
var icon = this.options.showButtonIcons ? this.options.pagination ? this.options.icons.paginationSwitchDown : this.options.icons.paginationSwitchUp : '';
var text = this.options.showButtonText ? this.options.pagination ? this.options.formatPaginationSwitchUp() : this.options.formatPaginationSwitchDown() : '';
this.$toolbar.find('button[name="paginationSwitch"]').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text);
this.updatePagination();
}
}, {
key: "toggleFullscreen",
value: function toggleFullscreen() {
this.$el.closest('.bootstrap-table').toggleClass('fullscreen');
this.resetView();
}
}, {
key: "toggleView",
value: function toggleView() {
this.options.cardView = !this.options.cardView;
this.initHeader();
var icon = this.options.showButtonIcons ? this.options.cardView ? this.options.icons.toggleOn : this.options.icons.toggleOff : '';
var text = this.options.showButtonText ? this.options.cardView ? this.options.formatToggleOff() : this.options.formatToggleOn() : '';
this.$toolbar.find('button[name="toggle"]').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, icon) + ' ' + text);
this.initBody();
this.trigger('toggle', this.options.cardView);
}
}, {
key: "resetSearch",
value: function resetSearch(text) {
var $search = this.$toolbar.find('.search input');
$search.val(text || '');
this.onSearch({
currentTarget: $search
});
}
}, {
key: "filterBy",
value: function filterBy(columns, options) {
this.filterOptions = Utils.isEmptyObject(options) ? this.options.filterOptions : $.extend(this.options.filterOptions, options);
this.filterColumns = Utils.isEmptyObject(columns) ? {} : columns;
this.options.pageNumber = 1;
this.initSearch();
this.updatePagination();
}
}, {
key: "scrollTo",
value: function scrollTo(params) {
if (typeof params === 'undefined') {
return this.$tableBody.scrollTop();
}
var options = {
unit: 'px',
value: 0
};
if (_typeof(params) === 'object') {
options = Object.assign(options, params);
} else if (typeof params === 'string' && params === 'bottom') {
options.value = this.$tableBody[0].scrollHeight;
} else if (typeof params === 'string') {
options.value = params;
}
var scrollTo = options.value;
if (options.unit === 'rows') {
scrollTo = 0;
this.$body.find("> tr:lt(".concat(options.value, ")")).each(function (i, el) {
scrollTo += $(el).outerHeight(true);
});
}
this.$tableBody.scrollTop(scrollTo);
}
}, {
key: "getScrollPosition",
value: function getScrollPosition() {
return this.scrollTo();
}
}, {
key: "selectPage",
value: function selectPage(page) {
if (page > 0 && page <= this.options.totalPages) {
this.options.pageNumber = page;
this.updatePagination();
}
}
}, {
key: "prevPage",
value: function prevPage() {
if (this.options.pageNumber > 1) {
this.options.pageNumber--;
this.updatePagination();
}
}
}, {
key: "nextPage",
value: function nextPage() {
if (this.options.pageNumber < this.options.totalPages) {
this.options.pageNumber++;
this.updatePagination();
}
}
}, {
key: "toggleDetailView",
value: function toggleDetailView(index, _columnDetailFormatter) {
var $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"]', index));
if ($tr.next().is('tr.detail-view')) {
this.collapseRow(index);
} else {
this.expandRow(index, _columnDetailFormatter);
}
this.resetView();
}
}, {
key: "expandRow",
value: function expandRow(index, _columnDetailFormatter) {
var row = this.data[index];
var $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index));
if ($tr.next().is('tr.detail-view')) {
return;
}
if (this.options.detailViewIcon) {
$tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailClose));
}
$tr.after(Utils.sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.children('td').length));
var $element = $tr.next().find('td');
var detailFormatter = _columnDetailFormatter || this.options.detailFormatter;
var content = Utils.calculateObjectValue(this.options, detailFormatter, [index, row, $element], '');
if ($element.length === 1) {
$element.append(content);
}
this.trigger('expand-row', index, row, $element);
}
}, {
key: "collapseRow",
value: function collapseRow(index) {
var row = this.data[index];
var $tr = this.$body.find(Utils.sprintf('> tr[data-index="%s"][data-has-detail-view]', index));
if (!$tr.next().is('tr.detail-view')) {
return;
}
if (this.options.detailViewIcon) {
$tr.find('a.detail-icon').html(Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.detailOpen));
}
this.trigger('collapse-row', index, row, $tr.next());
$tr.next().remove();
}
}, {
key: "expandAllRows",
value: function expandAllRows() {
var trs = this.$body.find('> tr[data-index][data-has-detail-view]');
for (var i = 0; i < trs.length; i++) {
this.expandRow($(trs[i]).data('index'));
}
}
}, {
key: "collapseAllRows",
value: function collapseAllRows() {
var trs = this.$body.find('> tr[data-index][data-has-detail-view]');
for (var i = 0; i < trs.length; i++) {
this.collapseRow($(trs[i]).data('index'));
}
}
}, {
key: "updateColumnTitle",
value: function updateColumnTitle(params) {
if (!params.hasOwnProperty('field') || !params.hasOwnProperty('title')) {
return;
}
this.columns[this.fieldsColumnsIndex[params.field]].title = this.options.escape ? Utils.escapeHTML(params.title) : params.title;
if (this.columns[this.fieldsColumnsIndex[params.field]].visible) {
var header = this.options.height !== undefined ? this.$tableHeader : this.$header;
header.find('th[data-field]').each(function (i, el) {
if ($(el).data('field') === params.field) {
$($(el).find('.th-inner')[0]).text(params.title);
return false;
}
});
}
}
}, {
key: "updateFormatText",
value: function updateFormatText(formatName, text) {
if (!/^format/.test(formatName) || !this.options[formatName]) {
return;
}
if (typeof text === 'string') {
this.options[formatName] = function () {
return text;
};
} else if (typeof text === 'function') {
this.options[formatName] = text;
}
this.initToolbar();
this.initPagination();
this.initBody();
}
}]);
return BootstrapTable;
}();
BootstrapTable.VERSION = Constants.VERSION;
BootstrapTable.DEFAULTS = Constants.DEFAULTS;
BootstrapTable.LOCALES = Constants.LOCALES;
BootstrapTable.COLUMN_DEFAULTS = Constants.COLUMN_DEFAULTS;
BootstrapTable.METHODS = Constants.METHODS;
BootstrapTable.EVENTS = Constants.EVENTS; // BOOTSTRAP TABLE PLUGIN DEFINITION
// =======================
$.BootstrapTable = BootstrapTable;
$.fn.bootstrapTable = function (option) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
var value;
this.each(function (i, el) {
var data = $(el).data('bootstrap.table');
var options = $.extend({}, BootstrapTable.DEFAULTS, $(el).data(), _typeof(option) === 'object' && option);
if (typeof option === 'string') {
var _data2;
if (!Constants.METHODS.includes(option)) {
throw new Error("Unknown method: ".concat(option));
}
if (!data) {
return;
}
value = (_data2 = data)[option].apply(_data2, args);
if (option === 'destroy') {
$(el).removeData('bootstrap.table');
}
}
if (!data) {
$(el).data('bootstrap.table', data = new $.BootstrapTable(el, options));
}
});
return typeof value === 'undefined' ? this : value;
};
$.fn.bootstrapTable.Constructor = BootstrapTable;
$.fn.bootstrapTable.theme = Constants.THEME;
$.fn.bootstrapTable.VERSION = Constants.VERSION;
$.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
$.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
$.fn.bootstrapTable.events = BootstrapTable.EVENTS;
$.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
$.fn.bootstrapTable.methods = BootstrapTable.METHODS;
$.fn.bootstrapTable.utils = Utils; // BOOTSTRAP TABLE INIT
// =======================
$(function () {
$('[data-toggle="table"]').bootstrapTable();
});
return BootstrapTable;
}));
|
function ChoseFile(buttonName) {
document.getElementById(buttonName).click();
}
function ReadImageData(img, fileobj) {
// img -- image element
img.onload = function() {}
var reader = new FileReader();
reader.onload = function(evt) {
img.src = evt.target.result;
}
reader.readAsDataURL(fileobj);
}
function PreviewImage(file, canvasname) {
if (file.files && file.files[0]) {
var img = document.getElementById(canvasname);
var reader = new FileReader();
reader.onload = function(evt) {
img.src = evt.target.result;
}
reader.readAsDataURL(file.files[0]);
}
}
function UpdateBlendCanvas() {
var source_canvas = document.getElementById("source_canvas");
var mask_canvas = document.getElementById("mask_canvas");
var blend_canvas = document.getElementById("blend_canvas");
// Make sure blend canvas is big enough !
blend_canvas.height = Math.max(source_canvas.height, mask_canvas.height);
blend_canvas.width = Math.max(source_canvas.width, mask_canvas.width);
if (source_canvas.src.length > 64 && mask_canvas.src.length > 64) {
// Empty image object length is 42, base64 length is at least 64 !
var need_blend_update = 0;
var ctx = blend_canvas.getContext('2d');
ctx.drawImage(mask_canvas, 0, 0, mask_canvas.width, mask_canvas.height);
var maskimg = ctx.getImageData(0, 0, mask_canvas.width, mask_canvas.height);
ctx.drawImage(source_canvas, 0, 0, source_canvas.width, source_canvas.height);
var sourceimg = ctx.getImageData(0, 0, source_canvas.width, source_canvas.height);
for (var i = 0 , len = Math.min(maskimg.data.length, sourceimg.data.length) ; i < len ; i += 4 ) {
if (maskimg.data[i] > 128 && maskimg.data[i + 1] > 128 && maskimg.data[i + 2] > 128) {
sourceimg.data[i] = maskimg.data[i];
sourceimg.data[i + 1] = maskimg.data[i + 1];
sourceimg.data[i + 2] = maskimg.data[i + 2];
sourceimg.data[i + 3] = maskimg.data[i + 3];
need_blend_update = 1;
}
}
if (need_blend_update) {
ctx.putImageData(sourceimg, 0 , 0);
}
}
}
|
// Call the dataTables jQuery plugin
$(document).ready(function() {
$('#dataTable').DataTable({
"order": [[0, "desc"]]
});
});
|
import * as React from "react"
import { Link } from "gatsby"
const Layout = ({ location, title, children }) => {
const rootPath = `${__PATH_PREFIX__}/`
const isRootPath = location.pathname === rootPath
let header
if (isRootPath) {
header = (
<h1 className="main-heading">
<Link to="/">{title}</Link>
</h1>
)
} else {
header = (
<Link className="header-link-home" to="/">
{title}
</Link>
)
}
return (
<div className="global-wrapper" data-is-root-path={isRootPath}>
<header className="global-header">{header}</header>
<main>{children}</main>
<footer>
© {new Date().getFullYear()}, Matthew Grube
</footer>
</div>
)
}
export default Layout
|
const fs = require ("fs");
const utils = require ("daveutils");
const feedRead = require ("davefeedread");
const urlTestFeed = "http://feeds.wnyc.org/radiolab";
const timeOutSecs = 30;
const whenstart = new Date ();
feedRead.parseUrl (urlTestFeed, timeOutSecs, function (err, theFeed) {
if (err) {
console.log (err.message);
}
else {
console.log ("It took " + utils.secondsSince (whenstart) + " seconds to read and parse the feed.");
var item = theFeed.items [0];
var rssguid = item ["rss:guid"];
console.log ("rssguid == " + utils.jsonStringify (rssguid));
console.log ("theFeed.head == " + utils.jsonStringify (theFeed.head));
console.log ("theFeed.items [0] == " + utils.jsonStringify (theFeed.items [0]));
theFeed.items.forEach (function (item, i) {
console.log ("Item #" + utils.padWithZeros (i, 2) + ": " + item.title + ".");
});
fs.writeFile ("feed.xml", utils.jsonStringify (theFeed), function (err) {
});
}
});
|
import React, { useState, useContext, useEffect } from "react";
import { Paper, ButtonGroup, IconButton, Button } from "@material-ui/core";
import { Link } from "react-router-dom";
import ModeCommentOutlinedIcon from '@material-ui/icons/ModeCommentOutlined';
import ThumbDownOutlinedIcon from '@material-ui/icons/ThumbDownOutlined';
import ThumbUpOutlinedIcon from '@material-ui/icons/ThumbUpOutlined';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import TimeGenerator from './../../TimeGenerator';
import defaultLogo from "./../../headspicture/defaulthead.png";
import "./styles.css";
import { getUniversityById, addCommentUniversity } from "./../../../action/university";
import { createComment, deleteCommentById, setLikeCommentById, removeCommentById } from "./../../../action/comment";
import { getUserById, addCommentUser, deleteUserById, deleteLikeCommentUser, addDislikeCommentUser, deleteDislikeCommentUser } from "./../../../action/user";
import UserContext from "./../../UserContext";
const log = console.log;
class MessageCard extends React.Component {
state = {
objectUser: undefined,
yourComment: undefined,
thisComment: undefined,
thumbUp: false,
thumbDown: false,
deleted: false,
deletedUser: false,
loading: true,
comment: {
click: false,
content: ''
}
}
constructor(props) {
super(props);
}
onClickThuUp = (e) => {
if (!this.props.user){
return;
}
const com_like = { like: this.state.thisComment.like };
if (this.state.thumbUp) {
com_like.like --;
this.setState(prevState => {return {...prevState, thumbUp: false} })
setLikeCommentById(this.state.thisComment._id, com_like).then(result => {
this.setState(prevState => {return {...prevState, thisComment: result.comment} });
})
} else {
com_like.like ++;
if (this.state.thumbDown) {
com_like.like ++;
this.setState(prevState => {return {...prevState, thumbDown: false} })
}
this.setState(prevState => {return {...prevState, thumbUp: true} })
setLikeCommentById(this.state.thisComment._id, com_like).then(result => {
this.setState(prevState => {return {...prevState, thisComment: result.comment} });
})
}
}
onClickThuDown = (e) => {
if (!this.props.user){
return;
}
const com_like = { like: this.state.thisComment.like };
if (this.state.thumbDown) {
com_like.like ++;
this.setState(prevState => {return {...prevState, thumbDown: false} });
setLikeCommentById(this.state.thisComment._id, com_like).then(result => {
this.setState(prevState => {return {...prevState, thisComment: result.comment} });
})
} else {
com_like.like --;
if (this.state.thumbUp) {
com_like.like --;
this.setState(prevState => {return {...prevState, thumbUp: false} });
}
this.setState(prevState => {return {...prevState, thumbDown: true} });
setLikeCommentById(this.state.thisComment._id, com_like).then(result => {
this.setState(prevState => {return {...prevState, thisComment: result.comment} });
})
}
}
onClickComment = (e) => {
if (!this.props.user){
return;
}
if (this.state.comment.click) {
this.setState(prevState => {return {...prevState, comment: {...this.state.comment, click: false}} });
} else {
this.setState(prevState => {return {...prevState, comment: {...this.state.comment, click: true}} });
}
}
onClickRespond = () => {
if (!this.props.user) {
return;
}
const nComment = document.getElementById("newusercommentcard__submit").value;
if (nComment === '') {
return;
} else {
const newComment = {
author: this.props.user._id,
university: this.state.thisComment.university,
respond: this.state.thisComment._id,
under: this.state.thisComment.under,
time: new Date(),
content: nComment
};
createComment(newComment).then(com => {
const comment = com.result;
addCommentUser(comment._id).then(result => {
const newUser = result.user;
addCommentUniversity(newComment.university, comment._id).then( result => {
this.props.app.setState(prevState => {return {...prevState, user: newUser} });
this.setState(prevState => {return {...prevState, comment: {...this.state.comment, click: false}} });
})
})
})
}
}
userProfile = () => {
if (this.state.comment.click) {
return (
<Paper className="newUser" elevation={2}>
<Link
className="newUser__link"
to={this.props.user? `/user/${this.props.user._id}` : '/login'}
>
<img src={this.props.user.profile.image !== ""? this.props.user.profile.image : defaultLogo} className="userImage" />
</Link>
<textarea
id="newusercommentcard__submit"
className="newUser__comment"
placeholder="write down your response here..."
>
</textarea>
<div className="newUser__buttonPos">
<Button
className="newUser__button"
variant="contained"
color="secondary"
onClick={this.onClickRespond}
>
Respond
</Button>
</div>
</Paper>
);
}
}
componentDidMount() {
const comment = this.props.comment;
if (this.props.report) {
getUserById(comment.author).then(result => {
const objectUser = result.user;
this.setState(prevState => {return {
...prevState,
objectUser: objectUser,
thisComment: comment,
thumbUp: false,
thumbDown: false,
deleted: comment.deleted,
deletedUser: objectUser.deleted,
loading: false}
})
})
} else {
getUserById(comment.com.author).then(result => {
const objectUser = result.user;
this.setState(prevState => {return {
...prevState,
objectUser: objectUser,
yourComment: comment.res,
thisComment: comment.com,
thumbUp: false,
thumbDown: false,
deleted: comment.com.deleted,
loading: false}
})
})
}
}
deleteComment = (e) => {
const deleted = { deleted: !this.state.thisComment.deleted }
this.setState(prevState => {return {...prevState, loading: true}});
deleteCommentById(this.state.thisComment._id, deleted).then(result => {
this.setState(prevState => {return {...prevState, deleted: deleted.deleted, loading: false}});
})
}
showDelete = () => {
if (this.props.login && this.props.user.admin) {
return (
<div>
{this.state.loading? <div/> : <div className="user__icon">
<IconButton
className="user__iconButton"
onClick={this.deleteComment}
>
<DeleteForeverIcon
className={ this.state.deleted ? "red__color" : "initial__color" }
fontSize="small"
/>
</IconButton>
</div>}
</div>
);
}
}
deleteUser = (e, r) => {
if (r === 'clickaway') {
return;
}
const deleted = { deleted: !this.state.objectUser.deleted }
this.setState(prevState => {return {...prevState, loading: true}});
deleteUserById(this.state.objectUser._id, deleted).then(result => {
const newUser = result.user;
removeCommentById(this.state.thisComment._id).then(result => {
this.setState(prevState => {return {...prevState, deletedUser: deleted.deleted, objectUser: newUser, loading: false}});
const newReports = this.props.app.state.reports.filter(report => {return report._id === result.comment._id})
this.props.app.setState(prevState => {return {...prevState, reports: newReports}});
})
})
}
render() {
return (
<div>
{this.state.loading? <div/> : <div className="MessageCard">
<Paper
className={this.state.comment.click ? "messageCard__paper longHeight" : "messageCard__paper shortHeight" }
elevation={3}
>
<div className="messageCard__content">
<Link
className="user__link"
to={`/user/${this.state.objectUser._id}`}
>
<img src={this.state.objectUser.profile.image === ""? defaultLogo : this.state.objectUser.profile.image} className="userImage" />
</Link>
<div className="messageCard__leftItem">
<div className="user__description">
<div className="user__nameTime">
<Link
className="user__username"
to={`/user/${this.state.objectUser._id}`}
>
{`${this.state.objectUser.name}`}
</Link>
</div>
<span className="user__comment"> {this.props.report? "Reports" : "Comments you"} </span>
<span className="user__commentItem"> {this.state.thisComment.content} </span>
{this.props.report? <div className="button__group">
<span className="user__time"> {`${TimeGenerator(this.state.thisComment.time)}`} </span>
</div> : <div className="button__group">
<span className="user__time"> {`${TimeGenerator(this.state.thisComment.time)}`} </span>
<div className="user__icon">
<IconButton
className="user__iconButton"
onClick={this.onClickComment}
>
<ModeCommentOutlinedIcon
className={ this.state.comment.click ? "blue__color" : "initial__color" }
fontSize="small"
/>
</IconButton>
</div>
<div className="user__icon">
<IconButton
className="user__iconButton"
onClick={this.onClickThuUp}
>
<ThumbUpOutlinedIcon
className={ this.state.thumbUp ? "red__color" : "initial__color" }
fontSize="small"
/>
</IconButton>
</div>
<span className="like__num"> {`${this.state.thisComment.like}`} </span>
<div className="user__icon">
<IconButton
className="user__iconButton"
onClick={this.onClickThuDown}
>
<ThumbDownOutlinedIcon
className={ this.state.thumbDown ? "red__color" : "initial__color" }
fontSize="small"
/>
</IconButton>
</div>
{this.showDelete()}
</div>}
</div>
</div>
<div className="messageCard__divider">
</div>
<div className="messageCard__RightItem">
{this.props.report? <Button variant="contained" color="secondary" onClick={this.deleteUser}>{this.state.deletedUser? "Unblock" : "Block"}</Button> : `${this.state.yourComment.content}`}
</div>
{this.userProfile()}
</div>
</Paper>
</div>}
</div>
);
}
}
export default MessageCard;
|
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-skipped.case
// - src/dstr-binding/default/async-gen-func-named-expr-dflt.template
/*---
description: Destructuring initializer is not evaluated when value is not `undefined` (async generator named function expression (default parameter))
esid: sec-asyncgenerator-definitions-evaluation
features: [async-iteration]
flags: [generated, async]
info: |
AsyncGeneratorExpression : async [no LineTerminator here] function * BindingIdentifier
( FormalParameters ) { AsyncGeneratorBody }
[...]
7. Let closure be ! AsyncGeneratorFunctionCreate(Normal, FormalParameters,
AsyncGeneratorBody, funcEnv, strict).
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
[...]
[...]
---*/
var initCount = 0;
function counter() {
initCount += 1;
}
var callCount = 0;
var f;
f = async function* h({ w = counter(), x = counter(), y = counter(), z = counter() } = { w: null, x: 0, y: false, z: '' }) {
assert.sameValue(w, null);
assert.sameValue(x, 0);
assert.sameValue(y, false);
assert.sameValue(z, '');
assert.sameValue(initCount, 0);
callCount = callCount + 1;
};
f().next().then(() => {
assert.sameValue(callCount, 1, 'invoked exactly once');
}).then($DONE, $DONE);
|
const axios = require('axios');
const keys = require('../config/APIkeys');
async function requestGasPrice(){
var gasPrice;
await axios.get('https://www.etherchain.org/api/gasPriceOracle')
.then(function (response) {
gasPrice = response.data;
})
.catch(function (error) {
console.log(error);
});
return gasPrice
}
async function requestData(){
var map = {};
await axios({
methods: 'GET',
url: keys.API.url,
headers: {
'X-CMC_PRO_API_KEY': keys.API.key
},
json: true,
gzip: true
}).then(res => {
console.log("Doing API request (data)");
const noStatus = res.data.data;
for(let x of noStatus){
map[x.symbol] = {
latestPrice: x.quote.USD.price,
change24h: x.quote.USD.percent_change_24h,
change7d: x.quote.USD.percent_change_7d,
marketCap: x.quote.USD.market_cap,
volume24h: x.quote.USD.volume_24h,
name: x.name,
circulatingSuply: x.circulating_supply,
totalSuply: x.total_supply,
id: x.id
};
}
});
return map;
};
async function requestInfo(id){
var info;
await axios({
methods: 'GET',
url: `https://pro-api.coinmarketcap.com/v1/cryptocurrency/info?id=${id}`,
headers: {
'X-CMC_PRO_API_KEY': keys.API.key
},
json: true,
gzip: true
}).then(res => {
console.log("Doing API request (info)");
info = res.data.data[id].logo;
});
return info;
};
async function requestAddressInfo(address){
var result = {};
await axios({
methods: 'GET',
url: keys.APIADDRESS.url + `${address}?apiKey=freekey`,
json: true,
gzip: true
}).then(res => {
console.log("Doing API request (address)");
result = {
balance: res.data['ETH'].balance,
price: res.data['ETH'].price.rate,
storjName: res.data.tokens[0].tokenInfo.symbol,
storjAmount: res.data.tokens[0].balance,
storjPrice: res.data.tokens[0].tokenInfo.price.rate,
storjDecimals: res.data.tokens[0].tokenInfo.decimals
}
});
return result;
}
async function requestRealTimeData(pair){
var result = {};
await axios({
methods: 'GET',
url: keys.APIV2.url + pair,
headers: {
'X-MBX-APIKEY': keys.APIV2.key
},
json: true,
gzip: true
}).then(res => {
console.log("Doing API request (real time data)");
result = {
priceChange: res.data.priceChange,
priceChangePercent: res.data.priceChangePercent,
lastPrice: res.data.lastPrice,
openPrice: res.data.openPrice,
highPrice: res.data.highPrice,
lowPrice: res.data.lowPrice,
volume: res.data.volume
}
});
return result;
}
module.exports = { requestData, requestGasPrice, requestInfo, requestAddressInfo, requestRealTimeData };
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("placeholder","cy",{title:"Priodweddau'r Daliwr Geiriau",toolbar:"Daliwr Geiriau",name:"Enw'r Daliwr Geiriau",invalidName:"Dyw'r daliwr geiriau methu â bod yn wag ac na all gynnyws y nodau [, ], \x3c, \x3e ",pathName:"daliwr geiriau"});
|
// Imports: GraphQL
import { gql } from "apollo-server-express";
// GraphQL: TypeDefs
const typeDefs = gql`
type Company {
_id: String!
name: String
email: String
password: String
hash: String
description: String
data: String
}
type User {
_id: String!
name: String
email: String
cedula: String
registradoPor: String
hash: String
description: String
data: String
}
type Certificate {
_id: String!
type: String
userId: String
description: String
medic: String
companyName: String
hash: String
data: String
}
type Query {
allCompanies: [Company!]!
allUsers: [User!]!
allCertificates: [Certificate!]!
allUsersFromCompany(registradoPor: String): [User!]!
allCertificatesFromCompany(companyName: String): [Certificate!]!
getUserCompany(email: String, password: String): [Company!]!
getCompanyById(_id: String): [Company!]!
getUserById(_id: String): [User!]!
getCertificateById(_id: String): [Certificate!]!
getCertificateByHash(hash: String): [Certificate!]!
getCertificateByUserId(userId: String): [Certificate!]!
}
type Mutation {
createUser(
name: String!
email: String
cedula: String
registradoPor: String
): User!
createCompany(name: String!, email: String, password: String): Company!
createCertificate(type: String!, userId: String, description: String, medic: String!, companyName: String, hash: String): Certificate!
}
`;
// Exports
export default typeDefs;
|
// ==UserScript==
// @name backpack.tf - Miscellaneous Extensions
// @description Adds more options for sorting items in backpacks (currently Sorting for paints, spells, levels, scm price, classified listings) and other stuff which I would have liked (including highlighting spells, autocompleting spell names, autocompleting particle names or sorting unusuals by class)
// @version 0.1.25
// @author Netroscript
// @namespace https://github.com/NetroScript
// @include /^https?:\/\/backpack\.tf\/.*
// @downloadURL https://github.com/NetroScript/backpack.tf-miscellaneous-extensions/raw/master/backpack.tf%20extended%20sorting.user.js
// @updateURL https://github.com/NetroScript/backpack.tf-miscellaneous-extensions/raw/master/backpack.tf%20extended%20sorting.meta.js
// @grant none
// @run-at document-end
// ==/UserScript==
(function () {
"use strict";
const Voices = 'Voices from Below';
const DieJob = 'Die Job';
const Corruption = 'Chromatic Corruption';
const Pigmentation = 'Putrescent Pigmentation';
const Spectrum = 'Spectral Spectrum';
const Sinister = 'Sinister Staining';
const TeamSpirit = 'Team Spirit Footprints';
const Headless = 'Headless Horseshoes';
const CorpseGray = 'Corpse Gray Footprints';
const Violet = 'Violent Violet Footprints';
const Purple = 'Bruised Purple Footprints';
const Gangreen = 'Gangreen Footprints';
const Orange = 'Rotten Orange Footprints';
const Exorcism = 'Exorcism';
function isColor(spell) {
return [DieJob, Corruption, Pigmentation, Spectrum, Sinister].includes(spell);
}
function isFootprint(spell) {
return [TeamSpirit, Headless, CorpseGray, Violet, Purple, Gangreen, Orange].includes(spell);
}
function isExorcism(spell) {
return Exorcism === spell;
}
function isVoices(spell) {
return Voices === spell;
}
function normalize(spell1, spell2) {
const normal = [spell1, spell2];
const flip = [spell2, spell1];
const voices = isVoices(spell1) || isVoices(spell2);
const colored = isColor(spell1) || isColor(spell2);
const prints = isFootprint(spell1) || isFootprint(spell2);
if (colored && voices) {
return isColor(spell1) ? normal : flip;
} else if (prints && voices) {
return isFootprint(spell1) ? normal : flip;
} else if (prints && colored) {
return isColor(spell1) ? normal : flip;
} else {
return isExorcism(spell1) ? flip : normal;
}
}
//###############Source: https://stackoverflow.com/a/15605648
String.prototype.fmt = function (hash) {
var string = this,
key;
for (key in hash)
string = string.replace(new RegExp("\\{" + key + "\\}", "gm"), hash[key]);
return string;
};
//##############################################################
//###############Source: https://stackoverflow.com/a/4726403
function idealTextColor(bgColor) {
var nThreshold = 105;
var components = getRGBComponents(bgColor);
var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);
return ((255 - bgDelta) < nThreshold)
? "#000000"
: "#ffffff";
}
function getRGBComponents(color) {
var r = color.substring(1, 3);
var g = color.substring(3, 5);
var b = color.substring(5, 7);
return {
R: parseInt(r, 16),
G: parseInt(g, 16),
B: parseInt(b, 16)
};
}
//##############################################################
var colors = {
"A Color Similar to Slate": {
"cc": ["#2F4F4F"]
},
"A Deep Commitment to Purple": {
"cc": ["#7D4071"]
},
"A Distinctive Lack of Hue": {
"cc": ["#141414"]
},
"A Mann's Mint": {
"cc": ["#BCDDB3"]
},
"After Eight": {
"cc": ["#2D2D24"]
},
"Aged Moustache Grey": {
"cc": ["#7E7E7E"]
},
"An Extraordinary Abundance of Tinge": {
"cc": ["#E6E6E6"]
},
"Australium Gold": {
"cc": ["#E7B53B"]
},
"Color No. 216-190-216": {
"cc": ["#D8BED8"]
},
"Dark Salmon Injustice": {
"cc": ["#E9967A"]
},
"Drably Olive": {
"cc": ["#808000"]
},
"Indubitably Green": {
"cc": ["#729E42"]
},
"Mann Co. Orange": {
"cc": ["#CF7336"]
},
"Muskelmannbraun": {
"cc": ["#A57545"]
},
"Noble Hatter's Violet": {
"cc": ["#51384A"]
},
"Peculiarly Drab Tincture": {
"cc": ["#C5AF91"]
},
"Pink as Hell": {
"cc": ["#FF69B4"]
},
"Radigan Conagher Brown": {
"cc": ["#694D3A"]
},
"The Bitter Taste of Defeat and Lime": {
"cc": ["#32CD32"]
},
"The Color of a Gentlemann's Business Pants": {
"cc": ["#F0E68C"]
},
"Ye Olde Rustic Colour": {
"cc": ["#7C6C57"]
},
"Zepheniah's Greed": {
"cc": ["#424F3B"]
},
"An Air of Debonair": {
"cc": [
"#654740", "#28394D"
]
},
"Balaclavas Are Forever": {
"cc": [
"#3B1F23", "#18233D"
]
},
"Cream Spirit": {
"cc": [
"#C36C2D", "#B88035"
]
},
"Operator's Overalls": {
"cc": [
"#483838", "#384248"
]
},
"Team Spirit": {
"cc": [
"#B8383B", "#5885A2"
]
},
"The Value of Teamwork": {
"cc": [
"#803020", "#256D8D"
]
},
"Waterlogged Lab Coat": {
"cc": [
"#A89A8C", "#839FA3"
]
}
};
var spells = { //Footprints
"Footprints Spell: Team Spirit Footprints": {
"cc": [
"#B8383B", "#5885A2"
]
},
"Footprints Spell: Gangreen Footprints": {
"cc": ["#79c46b"]
},
"Footprints Spell: Corpse Gray Footprints": {
"cc": ["#8e9f9d"]
},
"Footprints Spell: Violent Violet Footprints": {
"cc": ["#f7b4fe"]
},
"Footprints Spell: Rotten Orange Footprints": {
"cc": ["#CF7336"]
},
"Footprints Spell: Bruised Purple Footprints": {
"cc": ["#7D4071"]
},
"Footprints Spell: Headless Horseshoes": {
"cc": ["#ba76ff"]
}, //Paint changing
"Paint Spell: Die Job": {
"cc": [
"#E7B53B", "#8586ff"
]
},
"Paint Spell: Spectral Spectrum": {
"cc": [
"#B8383B", "#5885A2"
]
},
"Paint Spell: Putrescent Pigmentation": {
"cc": [
"#79c46b", "#67B037"
]
},
"Paint Spell: Sinister Staining": {
"cc": [
"#F2EF46", "#808000"
]
},
"Paint Spell: Chromatic Corruption": {
"cc": [
"#DB42BD", "#7D4071"
]
}, //Voice Changing
"Standard Spell: Voices from Below": { //this is not the official spell name but it seems the single spell names get merged into it
"cc": ["#D11959"]
},
"Standard Spell: Scout's Spectral Snarl": {
"cc": ["#acfd9e"]
},
"Standard Spell: Soldier's Booming Bark": {
"cc": ["#f48280"]
},
"Standard Spell: Pyro's Muffled Moan": {
"cc": ["#f8bbfe"]
},
"Standard Spell: Demoman's Cadaverous Croak": {
"cc": ["#90fdfd"]
},
"Standard Spell: Heavy's Bottomless Bass": {
"cc": ["#f57eff"]
},
"Standard Spell: Engineers's Gravelly Growl": {
"cc": ["#fcfd95"]
},
"Standard Spell: Medic's Blood-curdling Bellow": {
"cc": ["#f7b786"]
},
"Standard Spell: Sniper's Deep Downunder Drawl": {
"cc": ["#7c7cff"]
},
"Standard Spell: Spy's Creepy Croon": {
"cc": ["#e5e5e5"]
}, // Weapon changing
"Weapon Spell: Pumpkin Bombs": { //this is not the official spell name but it seems the single spell names get merged into it
"cc": ["#68167d"]
},
"Weapon Spell: Exorcism": {
"cc": [
"#B8383B", "#5885A2"
]
},
"Weapon Spell: Squash Rockets": {
"cc": ["#dc93ff"]
},
"Weapon Spell: Spectral Flame": {
"cc": ["#5faf53"]
},
"Weapon Spell: Sentry Quad-Pumpkins": {
"cc": ["#8b8ce9"]
},
"Weapon Spell: Gourd Grenades": {
"cc": ["#f8bb8c"]
},
"Weapon Spell: Halloween Fire": {
"cc": ["#4ef442"]
}
};
let filteri,
sIc,
filtersearchval,
filterValue,
filtertimeout,
sIc2;
if ((window.location.pathname.split("/effect/").length > 1 || window.location.pathname.startsWith("/unusuals")) && $("table.unusuallist-view").length == 0) {
let misc_ids = ["938_", "361_", "30140_", "993_", "30329_", "783_", "393_", "30646_", "451_", "339_", "54_", "315_", "590_", "316_", "605_", "30095_", "110_", "337_", "380_", "48_", "30004_"];
let items = $("li.item");
let filtervar = "All";
filteri = function () {
$(items).filter(function () {
$(items).show();
var i = $(this).attr("data-class");
if (filtervar == "misci") {
return (misc_ids.indexOf($(this).attr("data-defindex") + "_") == -1);
}
if (typeof i == "undefined" && filtervar == "Multi")
return false;
if (typeof i == "undefined")
return true;
return (i.indexOf(filtervar) == -1);
}).hide();
};
sIc = setInterval(function () {
let e = $(".form-control[placeholder='Filter items...']");
if (e.length == 1) {
e = e[0];
//Remove the old events
let c = e.cloneNode();
while (e.firstChild) {
c.appendChild(e.lastChild);
}
e.parentNode.replaceChild(c, e);
let classbuttonstemplate = `<div class="input-group-btn">
<button class="btn btn-default dropdown-toggle" id="classmenu1" role="button" data-toggle="dropdown" href="#">
<i class="stm stm-tf2"></i> <span id="className">Any
class</span>
</button>
<ul id="classmenu" class="dropdown-menu" role="menu" aria-labelledby="classmenu1">
<li><a data-class="All">Any
class</a></li>
<li><a data-class="Multi">Multi
class</a></li>
<li><a data-class="Scout">Scout</a></li>
<li><a data-class="Soldier">Soldier</a>
</li>
<li><a data-class="Pyro">Pyro</a></li>
<li><a data-class="Demoman">Demoman</a>
</li>
<li><a data-class="Heavy">Heavy</a></li>
<li><a data-class="Engineer">Engineer</a>
</li>
<li><a data-class="Medic">Medic</a></li>
<li><a data-class="Sniper">Sniper</a>
</li>
<li><a data-class="Spy">Spy</a>
</li>
<li><a data-class="misci">Miscs</a>
</li>
</ul>
</div>`;
if (window.location.pathname.startsWith("/unusuals")) {
$($("#unusual-pricelist-input-group").children()[0]).remove();
}
$("#unusual-pricelist-input-group").prepend(classbuttonstemplate);
$("#classmenu a").click(function (e) {
$("#className").text($(e.target).text());
filtervar = $(e.target).attr("data-class");
filterValue = $("#filterlist").val();
$(items).show();
if (filtervar != "All")
filteri();
$(items).filter(function () {
if (filterValue.length == 0) return false;
return ($(this).attr("data-name").toLowerCase().indexOf(filterValue.toLowerCase()) == -1);
}).hide();
});
//Bind new events
$(".form-control[placeholder='Filter items...']").on("keyup paste", function () {
clearTimeout(filtertimeout);
filtertimeout = setTimeout(function () {
filterValue = $("#filterlist").val();
$(items).show();
if (filtervar != "All")
filteri();
$(items).filter(function () {
if (filterValue.length == 0) return false;
return ($(this).attr("data-name").toLowerCase().indexOf(filterValue.toLowerCase()) == -1);
}).hide();
}, 80);
});
clearInterval(sIc);
}
}, 150);
}
// Add a trade offer link to every profile possible
let trade_link = $(".user-link").attr("data-offers-params");
if(trade_link != undefined && $("span:contains('Profile Information')").length == 1){
$(".profile .information .buttons").append(`<a class="btn btn-primary btn-xs" href="https://steamcommunity.com/tradeoffer/new/${trade_link}" target="_blank">
<i class="stm stm-steam"></i> Open trade offer</a>`);
}
if (window.location.pathname.startsWith("/profiles/") || window.location.pathname.startsWith("/id/")) {
//################################## Changes to Filtering ######################
filteri = function () { };
//Disable custom filtering if you liked the old method more, use at your own risk, I won't test anything without my filter version
let ToggleCustomFilter = true;
//Declaring Variables so they are accessible outside the scope
{
//Wait until the input is generated
if (ToggleCustomFilter)
sIc = setInterval(function () {
let e = $(".form-control[placeholder='Search...']");
if (e.length == 1) {
e = e[0];
//Remove the old events
let c = e.cloneNode();
while (e.firstChild) {
c.appendChild(e.lastChild);
}
e.parentNode.replaceChild(c, e);
//Add an attribute with information for filtering to every item
let aitems = $("#backpack .item:not('.spacer')");
let aitemsl = aitems.length;
for (let i = 0; i < aitemsl; i++) {
let d = $(aitems[i]);
let info = (d.children().last().text() + " " + d.attr("data-spell_1") + " " + d.attr("data-spell_2") + " " + d.attr("data-custom_name") + " " + d.attr("data-part_name_3") + " " + d.attr("data-part_name_2") + " " + d.attr("data-part_name_1")).toLowerCase().replace(/ undefined/g, "");
d.attr("data-filterinfo", info);
}
//Bind new events
$(".form-control[placeholder='Search...']").on("keyup paste", function () {
clearTimeout(filtertimeout);
filtertimeout = setTimeout(function () {
filteri();
}, 200);
});
//New Filter function
filteri = function () {
if (ToggleCustomFilter) {
filtersearchval = $(".form-control[placeholder='Search...']").val().toLowerCase();
$(".backpack-page").show();
let sitems = $("#backpack .item");
sitems.parent().find(".filterhidden").show();
if (filtersearchval === "")
return;
sitems.filter(function () {
if (!this.dataset.hasOwnProperty("filterinfo"))
return true;
if (!(this.dataset.filterinfo.indexOf(filtersearchval) !== -1))
return true;
return false;
}).hide().addClass("filterhidden");
}
//Hide empty backpack pages
$(".backpack-page:has(li:visible)").addClass("dhide");
$(".backpack-page").hide();
$(".dhide").show().removeClass("dhide");
};
markSpells();
//Execute the needed functions after the inventory is reloaded
$("#refresh-inventory").click(function () {
sIc2 = setInterval(function () {
let e = $(".inventory .item");
if (e.length > 0) {
//Add an attribute with information for filtering to every item
let aitems = $("#backpack .item:not('.spacer')");
let aitemsl = aitems.length;
for (let i = 0; i < aitemsl; i++) {
let d = $(aitems[i]);
let info = (d.children().last().text() + " " + d.attr("data-spell_1") + " " + d.attr("data-spell_2") + " " + d.attr("data-custom_name") + " " + d.attr("data-part_name_3") + " " + d.attr("data-part_name_2") + " " + d.attr("data-part_name_1")).toLowerCase().replace(/ undefined/g, "");
d.attr("data-filterinfo", info);
}
//Hide empty backpack pages
$(".backpack-page:has(li:visible)").addClass("dhide");
$(".backpack-page").hide();
$(".dhide").show().removeClass("dhide");
markSpells();
filteri();
clearInterval(sIc2);
}
}, 150);
});
clearInterval(sIc);
}
}, 150);
}
//##############################################################################
// Get the keyprice for later use
let matched_keyprice = $("meta[name=description]").attr("content").match(/value of ([0-9,.]+) ref, ([0-9,.]+) keys/);
let keyprice = parseFloat(matched_keyprice[1].replace(/,/g, "")) / parseFloat(matched_keyprice[2].replace(/,/g, ""));
let pagetemplate = `<div class="backpack-page">
<div class="page-number">
<div class="page-anchor" id="page{pagenum}">
</div>
<a href="#page{pagenum}" class="label label-success" style="{pagestyle}">{pagename}</a>
<span class="btn btn-primary btn-xs pull-right select-page">Select Page</span>
</div>
<ul class="item-list">
</ul>
</div>`;
var newSorts = [
[
"Group by paint", "paint", sortByPaint
],
[
"Group by spell", "spell", sortBySpell
],
[
"Group by level", "level", sortByLevel
],
[
"Group by scm", "scm", sortBySCM
],
[
"Group by classifieds", "classifieds", sortByClassifiedListing
],
[
"Group by craft number", "craftnumber", sortByCraftNumber
],
];
function sortByPaint() {
let paints = colors;
paints["Not Painted"] = {
"cc": ["#676780"]
};
paints["Hidden Items"] = {
"cc": ["#676780"]
};
for (let k in paints) {
paints[k]["items"] = [];
}
let z = $(".backpack-page .item:not(.spacer)");
paints["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
if (paints.hasOwnProperty($(z[p]).attr("data-paint_name"))) {
paints[$(z[p]).attr("data-paint_name")]["items"].push($(z[p])[0]);
} else {
paints["Not Painted"]["items"].push($(z[p])[0]);
}
}
for (let k in paints) {
paints[k]["items"] = genericItemSort("data-price", paints[k]["items"]);
}
genericSort(paints, "p");
}
var spellNormalize = [
{
"n": function (a, b) {
return normalize(a, b);
},
"id": "s"
},
{
"n": function (a, b) {
let [s1, s2] = normalize(a, b)
return [s2, s1];
},
"id": "s2"
}
]
var activeSort = 0;
function sortBySpell() {
let n = spellNormalize[activeSort]["n"];
let id = spellNormalize[activeSort]["id"];
let s = spells;
s["No Spell"] = {
"cc": ["#676780"]
};
s["Hidden Items"] = {
"cc": ["#676780"]
};
for (let k in s) {
s[k]["items"] = [];
}
let z = $(".backpack-page .item:not(.spacer)");
s["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
let sk = Object.keys(s);
if ((s.hasOwnProperty($(z[p]).attr("data-spell_1"))) && (s.hasOwnProperty($(z[p]).attr("data-spell_2")))) {
let [s1, s2] = n($(z[p]).attr("data-spell_1"), $(z[p]).attr("data-spell_2"));
let spellName = `${s1} and ${s2.slice(s2.indexOf(":") + 2)}`;
if(sk.includes(spellName)) {
s[spellName]["items"].push($(z[p])[0]);
} else {
s[spellName] = {"items": [$(z[p])[0]], "cc": [s[s1]["cc"][0], s[s2]["cc"][0]]};
}
} else if (s.hasOwnProperty($(z[p]).attr("data-spell_1"))) {
s[$(z[p]).attr("data-spell_1")]["items"].push($(z[p])[0]);
} else {
s["No Spell"]["items"].push($(z[p])[0]);
}
}
for (let k in s) {
s[k]["items"] = genericItemSort("data-price", s[k]["items"]);
}
let ns = s["No Spell"];
delete s["No Spell"];
let hi = s["Hidden Items"];
delete s["Hidden Items"];
let reducer = function (obj, key) {
obj[key] = s[key];
return obj;
};
const ordered = Object.keys(s).sort().reduce(reducer, {});
ordered["No Spell"] = ns;
ordered["Hidden Items"] = hi;
genericSort(ordered, id, true);
if (activeSort + 1 >= spellNormalize.length) {
activeSort = 0;
} else {
activeSort = activeSort + 1;
}
}
function sortByLevel() {
let l = {};
l["No Level"] = {
"cc": ["#676780"],
"items": []
};
//Add Special Colors to specific levels like this
l["Level 0"] = {
"cc": ["#DD5522"],
"items": []
};
l["Hidden Items"] = {
"cc": ["#676780"]
};
let z = $(".backpack-page .item:not(.spacer)");
l["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
if ($(z[p]).attr("data-level") !== undefined) {
let level = "Level " + $(z[p]).attr("data-level");
if (!l.hasOwnProperty(level)) {
l[level] = {
"cc": ["#676780"],
"items": []
};
}
l[level]["items"].push($(z[p])[0]);
} else {
l["No Level"]["items"].push($(z[p])[0]);
}
}
for (let k in l) {
l[k]["items"] = genericItemSort("data-price", l[k]["items"]);
}
genericSort(l, "l", true, {
"use": true,
"funct": function (a, b) {
return parseInt(a[0].split(" ")[1]) - parseInt(b[0].split(" ")[1]);
}
});
}
function sortByDefindex() {
let d = {};
d["No Defindex"] = {
"cc": ["#676780"],
"items": []
};
d["Items"] = {
"cc": ["#676780"],
"items": []
};
d["Hidden Items"] = {
"cc": ["#676780"]
};
let z = $(".backpack-page .item:not(.spacer)");
//If you want all defindexes on a single page and not a group for each defindex change the singlepage value
let singlepage = false;
d["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
if ($(z[p]).attr("data-defindex") !== undefined) {
let def = "Defindex: " + $(z[p]).attr("data-defindex");
if (!singlepage) {
if (!d.hasOwnProperty(def)) {
d[def] = {
"cc": ["#676780"],
"items": []
};
}
d[def]["items"].push($(z[p])[0]);
} else {
d["Items"]["items"].push($(z[p])[0]);
}
} else {
d["No Defindex"]["items"].push($(z[p])[0]);
}
}
if (!singlepage)
for (let k in d) {
d[k]["items"] = genericItemSort("data-price", d[k]["items"]);
}
else
for (let k in d) {
d[k]["items"] = genericItemSort("data-defindex", d[k]["items"]);
}
genericSort(d, "d", true, {
"use": true,
"funct": function (a, b) {
return parseInt(a[0].split(" ")[1]) - parseInt(b[0].split(" ")[1]);
}
});
}
function sortBySCM() {
let scm = {};
scm["SCM"] = {
"cc": ["#DD5522"],
"items": []
};
scm["Not SCM"] = {
"cc": ["#676780"],
"items": []
};
scm["Hidden Items"] = {
"cc": ["#676780"]
};
let z = $(".backpack-page .item:not(.spacer)");
scm["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
if ($(z[p]).attr("data-p_scm")) {
scm["SCM"]["items"].push($(z[p])[0]);
} else {
scm["Not SCM"]["items"].push($(z[p])[0]);
}
}
for (let k in scm) {
scm[k]["items"] = genericItemSort("data-price", scm[k]["items"]);
}
genericSort(scm, "scm", true, {
"use": true,
"funct": function(a, b) {
return parseInt(a[0].split(" ")[1]) - parseInt(b[0].split(" ")[1]);
}
});
}
function sortByClassifiedListing() {
let c = {
"Classified Listings": {},
"Unlisted Items": {},
"Hidden Items": {}
};
for (let k in c) {
c[k]["items"] = [];
c[k]["cc"] = ["#676780"];
}
let z = $(".backpack-page .item:not(.spacer)");
c["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
if ($(z[p]).attr("data-listing_price") != undefined) {
c["Classified Listings"]["items"].push($(z[p])[0]);
} else {
c["Unlisted Items"]["items"].push($(z[p])[0]);
}
}
for (let k in c) {
if (k == "Classified Listings") {
c[k]["items"] = c[k]["items"].sort((a, b) => {
return listing_price_to_scrap($(b).attr("data-listing_price")) - listing_price_to_scrap($(a).attr("data-listing_price"));
});
} else {
c[k]["items"] = genericItemSort("data-price", c[k]["items"]);
}
}
genericSort(c, "c", true);
}
function sortByCraftNumber() {
let cn = {};
cn["Craft Number"] = {
"cc": ["#DD5522"],
"items": []
};
cn["Crates"] = {
"cc": ["#676780"],
"items": []
}
cn["No Craft Number"] = {
"cc": ["#676780"],
"items": []
};
cn["Hidden Items"] = {
"cc": ["#676780"]
};
let z = $(".backpack-page .item:not(.spacer)");
cn["Hidden Items"]["items"] = $(".temp-page .item:not(.spacer)");
for (let p = 0; p < z.length; p++) {
if ($(z[p])[0].outerText.includes("#")) {
if($(z[p]).data("crate") == undefined) {
cn["Craft Number"]["items"].push($(z[p])[0]);
} else {
cn["Crates"]["items"].push($(z[p])[0]);
}
} else {
cn["No Craft Number"]["items"].push($(z[p])[0]);
}
}
for (let k in cn) {
if (k == "Craft Number") {
cn[k]["items"] = cn[k]["items"].sort((a, b) => Number($(a)[0].outerText.split("#")[1]) - Number($(b)[0].outerText.split("#")[1]));
} else {
cn[k]["items"] = genericItemSort("data-price", cn[k]["items"]);
}
}
genericSort(cn, "craftnumber", true);
}
var lasttype = "";
var sortType = "";
var text = false;
function genericItemSort(sortTyp, array, t = false) {
sortType = sortTyp;
text = t;
array.sort(function (a, b) {
// To reverse the sort, but currently no where needed so commented out
// if(toggle && sortType == osortType){
// var tmp = a;
// a = b;
// b = tmp;
// }
if (text) {
if ($(a).attr(sortType).toLowerCase() < $(b).attr(sortType).toLowerCase())
return -1;
if ($(a).attr(sortType).toLowerCase() > $(b).attr(sortType).toLowerCase())
return 1;
return 0;
}
return parseFloat($(b).attr(sortType)) - parseFloat($(a).attr(sortType));
});
return array;
}
function genericSort(o, type, hide = false, csort = {
"use": false
}) {
$(".item:not(.spacer)").detach();
$("#backpack").empty();
let a = [];
for (let k in o) {
a.push([
k, o[k]["cc"],
o[k]["items"]
]);
}
if (csort.use !== false) {
for (let i = 0; i < a.length; i++) {
if (a[i][2].length == 0) {
a.splice(i, 1);
i--;
}
}
a.sort(csort.funct);
}
if (lasttype == type) {
a.reverse();
lasttype = type + "1";
} else
lasttype = type;
for (let i = 0; i < a.length; i++) {
if (!hide || a[i][2].length != 0) {
let textcolor = "color: " + idealTextColor(a[i][1][0]) + ";";
let bgcolor = (a[i][1].length == 1)
? "background-color: " + a[i][1][0] + ";"
: "background: linear-gradient( " + a[i][1][0] + " 0%, " + a[i][1][0] + " 50%, " + a[i][1][1] + " 50%," + a[i][1][1] + " 100% );";
$("#backpack").append(pagetemplate.fmt({
pagenum: i,
pagestyle: textcolor + bgcolor,
pagename: a[i][0]
}));
for (let r = 0; r < a[i][2].length; r++) {
$("#page" + i).parent().parent().find(".item-list").append(a[i][2][r]);
}
}
}
filteri();
$(".backpack-page a:contains('Hidden Items')").parent().parent().hide().addClass("temp-page");
}
//Adding new Sorting Methods
for (let i = 0; i < newSorts.length; i++) {
$(".panel-extras #inventory-sort-menu .dropdown-menu.dropdown-menu-right.pull-right").append(`
<li id="customsort` + i + "\" data-value=\"" + newSorts[i][1] + "\"><a>" + newSorts[i][0] + `</a></li>
`);
$("#customsort" + i).click(function (e) {
let i = parseInt($(e.target).parent().attr("id").replace(/^\D+/g, ""));
$("#inventory-sort-menu").removeClass("open");
$(".current-sort").text(newSorts[i][0]);
newSorts[i][2]();
e.preventDefault();
e.stopPropagation();
});
}
//Replace Sorting
var replaceSorts = {
"defindex": sortByDefindex
};
//Stop reverse sorting when another sort was clicked on before
$(".dropdown-menu.dropdown-menu-right.pull-right li:not([id^='custom'])").click(function (e) {
if (lasttype == $(this).attr("data-value")) {
e.preventDefault();
e.stopPropagation();
let b = $("#backpack");
b.children().each(function (e, p) {
b.prepend(p);
});
} else if (replaceSorts.hasOwnProperty($(this).attr("data-value"))) {
$("#inventory-sort-menu").removeClass("open");
$(".current-sort").text($(this).text());
replaceSorts[$(this).attr("data-value")]();
e.preventDefault();
e.stopPropagation();
}
lasttype = $(this).attr("data-value");
filteri();
});
function listing_price_to_scrap(price) {
if (price == undefined) return undefined;
let out = 0;
let price_parts = price.split(",");
price_parts.forEach(part => {
part = part.trim();
if (part.indexOf("key") != -1) {
out += parseFloat(part.split(" ")[0]) * keyprice;
} else if (part.indexOf("ref") != -1) {
out += parseFloat(part.split(" ")[0]);
}
});
return out;
}
// Code to mark spells in the compare link too
let compare_observer = undefined;
let modal_observer = new MutationObserver(()=>{
if($("#active-modal").find(".modal-title").text() == "Compare inventories"){
compare_observer = new MutationObserver(()=>{
markSpells();
});
compare_observer.observe($("#inventory-cmp-bins")[0], {"childList": true});
} else {
if(compare_observer != undefined){
compare_observer.disconnect();
compare_observer = undefined;
}
}
});
modal_observer.observe($("#page-content")[0], {"childList": true});
}
if (window.location.pathname.startsWith("/classifieds")) {
markSpells();
}
function markSpells() {
$("[data-spell_1]").attr("style", "border-bottom: 6px dotted #10ff00!important");
$("[data-spell_2]").attr("style", "border-bottom: 6px dotted #ff2121!important");
}
function genMP(element) {
let query = "https://marketplace.tf/items/";
let item = $(element);
let defindex = item.attr("data-defindex");
query += defindex + ";" + item.attr("data-quality");
if (item.attr("data-craftable") !== "1")
query += ";uncraftable";
let effectid = item.attr("data-effect_id");
if (effectid !== null && effectid !== undefined) {
query += ";u" + effectid;
}
let skininfo = item.find(".item-icon");
if (skininfo.length > 0) {
skininfo = skininfo.css("background-image").match(/warpaint\/[(?!_)\S]+_[0-9]+_[0-9]+_[0-9]+\.png/g);
if (skininfo !== null) {
let skin = skininfo[0].split("_")[1];
let wear = skininfo[0].split("_")[2];
query += ";w" + wear + ";pk" + skin;
}
}
if (item.attr("data-quality_elevated") == "11")
query += ";strange";
let kstier = item.attr("data-ks_tier");
if (kstier !== null && kstier !== undefined) {
query += ";kt-" + kstier;
}
if (item.attr("data-original-title").toLowerCase().indexOf("festivized") != -1)
query += ";festive";
return query;
}
function genWeaponSearch(element) {
let query = "/premium/search?";
let item = $(element);
let name = item.attr("data-base_name");
let quality = item.attr("data-quality");
let elQuality = item.attr("data-quality_elevated") ? item.attr("data-quality_elevated") : "";
let killstreak = item.attr("data-ks_tier") ? item.attr("data-ks_tier") : 0;
let effect = item.attr("data-effect_id");
let skin = item.attr("data-paint_kit");
let skininfo = item.find(".item-icon").css("background-image").match(/warpaint\/[(?!_)\S]+_[0-9]+_[0-9]+_[0-9]+\.png/g);
let wear = skininfo[0].split("_")[2];
query += "item=" + name + "&quality=" + quality + "&texture_name=" + skin + "&wear_tier=" + wear + "&killstreak_tier=" + killstreak;
if (effect) {
query += "&particle=" + effect;
}
if (elQuality) {
query += "&elevated=" + elQuality;
}
return query;
}
let skinnames = ["Bovine Blazemaker", "War Room", "Treadplate Tormenter", "Bogtrotter", "Earth, Sky and Fire", "Team Sprayer", "Spruce Deuce", "Hickory Hole-Puncher", "Rooftop Wrangler", "Civic Duty", "Civil Servant", "Local Hero", "Mayor", "Smalltown Bringdown", "Citizen Pain", "Tartan Torpedo", "Lumber From Down Under", "Rustic Ruiner", "Barn Burner", "Homemade Heater", "Plaid Potshotter", "Country Crusher", "Iron Wood", "Shot in the Dark", "Blasted Bombardier", "Backcountry Blaster", "Antique Annihilator", "Old Country", "American Pastoral", "Reclaimed Reanimator", "Red Rock Roscoe", "Sand Cannon", "Sudden Flurry", "Psychedelic Slugger", "Purple Range", "Night Terror", "Carpet Bomber", "Woodland Warrior", "Wrapped Reviver", "Forest Fire", "Night Owl", "Woodsy Widowmaker", "Backwoods Boomstick", "King of the Jungle", "Masked Mender", "Thunderbolt", "Liquid Asset", "Shell Shocker", "Current Event", "Pink Elephant", "Flash Fryer", "Spark of Life", "Dead Reckoner", "Black Dahlia", "Sandstone Special", "Lightning Rod", "Brick House", "Aqua Marine", "Low Profile", "Turbine Torcher", "Boneyard", "Pumpkin Patch", "Macabre Web", "Autumn", "Nutcracker", "Wildwood", "Top Shelf", "High Roller's", "Coffin Nail", "Dressed to Kill", "Rainbow", "Balloonicorn", "Sweet Dreams", "Mister Cuddles", "Blue Mew", "Shot to Hell", "Torqued to Hell", "Stabbed to Hell", "Brain Candy", "Flower Power", "Killer Bee", "Warhawk", "Red Bear", "Butcher Bird", "Airwolf", "Blitzkrieg", "Corsair", "Anodized Aloha", "Bamboo Brushed", "Croc Dusted", "Leopard Printed", "Macaw Masked", "Mannana Peeled", "Park Pigmented", "Piña Polished", "Sax Waxed", "Tiger Buffed", "Yeti Coated", "Bank Rolled", "Bloom Buffed", "Bonk Varnished", "Cardboard Boxed", "Clover Camo'd", "Dream Piped", "Fire Glazed", "Freedom Wrapped", "Kill Covered", "Merc Stained", "Pizza Polished", "Quack Canvassed", "Star Crossed", "Carpet Bomber Mk.II", "Woodland Warrior Mk.II", "Wrapped Reviver Mk.II", "Forest Fire Mk.II", "Night Owl Mk.II", "Woodsy Widowmaker Mk.II", "Autumn Mk.II", "Plaid Potshotter Mk.II", "Civic Duty Mk.II", "Civil Servant Mk.II", "Dead Reckoner Mk.II", "Bovine Blazemaker Mk.II", "Backwoods Boomstick Mk.II", "Masked Mender Mk.II", "Macabre Web Mk.II", "Iron Wood Mk.II", "Nutcracker Mk.II", "Smalltown Bringdown Mk.II", "Dragon Slayer", "Smissmas Sweater", "Miami Element", "Jazzy", "Mosaic", "Cosmic Calamity", "Hana", "Uranium", "Neo Tokyo", "Hazard Warning", "Damascus & Mahogany", "Dovetailed", "Alien Tech", "Cabin Fevered", "Polar Surprise", "Bomber Soul", "Geometrical Teams", "Horror Holiday", "Spectral Shimmered", "Haunted Ghosts", "Totally Boned", "Spirit of Halloween", "Calavera Canvas", "Skull Study", "Ghost Town", "Tumor Toasted", "Electroshocked", "Seriously Snowed", "Igloo", "Gift Wrapped", "Alpine", "Snow Covered", "Sleighin' Style", "Frost Ornamented", "Smissmas Village", "Smissmas Camo", "Winterland Wrapped", "Organ-ically Hellraised", "Spider Season", "Gourdy Green", "Eyestalker", "Death Deluxe", "Portal Plastered", "Candy Coated", "Spider's Cluster", "Raving Dead", "Crawlspace Critters", "Sweet Toothed", "Helldriver", "Mummified Mimic", "Pumpkin Pied", "Spectrum Splattered", "Snowflake Swirled", "Snow Globalization", "Glacial Glazed", "Gifting Mann's Wrapping Paper", "Peppermint Swirl", "Gingerbread Winner", "Smissmas Spycrabs", "Elfin Enamel", "Frozen Aurora", "Cookie Fortress", "Frosty Delivery", "Saccharine Striped", "Starlight Serenity", "Skull Cracked", "Simple Spirits", "Searing Souls", "Sarsparilla Sprayed", "Potent Poison", "Kiln and Conquer", "Swashbuckled", "Polter-Guised", "Neon-ween", "Necromanced", "Party Phantoms", "Broken Bones", "Misfortunate"];
let svariants = [];
//Skin Name Autocomplete
//Prevent Tab changing the focus
$("#page-content").on("keydown", "input[placeholder='An exact texture name is required (Warhawk, Coffin Nail, Dressed to Kill, etc.)']", function (e) {
if (e.which == 9 || e.keyCode == 9) {
e.preventDefault();
}
});
$("#page-content").on("keyup", "input[placeholder='An exact texture name is required (Warhawk, Coffin Nail, Dressed to Kill, etc.)']", function (e) {
if (e.which == 9 || e.keyCode == 9) {
e.preventDefault();
$("input[placeholder='An exact texture name is required (Warhawk, Coffin Nail, Dressed to Kill, etc.)").val(svariants[0]);
svariants.push(svariants.shift());
$("#autocompskin").text("");
} else {
let template = "<div id=\"autocompskin\" style=\"color:gray;position: absolute;pointer-events: none;user-select: none;-moz-user-select: none;-khtml-user-select: none;-webkit-user-select: none;-o-user-select: none;transform: translate(13px, -25px);\"></div>";
svariants = [];
let int = $("input[placeholder='An exact texture name is required (Warhawk, Coffin Nail, Dressed to Kill, etc.)");
if ($("#autocompskin").length == 0) $(template).insertAfter(int);
let sl = skinnames.length;
for (let i = 0; i < sl; i++) {
if (skinnames[i].toLowerCase().startsWith(int.val().toLowerCase())) svariants.push(skinnames[i]);
}
if (svariants.length == sl || svariants.length == 0)
$("#autocompskin").text("");
else
$("#autocompskin").text(svariants[0] + " - Press Tab to autocomplete, press again for alternative suggestions");
}
});
//Modify Popover
$("body").on("mouseover", ".item", function () {
let self = this;
let id = setInterval(function () {
if ($(self).next().hasClass("popover")) {
let popover = $(self).next().find("#popover-price-links");
let id2 = setInterval(function () {
let checkingmp = popover.find(".fa-spinner").length;
if (checkingmp <= 0) {
if (popover.find("a[href^='https://marketplace.tf']").length !== 1 && popover.find(".cmpb").length < 1) {
popover.append("<a class=\"btn btn-default btn-xs cmpb\" href=\"" + genMP($(self)[0]) + "\" target=\"_blank\"><img src=\"/images/marketplace-small.png?v=2\" style='width: 13px;height: 13px;margin-top: -4px;'> Marketplace</a>");
}
if (popover.find("a[href^='/premium/search']").length !== 1 && $(self).attr("data-paint_kit")) {
popover.append("<a class=\"btn btn-default btn-xs\" href=\"" + genWeaponSearch($(self)[0]) + "\"><i class=\"fa fa-star\"></i>Skin Search</a>");
}
clearInterval(id2);
}
}, 50);
setTimeout(function () {
clearInterval(id2);
}, 1000);
clearInterval(id);
}
}, 50);
setTimeout(function () {
clearInterval(id);
}, 750);
});
// Modify Search Modal
new MutationObserver(() => {
let searchModal = $(".modal-title:contains(Advanced Search), .modal-title:contains(Build Query)").parents("#active-modal");
// The Modal which opened is the search modal
if(searchModal.length > 0) {
// Filters are loaded later, so we need to listen to the onload of the filters
new MutationObserver((mutations) => {
// Check if Loading filters text gets removed
if(mutations.some(mutation => Array.from(mutation.removedNodes.entries()).some(node => $(node).text().includes("Loading filters...")))){
let particleEffectContainer = $("#panel-particle > div");
// Add search box
particleEffectContainer.prepend("<input class=\"form-control filter-text\" id=\"particle-filter\" data-key=\"item\" type=\"text\" placeholder=\"Filter for effects\" style=\"margin-bottom: 5px;\">");
// On search hide / unhide all the elements
$("#particle-filter").keyup(() => {
let filterWord = $("#particle-filter").val().toLowerCase();
let effects = particleEffectContainer.find(".btn-multi-filter");
effects.each(function() {
let el = $(this);
el.show();
if(!el.text().toLowerCase().includes(filterWord)){
el.hide();
}
});
});
}
}).observe($(searchModal).find(".modal-body")[0], {
childList: true,
});
}
}).observe($("main")[0], {
childList: true
});
})();
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import ReduxPromise from 'redux-promise';
import reducers from './reducers';
import routes from './routes';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('.container'));
|
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implementation of DataNode for wrapping JSON data.
*
*/
goog.provide('goog.ds.JsonDataSource');
goog.require('goog.Uri');
goog.require('goog.dom');
goog.require('goog.ds.DataManager');
goog.require('goog.ds.JsDataSource');
goog.require('goog.ds.LoadState');
goog.require('goog.ds.logger');
/**
* Data source whose backing is a JSON-like service, in which
* retreiving the resource specified by URL with the additional parameter
* callback. The resource retreived is executable JavaScript that
* makes a call to the named function with a JavaScript object literal
* as the only parameter.
*
* Example URI could be:
* http://www.google.com/data/search?q=monkey&callback=mycb
* which might return the JS:
* mycb({searchresults:
* [{uri: 'http://www.monkey.com', title: 'Site About Monkeys'}]});
*
* TODO(user): Evaluate using goog.net.Jsonp here.
*
* A URI of an empty string will mean that no request is made
* and the data source will be a data source with no child nodes
*
* @param {string|goog.Uri} uri URI for the request.
* @param {string} name Name of the datasource.
* @param {string=} opt_callbackParamName The parameter name that is used to
* specify the callback. Defaults to 'callback'.
*
* @extends {goog.ds.JsDataSource}
* @constructor
*/
goog.ds.JsonDataSource = function(uri, name, opt_callbackParamName) {
goog.ds.JsDataSource.call(this, null, name, null);
if (uri) {
this.uri_ = new goog.Uri(uri);
} else {
this.uri_ = null;
}
/**
* This is the callback parameter name that is added to the uri.
* @type {string}
* @private
*/
this.callbackParamName_ = opt_callbackParamName || 'callback';
};
goog.inherits(goog.ds.JsonDataSource, goog.ds.JsDataSource);
/**
* Default load state is NOT_LOADED
* @private
*/
goog.ds.JsonDataSource.prototype.loadState_ = goog.ds.LoadState.NOT_LOADED;
/**
* Map of all data sources, needed for callbacks
* Doesn't work unless dataSources is exported (not renamed)
*/
goog.ds.JsonDataSource['dataSources'] = {};
/**
* Load or reload the backing data for this node.
* Fires the JsonDataSource
*/
goog.ds.JsonDataSource.prototype.load = function() {
if (this.uri_) {
// NOTE: "dataSources" is expose above by name so that it will not be
// renamed. It should therefore be accessed via array notation here so
// that it also doesn't get renamed and stops the compiler from complaining
goog.ds.JsonDataSource['dataSources'][this.dataName_] = this;
goog.ds.logger.info('Sending JS request for DataSource ' +
this.getDataName() + ' to ' + this.uri_);
this.loadState_ = goog.ds.LoadState.LOADING;
var uriToCall = new goog.Uri(this.uri_);
uriToCall.setParameterValue(this.callbackParamName_,
'JsonReceive.' + this.dataName_);
goog.global['JsonReceive'][this.dataName_] =
goog.bind(this.receiveData, this);
var scriptEl = goog.dom.createDom('script', {'src': uriToCall});
goog.dom.getElementsByTagNameAndClass('head')[0].appendChild(scriptEl);
} else {
this.root_ = {};
this.loadState_ = goog.ds.LoadState.NOT_LOADED;
}
};
/**
* Gets the state of the backing data for this node
* @return {goog.ds.LoadState} The state.
*/
goog.ds.JsonDataSource.prototype.getLoadState = function() {
return this.loadState_;
};
/**
* Receives data from a Json request
* @param {Object} obj The JSON data.
*/
goog.ds.JsonDataSource.prototype.receiveData = function(obj) {
this.setRoot(obj);
this.loadState_ = goog.ds.LoadState.LOADED;
goog.ds.DataManager.getInstance().fireDataChange(this.getDataName());
};
/**
* Temp variable to hold callbacks
* until BUILD supports multiple externs.js files
*/
goog.global['JsonReceive'] = {};
|
import React from 'react';
import PlusIcon from 'ps-react/PlusIcon';
export default function PlusIconExample() {
return <PlusIcon />;
}
|
/*
Copyright 2017 Ziadin Givan
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
https://github.com/givan/VvvebJs
*/
// Simple JavaScript Templating
// John Resig - https://johnresig.com/ - MIT Licensed
(function(){
var cache = {};
this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = /^[-a-zA-Z0-9]+$/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("{%").join("\t")
.replace(/((^|%})[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%}/g, "',$1,'")
.split("\t").join("');")
.split("%}").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// Provide some basic currying to the user
return data ? fn( data ) : fn;
};
})();
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
function getStyle(el,styleProp)
{
value = "";
//var el = document.getElementById(el);
if (el.style && el.style.length > 0 && el.style[styleProp])//check inline
var value = el.style[styleProp];
else
if (el.currentStyle) //check defined css
var value = el.currentStyle[styleProp];
else if (window.getComputedStyle)
{
var value = document.defaultView.getDefaultComputedStyle ?
document.defaultView.getDefaultComputedStyle(el,null).getPropertyValue(styleProp) :
window.getComputedStyle(el,null).getPropertyValue(styleProp);
}
return value;
}
function isElement(obj){
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object")/* && obj.tagName != "BODY"*/;
}
var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
if (Vvveb === undefined) var Vvveb = {};
Vvveb.defaultComponent = "_base";
Vvveb.preservePropertySections = true;
Vvveb.dragIcon = 'icon';//icon = use component icon when dragging | html = use component html to create draggable element
Vvveb.baseUrl = document.currentScript?document.currentScript.src.replace(/[^\/]*?\.js$/,''):'';
Vvveb.ComponentsGroup = {};
Vvveb.Components = {
_components: {},
_nodesLookup: {},
_attributesLookup: {},
_classesLookup: {},
_classesRegexLookup: {},
init: function(url) {
},
get: function(type) {
return this._components[type];
},
add: function(type, data) {
data.type = type;
this._components[type] = data;
if (data.nodes)
{
for (var i in data.nodes)
{
this._nodesLookup[ data.nodes[i] ] = data;
}
}
if (data.attributes)
{
if (data.attributes.constructor === Array)
{
for (var i in data.attributes)
{
this._attributesLookup[ data.attributes[i] ] = data;
}
} else
{
for (var i in data.attributes)
{
if (typeof this._attributesLookup[i] === 'undefined')
{
this._attributesLookup[i] = {};
}
if (typeof this._attributesLookup[i][ data.attributes[i] ] === 'undefined')
{
this._attributesLookup[i][ data.attributes[i] ] = {};
}
this._attributesLookup[i][ data.attributes[i] ] = data;
}
}
}
if (data.classes)
{
for (var i in data.classes)
{
this._classesLookup[ data.classes[i] ] = data;
}
}
if (data.classesRegex)
{
for (var i in data.classesRegex)
{
this._classesRegexLookup[ data.classesRegex[i] ] = data;
}
}
},
extend: function(inheritType, type, data) {
newData = data;
if (inheritData = this._components[inheritType])
{
newData = $.extend(true,{}, inheritData, data);
newData.properties = $.merge( $.merge([], inheritData.properties?inheritData.properties:[]), data.properties?data.properties:[]);
}
//sort by order
newData.properties.sort(function (a,b)
{
if (typeof a.sort === "undefined") a.sort = 0;
if (typeof b.sort === "undefined") b.sort = 0;
if (a.sort < b.sort)
return -1;
if (a.sort > b.sort)
return 1;
return 0;
});
this.add(type, newData);
},
matchNode: function(node) {
if (node.attributes.length)
{
//search for attributes
for (var i in node.attributes)
{
if (node.attributes[i])
{
attr = node.attributes[i].name;
value = node.attributes[i].value;
if (attr in this._attributesLookup)
{
component = this._attributesLookup[ attr ];
//currently we check that is not a component by looking at name attribute
//if we have a collection of objects it means that attribute value must be checked
if (typeof component["name"] === "undefined")
{
if (value in component)
{
return component[value];
}
} else
return component;
}
}
}
for (var i in node.attributes)
{
attr = node.attributes[i].name;
value = node.attributes[i].value;
//check for node classes
if (attr == "class")
{
classes = value.split(" ");
for (j in classes)
{
if (classes[j] in this._classesLookup)
return this._classesLookup[ classes[j] ];
}
for (regex in this._classesRegexLookup)
{
regexObj = new RegExp(regex);
if (regexObj.exec(value))
{
return this._classesRegexLookup[ regex ];
}
}
}
}
}
tagName = node.tagName.toLowerCase();
if (tagName in this._nodesLookup) return this._nodesLookup[ tagName ];
return false;
//return false;
},
render: function(type) {
var component = this._components[type];
var rightPanel = jQuery("#right-panel #component-properties");
var section = rightPanel.find('.section[data-section="default"]');
if (!(Vvveb.preservePropertySections && section.length))
{
rightPanel.html('').append(tmpl("vvveb-input-sectioninput", {key:"default", header:component.name}));
section = rightPanel.find(".section");
}
rightPanel.find('[data-header="default"] span').html(component.name);
section.html("")
if (component.beforeInit) component.beforeInit(Vvveb.Builder.selectedEl.get(0));
var element;
var fn = function(component, property) {
return property.input.on('propertyChange', function (event, value, input) {
var element = Vvveb.Builder.selectedEl;
if (property.child) element = element.find(property.child);
if (property.parent) element = element.parent(property.parent);
if (property.onChange)
{
element = property.onChange(element, value, input, component);
}/* else */
if (property.htmlAttr)
{
oldValue = element.attr(property.htmlAttr);
if (property.htmlAttr == "class" && property.validValues)
{
element.removeClass(property.validValues.join(" "));
element = element.addClass(value);
}
else if (property.htmlAttr == "style")
{
element = element.css(property.key, value);
}
else
{
element = element.attr(property.htmlAttr, value);
}
Vvveb.Undo.addMutation({type: 'attributes',
target: element.get(0),
attributeName: property.htmlAttr,
oldValue: oldValue,
newValue: element.attr(property.htmlAttr)});
}
if (component.onChange)
{
element = component.onChange(element, property, value, input);
}
if (!property.child && !property.parent) Vvveb.Builder.selectNode(element);
return element;
});
};
var nodeElement = Vvveb.Builder.selectedEl;
for (var i in component.properties)
{
var property = component.properties[i];
var element = nodeElement;
if (property.beforeInit) property.beforeInit(element.get(0))
if (property.child) element = element.find(property.child);
if (property.data) {
property.data["key"] = property.key;
} else
{
property.data = {"key" : property.key};
}
if (typeof property.group === 'undefined') property.group = null;
property.input = property.inputtype.init(property.data);
if (property.init)
{
property.inputtype.setValue(property.init(element.get(0)));
} else if (property.htmlAttr)
{
if (property.htmlAttr == "style")
{
//value = element.css(property.key);//jquery css returns computed style
var value = getStyle(element.get(0), property.key);//getStyle returns declared style
} else
{
var value = element.attr(property.htmlAttr);
}
//if attribute is class check if one of valid values is included as class to set the select
if (value && property.htmlAttr == "class" && property.validValues)
{
value = value.split(" ").filter(function(el) {
return property.validValues.indexOf(el) != -1
});
}
property.inputtype.setValue(value);
}
fn(component, property);
if (property.inputtype == SectionInput)
{
section = rightPanel.find('.section[data-section="' + property.key + '"]');
if (Vvveb.preservePropertySections && section.length)
{
section.html("");
} else
{
rightPanel.append(property.input);
section = rightPanel.find('.section[data-section="' + property.key + '"]');
}
}
else
{
var row = $(tmpl('vvveb-property', property));
row.find('.input').append(property.input);
section.append(row);
}
if (property.inputtype.afterInit)
{
property.inputtype.afterInit(property.input);
}
}
if (component.init) component.init(Vvveb.Builder.selectedEl.get(0));
}
};
Vvveb.WysiwygEditor = {
isActive: false,
oldValue: '',
doc:false,
init: function(doc) {
this.doc = doc;
$("#bold-btn").on("click", function (e) {
doc.execCommand('bold',false,null);
e.preventDefault();
return false;
});
$("#italic-btn").on("click", function (e) {
doc.execCommand('italic',false,null);
e.preventDefault();
return false;
});
$("#underline-btn").on("click", function (e) {
doc.execCommand('underline',false,null);
e.preventDefault();
return false;
});
$("#strike-btn").on("click", function (e) {
doc.execCommand('strikeThrough',false,null);
e.preventDefault();
return false;
});
$("#link-btn").on("click", function (e) {
doc.execCommand('createLink',false,"#");
e.preventDefault();
return false;
});
},
undo: function(element) {
this.doc.execCommand('undo',false,null);
},
redo: function(element) {
this.doc.execCommand('redo',false,null);
},
edit: function(element) {
element.attr({'contenteditable':true, 'spellcheckker':false});
$("#wysiwyg-editor").show();
this.element = element;
this.isActive = true;
this.oldValue = element.html();
},
destroy: function(element) {
element.removeAttr('contenteditable spellcheckker');
$("#wysiwyg-editor").hide();
this.isActive = false;
node = this.element.get(0);
Vvveb.Undo.addMutation({type:'characterData',
target: node,
oldValue: this.oldValue,
newValue: node.innerHTML});
}
}
Vvveb.Builder = {
dragMoveMutation : false,
isPreview : false,
runJsOnSetHtml : false,
init: function(url, callback) {
self = this;
self.loadControlGroups();
self.selectedEl = null;
self.highlightEl = null;
self.initCallback = callback;
self.documentFrame = $("#iframe-wrapper > iframe");
self.canvas = $("#canvas");
self._loadIframe(url);
self._initDragdrop();
self._initBox();
self.dragElement = null;
},
/* controls */
loadControlGroups : function() {
componentsList = $("#components-list");
componentsList.empty();
var item = {};
for (group in Vvveb.ComponentsGroup)
{
componentsList.append('<li class="header" data-section="' + group + '" data-search=""><label class="header" for="comphead_' + group + '">' + group + ' <div class="header-arrow"></div>\
</label><input class="header_check" type="checkbox" checked="true" id="comphead_' + group + '"> <ol></ol></li>');
componentsSubList = componentsList.find('li[data-section="' + group + '"] ol');
components = Vvveb.ComponentsGroup[ group ];
for (i in components)
{
componentType = components[i];
component = Vvveb.Components.get(componentType);
if (component)
{
item = $('<li data-section="' + group + '" data-type="' + componentType + '" data-search="' + component.name.toLowerCase() + '"><a href="#">' + component.name + "</a></li>");
if (component.image) {
item.css({
backgroundImage: "url(" + 'libs/builder/' + component.image + ")",
backgroundRepeat: "no-repeat"
})
}
componentsSubList.append(item)
}
}
}
},
loadUrl : function(url, callback) {
jQuery("#select-box").hide();
self.initCallback = callback;
if (self.iframe.src != url) self.iframe.src = url;
},
/* iframe */
_loadIframe : function(url) {
self.iframe = this.documentFrame.get(0);
self.iframe.src = url;
return this.documentFrame.on("load", function()
{
window.FrameWindow = self.iframe.contentWindow;
window.FrameDocument = self.iframe.contentWindow.document;
$(window.FrameWindow).on( "beforeunload", function(event) {
var dialogText = "You have unsaved changes";
event.returnValue = dialogText;
return dialogText;
});
jQuery(window.FrameWindow).on("scroll resize", function(event) {
if (self.selectedEl)
{
offset = self.selectedEl.offset();
jQuery("#select-box").css(
{"top": offset.top - self.frameDoc.scrollTop() ,
"left": offset.left - self.frameDoc.scrollLeft() ,
"width" : self.selectedEl.outerWidth(),
"height": self.selectedEl.outerHeight(),
//"display": "block"
});
}
if (self.highlightEl)
{
offset = self.highlightEl.offset();
jQuery("#highlight-box").css(
{"top": offset.top - self.frameDoc.scrollTop() ,
"left": offset.left - self.frameDoc.scrollLeft() ,
"width" : self.highlightEl.outerWidth(),
"height": self.highlightEl.outerHeight(),
//"display": "block"
});
}
});
Vvveb.WysiwygEditor.init(window.FrameDocument);
if (self.initCallback) self.initCallback();
return self._frameLoaded();
});
},
_frameLoaded : function() {
self.frameDoc = $(window.FrameDocument);
self.frameHtml = $(window.FrameDocument).find("html");
self.frameBody = $(window.FrameDocument).find("body");
this._initHighlight();
},
_getElementType: function(el) {
//search for component attribute
componentName = '';
if (el.attributes)
for (var j = 0; j < el.attributes.length; j++){
if (el.attributes[j].nodeName.indexOf('data-component') > -1)
{
componentName = el.attributes[j].nodeName.replace('data-component-', '');
}
}
if (componentName != '') return componentName;
return el.tagName;
},
loadNodeComponent: function(node) {
data = Vvveb.Components.matchNode(node);
var component;
if (data)
component = data.type;
else
component = Vvveb.defaultComponent;
Vvveb.Components.render(component);
},
selectNode: function(node) {
if (!node)
{
jQuery("#select-box").hide();
return;
}
if (self.texteditEl && self.selectedEl.get(0) != node)
{
Vvveb.WysiwygEditor.destroy(self.texteditEl);
jQuery("#select-box").removeClass("text-edit").find("#select-actions").show();
self.texteditEl = null;
}
self.selectedEl = target = jQuery(node);
offset = target.offset();
jQuery("#select-box").css(
{"top": offset.top - self.frameDoc.scrollTop() ,
"left": offset.left - self.frameDoc.scrollLeft() ,
"width" : target.outerWidth(),
"height": target.outerHeight(),
"display": "block",
});
jQuery("#highlight-name").html(self._getElementType(node));
},
/* iframe highlight */
_initHighlight: function() {
moveEvent = {target:null, };
this.frameBody.on("mousemove touchmove", function(event) {
if (event.target && isElement(event.target))
{
//moveEvent = event;
self.highlightEl = target = jQuery(event.target);
offset = target.offset();
height = target.outerHeight();
halfHeight = Math.max(height / 2, 50);
width = target.outerWidth();
halfWidth = Math.max(width / 2, 50);
if (self.isDragging)
{
parent = self.highlightEl;
//parentOffset = self.dragElement.offset();
try {
if (event.originalEvent)
{
if ((offset.top < (event.originalEvent.y - halfHeight)) || (offset.left < (event.originalEvent.x - halfWidth)))
{
if (isIE11)
self.highlightEl.append(self.dragElement);
else
self.dragElement.appendTo(parent);
} else
{
if (isIE11)
self.highlightEl.prepend(self.dragElement);
else
self.dragElement.prependTo(parent);
};
}
} catch(err) {
console.log(err);
return false;
}
if (event.originalEvent) self.iconDrag.css({'left': event.originalEvent.x + 275/*left panel width*/, 'top':event.originalEvent.y - 30 });
}// else //uncomment else to disable parent highlighting when dragging
{
jQuery("#highlight-box").css(
{"top": offset.top - self.frameDoc.scrollTop() ,
"left": offset.left - self.frameDoc.scrollLeft() ,
"width" : width,
"height": height,
"display" : event.target.hasAttribute('contenteditable')?"none":"block",
"border":self.isDragging?"1px dashed aqua":"",//when dragging highlight parent with green
});
jQuery("#highlight-name").html(self._getElementType(event.target));
if (self.isDragging) jQuery("#highlight-name").hide(); else jQuery("#highlight-name").show();//hide tag name when dragging
}
}
});
this.frameBody.on("mouseup touchend", function(event) {
if (self.isDragging)
{
self.isDragging = false;
if (self.iconDrag) self.iconDrag.remove();
if (component.dragHtml) //if dragHtml is set for dragging then set real component html
{
newElement = $(component.html);
self.dragElement.replaceWith(newElement);
self.dragElement = newElement;
}
if (component.afterDrop) self.dragElement = component.afterDrop(self.dragElement);
self.dragElement.css("border", "");
node = self.dragElement.get(0);
self.selectNode(node);
self.loadNodeComponent(node);
if (self.dragMoveMutation === false)
{
Vvveb.Undo.addMutation({type: 'childList',
target: node.parentNode,
addedNodes: [node],
nextSibling: node.nextSibling});
} else
{
self.dragMoveMutation.newParent = node.parentNode;
self.dragMoveMutation.newNextSibling = node.nextSibling;
Vvveb.Undo.addMutation(self.dragMoveMutation);
self.dragMoveMutation = false;
}
}
});
this.frameBody.on("dblclick", function(event) {
if (Vvveb.Builder.isPreview == false)
{
self.texteditEl = target = jQuery(event.target);
Vvveb.WysiwygEditor.edit(self.texteditEl);
self.texteditEl.attr({'contenteditable':true, 'spellcheckker':false});
self.texteditEl.on("blur keyup paste input", function(event) {
jQuery("#select-box").css({
"width" : self.texteditEl.outerWidth(),
"height": self.texteditEl.outerHeight()
});
});
jQuery("#select-box").addClass("text-edit").find("#select-actions").hide();
jQuery("#highlight-box").hide();
}
});
this.frameBody.on("click", function(event) {
if (Vvveb.Builder.isPreview == false)
{
if (event.target)
{
self.selectNode(event.target);
self.loadNodeComponent(event.target);
}
event.preventDefault();
return false;
}
});
},
_initBox: function() {
$("#drag-box").on("mousedown", function(event) {
jQuery("#select-box").hide();
self.dragElement = self.selectedEl;
self.isDragging = true;
node = self.dragElement.get(0);
self.dragMoveMutation = {type: 'move',
target: node,
oldParent: node.parentNode,
oldNextSibling: node.nextSibling};
//self.selectNode(false);
event.preventDefault();
return false;
});
$("#down-box").on("click", function(event) {
jQuery("#select-box").hide();
node = self.selectedEl.get(0);
oldParent = node.parentNode;
oldNextSibling = node.nextSibling;
next = self.selectedEl.next();
if (next.length > 0)
{
next.after(self.selectedEl);
} else
{
self.selectedEl.parent().after(self.selectedEl);
}
newParent = node.parentNode;
newNextSibling = node.nextSibling;
Vvveb.Undo.addMutation({type: 'move',
target: node,
oldParent: oldParent,
newParent: newParent,
oldNextSibling: oldNextSibling,
newNextSibling: newNextSibling});
event.preventDefault();
return false;
});
$("#up-box").on("click", function(event) {
jQuery("#select-box").hide();
node = self.selectedEl.get(0);
oldParent = node.parentNode;
oldNextSibling = node.nextSibling;
next = self.selectedEl.prev();
if (next.length > 0)
{
next.before(self.selectedEl);
} else
{
self.selectedEl.parent().before(self.selectedEl);
}
newParent = node.parentNode;
newNextSibling = node.nextSibling;
Vvveb.Undo.addMutation({type: 'move',
target: node,
oldParent: oldParent,
newParent: newParent,
oldNextSibling: oldNextSibling,
newNextSibling: newNextSibling});
event.preventDefault();
return false;
});
$("#clone-box").on("click", function(event) {
clone = self.selectedEl.clone();
self.selectedEl.after(clone);
self.selectedEl = clone.click();
node = clone.get(0);
Vvveb.Undo.addMutation({type: 'childList',
target: node.parentNode,
addedNodes: [node],
nextSibling: node.nextSibling});
event.preventDefault();
return false;
});
$("#parent-box").on("click", function(event) {
node = self.selectedEl.parent().get(0);
self.selectNode(node);
self.loadNodeComponent(node);
event.preventDefault();
return false;
});
$("#delete-box").on("click", function(event) {
jQuery("#select-box").hide();
node = self.selectedEl.get(0);
Vvveb.Undo.addMutation({type: 'childList',
target: node.parentNode,
removedNodes: [node],
nextSibling: node.nextSibling});
self.selectedEl.remove();
event.preventDefault();
return false;
});
},
/* drag and drop */
_initDragdrop : function() {
self.isDragging = false;
component = {};
$('#components ul > li > ol > li').on("mousedown touchstart", function(event) {
$this = jQuery(this);
$("#component-clone").remove();
component = Vvveb.Components.get($this.data("type"));
if (component.dragHtml)
{
html = component.dragHtml;
} else
{
html = component.html;
}
self.dragElement = $(html);
self.dragElement.css("border", "1px dashed #4285f4");
if (component.dragStart) self.dragElement = component.dragStart(self.dragElement);
self.isDragging = true;
if (Vvveb.dragIcon == 'html')
self.iconDrag = $(html).attr("id", "component-clone").css('position', 'absolute');
else
self.iconDrag = $('<img src=""/>').attr({"id": "component-clone", 'src': $this.css("background-image").replace(/^url\(['"](.+)['"]\)/, '$1')}).
css({'z-index':100, 'position':'absolute', 'width':'64px', 'height':'64px', 'top': event.originalEvent.y, 'left': event.originalEvent.x});
$('body').append(self.iconDrag);
event.preventDefault();
return false;
});
$('body').on('mouseup touchend', function(event) {
if (self.iconDrag && self.isDragging == true)
{
self.isDragging = false;
$("#component-clone").remove();
}
});
$('body').on('mousemove touchmove', function(event) {
if (self.iconDrag && self.isDragging == true)
{
self.iconDrag.css({'left': event.originalEvent.x - 60, 'top':event.originalEvent.y - 30});
elementMouseIsOver = document.elementFromPoint(event.clientX - 60, event.clientY - 40);
//if drag elements hovers over iframe switch to iframe mouseover handler
if (elementMouseIsOver && elementMouseIsOver.tagName == 'IFRAME')
{
self.frameBody.trigger("mousemove", event);
event.stopPropagation();
self.selectNode(false);
}
}
});
$('#components ul > ol > li > li').on("mouseup touchend", function(event) {
self.isDragging = false;
$("#component-clone").remove();
});
},
getHtml: function()
{
var doc = window.FrameDocument;
var hasDoctpe = (doc.doctype !== null);
var html = "";
if (hasDoctpe) html =
"<!DOCTYPE "
+ doc.doctype.name
+ (doc.doctype.publicId ? ' PUBLIC "' + doc.doctype.publicId + '"' : '')
+ (!doc.doctype.publicId && doc.doctype.systemId ? ' SYSTEM' : '')
+ (doc.doctype.systemId ? ' "' + doc.doctype.systemId + '"' : '')
+ ">\n";
html += doc.documentElement.innerHTML + "\n</html>";
return html;
},
setHtml: function(html)
{
//update only body to avoid breaking iframe css/js relative paths
start = html.indexOf("<body");
end = html.indexOf("</body");
if (start >= 0 && end >= 0) {
body = html.slice(html.indexOf(">", start) + 1, end);
} else {
body = html
}
if (this.runJsOnSetHtml)
self.frameBody.html(body);
else
window.FrameDocument.body.innerHTML = body;
//below methods brake document relative css and js paths
//return self.iframe.outerHTML = html;
//return self.documentFrame.html(html);
//return self.documentFrame.attr("srcdoc", html);
}
};
Vvveb.CodeEditor = {
isActive: false,
oldValue: '',
doc:false,
init: function(doc) {
$("#vvveb-code-editor textarea").val(Vvveb.Builder.getHtml());
$("#vvveb-code-editor textarea").keyup(function ()
{
delay(Vvveb.Builder.setHtml(this.value), 1000);
});
//load code on document changes
Vvveb.Builder.frameBody.on("vvveb.undo.add vvveb.undo.restore", function (e) { Vvveb.CodeEditor.setValue();});
//load code when a new url is loaded
Vvveb.Builder.documentFrame.on("load", function (e) { Vvveb.CodeEditor.setValue();});
this.isActive = true;
},
setValue: function(value) {
if (this.isActive)
{
$("#vvveb-code-editor textarea").val(Vvveb.Builder.getHtml());
}
},
destroy: function(element) {
//this.isActive = false;
},
toggle: function() {
if (this.isActive != true)
{
this.isActive = true;
return this.init();
}
this.isActive = false;
this.destroy();
}
}
Vvveb.Gui = {
init: function() {
$("[data-vvveb-action]").each(function () {
on = "click";
if (this.dataset.vvvebOn) on = this.dataset.vvvebOn;
$(this).on(on, Vvveb.Gui[this.dataset.vvvebAction]);
if (this.dataset.vvvebShortcut)
{
$(document).bind('keydown', this.dataset.vvvebShortcut, Vvveb.Gui[this.dataset.vvvebAction]);
$(window.FrameDocument, window.FrameWindow).bind('keydown', this.dataset.vvvebShortcut, Vvveb.Gui[this.dataset.vvvebAction]);
}
});
},
undo : function () {
if (Vvveb.WysiwygEditor.isActive)
{
Vvveb.WysiwygEditor.undo();
} else
{
Vvveb.Undo.undo();
}
Vvveb.Builder.selectNode();
},
redo : function () {
if (Vvveb.WysiwygEditor.isActive)
{
Vvveb.WysiwygEditor.redo();
} else
{
Vvveb.Undo.redo();
}
Vvveb.Builder.selectNode();
},
save : function ()
{
var short_title = $("#left-panel .tree li.active")[0].getAttribute('data-page');
var title = $("#left-panel .tree li.active")[0].getAttribute('data-title');
$.ajax({
type: "POST",
url: 'saveResumeInHTMLFile.php',
data: {html: Vvveb.Builder.getHtml(), short_title: short_title, title: title},
success: function(data){
console.log('enregistrement d\'un CV');
location.reload(true); //on recharge la page pour faire apparaitre le nouveau CV dans "mes CVs"
}
});
},
download : function () {
filename = /[^\/]+$/.exec(Vvveb.Builder.iframe.src)[0];
uriContent = "data:application/octet-stream," + encodeURIComponent(Vvveb.Builder.getHtml());
var link = document.createElement('a');
if ('download' in link)
{
link.download = filename;
link.href = uriContent;
link.target = "_blank";
document.body.appendChild(link);
result = link.click();
document.body.removeChild(link);
link.remove();
} else
{
location.href = uriContent;
}
},
pdf : function (){
var short_title = $("#left-panel .tree li.active")[0].getAttribute('data-page');
var title = $("#left-panel .tree li.active")[0].getAttribute('data-title');
$.ajax({
type: "POST",
url: 'downloadPdf.php',
data: {html: Vvveb.Builder.getHtml(), short_title: short_title, title: title},
success: function(data){
console.log('export pdf d\'un CV');
setTimeout(function() {
url = 'http://localhost/mycvproject/'+short_title;
downloadFile(url);
}, 2000);
window.downloadFile = function (sUrl) {
if (/(iP)/g.test(navigator.userAgent)) {
window.open(sUrl, '_blank');
return false;
}
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
var link = document.createElement('a');
link.href = sUrl;
link.setAttribute('target','_blank');
if (link.download !== undefined) {
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
if (sUrl.indexOf('?') === -1) {
sUrl += '?download';
}
window.open(sUrl, '_blank');
return true;
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
$.ajax({
type: "POST",
url: 'deletePdf.php',
data: {short_title: short_title},
success: function(data) {
console.log('delete pdf');
}
});
}
});
},
viewport : function () {
$("#canvas").attr("class", this.dataset.view);
},
toggleEditor : function () {
$("#resume-editor").toggleClass("bottom-panel-expand");
$("#toggleEditorJsExecute").toggle();
Vvveb.CodeEditor.toggle();
},
toggleEditorJsExecute : function () {
Vvveb.Builder.runJsOnSetHtml = this.checked;
},
preview : function () {
(Vvveb.Builder.isPreview == true)?Vvveb.Builder.isPreview = false:Vvveb.Builder.isPreview = true;
$("#iframe-layer").toggle();
$("#resume-editor").toggleClass("preview");
},
fullscreen : function () {
launchFullScreen(document); // the whole page
},
componentSearch : function () {
searchText = this.value;
$("#components-list li ol li").each(function () {
$this = $(this);
$this.hide();
if ($this.data("search").indexOf(searchText) > -1) $this.show();
});
},
clearComponentSearch : function () {
$("#component-search").val("").keyup();
}
}
Vvveb.ResumeManager = {
tree:false,
resumes:{},
currentResume: false,
init: function() {
this.tree = $("#resumemanager .tree > ol").html("");
$(this.tree).on("click", "a", function (e) {
e.preventDefault();
return false;
});
//clic droit (modifier nom & supprimer)
$(this.tree).bind('contextmenu', function(e)
{
//TODO SHOW POPUP
var resumeTitle = e.target.innerHTML;
var resumeId = e.target.offsetParent.dataset.id;
console.log('resumeTitle = ',resumeTitle);
console.log('resumeId = ',resumeId);
$('#resumeTitle').val(resumeTitle);
$('#resumeId').val(resumeId);
$('#manage-modal').modal('show');
e.preventDefault();
return false;
});
$(this.tree).on("click", "li[data-page] label", function (e) {
var page = $(this.parentNode).data("page");
if (page) Vvveb.ResumeManager.loadPage(page);
return false;
});
$(this.tree).on("click", "li[data-component] label ", function (e) {
node = $(e.currentTarget.parentNode).data("node");
Vvveb.Builder.frameHtml.animate({
scrollTop: $(node).offset().top
}, 1000);
Vvveb.Builder.selectNode(node);
Vvveb.Builder.loadNodeComponent(node);
//e.preventDefault();
//return false;
}).on("mouseenter", "li[data-component] label", function (e) {
node = $(e.currentTarget).data("node");
$(node).trigger("mousemove");
});
},
addResume: function(id, name, title, url) {
if(!id)
{
id = 0;
}
this.resumes[name] = {title:title, url:url};
this.tree.append(
tmpl("vvveb-resumemanager-page", {id:id, name:name, title:title, url:url}));
},
addResumes: function(resumes) {
for (resume in resumes)
{
this.addResume(resumes[resume]['name'], resumes[resume]['title'], resumes[resume]['url']);
}
},
addComponent: function(name, url, title, page) {
$("[data-page='" + page + "'] > ol", this.tree).append(
tmpl("vvveb-filemanager-component", {name:name, url:url, title:title}));
},
getComponents: function() {
var tree = [];
function getNodeTree (node, parent) {
if (node.hasChildNodes()) {
for (var j = 0; j < node.childNodes.length; j++) {
child = node.childNodes[j];
if (child && child["attributes"] != undefined &&
(matchChild = Vvveb.Components.matchNode(child)))
{
element = {
name: matchChild.name,
image: matchChild.image,
type: matchChild.type,
node: child,
children: []
};
element.children = [];
parent.push(element);
element = getNodeTree(child, element.children);
} else
{
element = getNodeTree(child, parent);
}
}
}
return false;
}
getNodeTree(window.FrameDocument.body, tree);
return tree;
},
loadComponents: function() {
tree = this.getComponents();
html = drawComponentsTree(tree);
function drawComponentsTree(tree)
{
var html = $("<ol></ol>");
j++;
for (i in tree)
{
var node = tree[i];
if (tree[i].children.length > 0)
{
var li = $('<li data-component="' + node.name + '">\
<label for="id' + j + '" style="background-image:url(libs/builder/' + node.image + ')"><span>' + node.name + '</span></label>\
<input type="checkbox" id="id' + j + '">\
</li>');
li.data("node", node.node);
li.append(drawComponentsTree(node.children));
html.append(li);
}
else
{
var li =$('<li data-component="' + node.name + '" class="file">\
<label for="id' + j + '" style="background-image:url(libs/builder/' + node.image + ')"><span>' + node.name + '</span></label>\
<input type="checkbox" id="id' + j + '"></li>');
li.data("node", node.node);
html.append(li);
}
}
return html;
}
$("[data-page='" + this.currentPage + "'] > ol", this.tree).replaceWith(html);
},
loadPage: function(name) {
$("[data-page]", this.tree).removeClass("active");
$("#filemanager .tree li.active").removeClass("active");
$("[data-page='" + name + "']", this.tree).addClass("active");
this.currentPage = name;
Vvveb.Builder.loadUrl(this.resumes[name]['url'],
function () {
Vvveb.ResumeManager.loadComponents();
});
}
}
Vvveb.FileManager = {
tree:false,
pages:{},
currentPage: false,
init: function() {
this.tree = $("#filemanager .tree > ol").html("");
$(this.tree).on("click", "a", function (e) {
e.preventDefault();
return false;
});
$(this.tree).on("click", "li[data-page] label", function (e) {
var page = $(this.parentNode).data("page");
if (page) Vvveb.FileManager.loadPage(page);
return false;
})
$(this.tree).on("click", "li[data-component] label ", function (e) {
node = $(e.currentTarget.parentNode).data("node");
Vvveb.Builder.frameHtml.animate({
scrollTop: $(node).offset().top
}, 1000);
Vvveb.Builder.selectNode(node);
Vvveb.Builder.loadNodeComponent(node);
//e.preventDefault();
//return false;
}).on("mouseenter", "li[data-component] label", function (e) {
node = $(e.currentTarget).data("node");
$(node).trigger("mousemove");
});
},
addPage: function(name, title, url) {
this.pages[name] = {title:title, url:url};
this.tree.append(
tmpl("vvveb-filemanager-page", {name:name, title:title, url:url}));
},
addPages: function(pages) {
for (page in pages)
{
this.addPage(pages[page]['name'], pages[page]['title'], pages[page]['url']);
}
},
addComponent: function(name, url, title, page) {
$("[data-page='" + page + "'] > ol", this.tree).append(
tmpl("vvveb-filemanager-component", {name:name, url:url, title:title}));
},
getComponents: function() {
var tree = [];
function getNodeTree (node, parent) {
if (node.hasChildNodes()) {
for (var j = 0; j < node.childNodes.length; j++) {
child = node.childNodes[j];
if (child && child["attributes"] != undefined &&
(matchChild = Vvveb.Components.matchNode(child)))
{
element = {
name: matchChild.name,
image: matchChild.image,
type: matchChild.type,
node: child,
children: []
};
element.children = [];
parent.push(element);
element = getNodeTree(child, element.children);
} else
{
element = getNodeTree(child, parent);
}
}
}
return false;
}
getNodeTree(window.FrameDocument.body, tree);
return tree;
},
loadComponents: function() {
tree = this.getComponents();
html = drawComponentsTree(tree);
function drawComponentsTree(tree)
{
var html = $("<ol></ol>");
j++;
for (i in tree)
{
var node = tree[i];
if (tree[i].children.length > 0)
{
var li = $('<li data-component="' + node.name + '">\
<label for="id' + j + '" style="background-image:url(libs/builder/' + node.image + ')"><span>' + node.name + '</span></label>\
<input type="checkbox" id="id' + j + '">\
</li>');
li.data("node", node.node);
li.append(drawComponentsTree(node.children));
html.append(li);
}
else
{
var li =$('<li data-component="' + node.name + '" class="file">\
<label for="id' + j + '" style="background-image:url(libs/builder/' + node.image + ')"><span>' + node.name + '</span></label>\
<input type="checkbox" id="id' + j + '"></li>');
li.data("node", node.node);
html.append(li);
}
}
return html;
}
$("[data-page='" + this.currentPage + "'] > ol", this.tree).replaceWith(html);
},
getCurrentUrl: function() {
if (this.currentPage)
return this.pages[this.currentPage]['url'];
},
reloadCurrentPage: function() {
if (this.currentPage)
return this.loadPage(this.currentPage);
},
loadPage: function(name, disableCache = true) {
$("[data-page]", this.tree).removeClass("active");
$("#resumemanager .tree li.active").removeClass("active");
$("[data-page='" + name + "']", this.tree).addClass("active");
this.currentPage = name;
var url = this.pages[name]['url'];
Vvveb.Builder.loadUrl(url + (disableCache ? (url.indexOf('?') > -1?'&':'?') + Math.random():''),
function () {
Vvveb.FileManager.loadComponents();
});
},
}
// Toggle fullscreen
function launchFullScreen(document) {
if(document.documentElement.requestFullScreen) {
if (document.FullScreenElement)
document.exitFullScreen();
else
document.documentElement.requestFullScreen();
//mozilla
} else if(document.documentElement.mozRequestFullScreen) {
if (document.mozFullScreenElement)
document.mozCancelFullScreen();
else
document.documentElement.mozRequestFullScreen();
//webkit
} else if(document.documentElement.webkitRequestFullScreen) {
if (document.webkitFullscreenElement)
document.webkitExitFullscreen();
else
document.documentElement.webkitRequestFullScreen();
//ie
} else if(document.documentElement.msRequestFullscreen) {
if (document.msFullScreenElement)
document.msExitFullscreen();
else
document.documentElement.msRequestFullscreen();
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Typography from 'material-ui/Typography';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import Divider from 'material-ui/Divider';
import PaddedContent from '../../../../../common/paddedContent';
import SpreadContent from '../../../../../common/spreadContent';
import { sendReminder } from '../../../../../../reducers/cfeiReviewers';
const messages = {
assessments: 'Assessments',
reminder: 'Send reminder',
};
const SingleReviewer = (props) => {
const {
reviewer: {
user_name: username,
assessments: {
counts,
send_reminder: doSendReminder,
} = {},
} = {},
isFocalPoint,
cfeiCompleted,
notifyReviewer } = props;
return (
<div>
<PaddedContent>
<SpreadContent>
<Typography >{username}</Typography>
<Typography type="caption">{`${counts} ${messages.assessments}`}</Typography>
</SpreadContent>
</PaddedContent >
{!cfeiCompleted && isFocalPoint && doSendReminder && <Grid container justify="flex-end">
<Grid item>
<Button color="accent" onClick={notifyReviewer}>{messages.reminder}</Button>
</Grid>
</Grid>}
<Divider />
</div>
);
};
SingleReviewer.propTypes = {
reviewer: PropTypes.object,
isFocalPoint: PropTypes.bool,
cfeiCompleted: PropTypes.bool,
notifyReviewer: PropTypes.func,
};
const mapDispatchToProps = (dispatch, {
reviewer: {
user_id: reviewerId,
assessments: {
eoi_id: eoiId,
} = {},
} = {},
}) => ({
notifyReviewer: () => dispatch(sendReminder(eoiId, reviewerId)),
});
export default connect(null, mapDispatchToProps)(SingleReviewer);
|
import React, { useContext } from 'react';
import {
ViewPropTypes,
TouchableOpacity,
StyleSheet,
View,
Text,
Image,
} from 'react-native';
import PropTypes from 'prop-types';
import Color from 'color';
import { ThemeContext } from '../theme';
const CLOSE_IMG = require('../assets/images/cancel.png');
const propTypes = {
/**
* Title to be displayed in Alert
*/
title: PropTypes.string,
/**
* Message to be displayed in Alert
*/
message: PropTypes.string.isRequired,
/**
* The Alert visual variant
*/
variant: PropTypes.oneOf([
'primary',
'secondary',
'success',
'danger',
'warning',
'info',
'light',
'dark',
]),
/**
* Renders a properly aligned dismiss button, as well as
* adding extra horizontal padding to the Alert.
*/
dismissible: PropTypes.bool,
/**
* Callback fired when alert is closed.
*/
onClose: PropTypes.func,
/**
* Style for the container which host the text message
*/
containerStyle: ViewPropTypes.style,
/**
* Text style for title
*/
titleStyle: Text.propTypes.style,
/**
* Text style for message
*/
messageStyle: Text.propTypes.style,
};
const defaultProps = {
variant: 'primary',
containerStyle: {},
messageStyle: {},
titleStyle: {},
title: null,
dismissible: false,
onClose: () => {},
};
// Constants
const BACKGROUND_FACOTR = 0.8;
const BORDER_FACTOR = 0.72;
const TEXT_FACTOR = 0.48;
const WHITE_COLOR = Color('white');
const BLACK_COLOR = Color('black');
const Alert = ({
title,
message,
variant,
dismissible,
onClose,
containerStyle,
titleStyle,
messageStyle,
}) => {
const { theme } = useContext(ThemeContext);
const color = Color(theme.colors[variant] || theme.colors.primary);
const backgroundColor = color.mix(WHITE_COLOR, BACKGROUND_FACOTR);
const borderColor = color.mix(WHITE_COLOR, BORDER_FACTOR);
const textColor = color.mix(BLACK_COLOR, TEXT_FACTOR);
const combinedContainerStyle = [
styles.container(backgroundColor, borderColor, theme),
dismissible ? styles.row : null,
containerStyle,
];
const combinedTitleStyle = [styles.title(textColor, theme), titleStyle];
const combinedMessageStyle = [styles.message(textColor), messageStyle];
return (
<View accessible accessibilityRole="alert" style={combinedContainerStyle}>
<View style={dismissible ? styles.spread : null}>
{title && <Text style={combinedTitleStyle}>{title}</Text>}
<Text style={combinedMessageStyle}>{message}</Text>
</View>
{dismissible && (
<TouchableOpacity onPress={onClose}>
<Image source={CLOSE_IMG} style={styles.image(textColor, theme)} />
</TouchableOpacity>
)}
</View>
);
};
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
},
spread: {
flex: 1,
},
container: (backgroundColor, borderColor, theme) => ({
backgroundColor,
borderColor,
borderWidth: theme.dimensions.borderWidth,
borderRadius: theme.dimensions.borderRadius,
paddingHorizontal: theme.spacing.large,
paddingVertical: theme.spacing.medium,
}),
title: (color, theme) => ({
color,
fontWeight: 'bold',
marginBottom: theme.spacing.small,
}),
message: color => ({
color,
}),
image: (color, theme) => ({
width: theme.dimensions.alertIconSize,
height: theme.dimensions.alertIconSize,
tintColor: color,
}),
});
Alert.propTypes = propTypes;
Alert.defaultProps = defaultProps;
export default Alert;
|
const target = {
// id: 'target',
foo: 'bar',
baz: 'qux'
};
const handler = {
// get() {
// return 'handler override';
// }
// get(trapTarget, property, receiver) {
// // console.log(trapTarget === target);
// // console.log(property);
// // console.log(receiver === proxy);
// return trapTarget[property];
// }
// get() {
// return Reflect.get(...arguments);
// }
// get: Reflect.get
get(trapTarget, property, receiver) {
let decoration = '';
if (property === 'foo') {
decoration = '!!!';
}
return Reflect.get(...arguments) + decoration;
}
};
const proxy = new Proxy(target, handler);
// const proxy = new Proxy(target, Reflect);
console.log(proxy.foo);
console.log(target.foo);
console.log(proxy.baz);
console.log(target.baz);
// proxy.foo;
// // true
// // foo
// // true
// console.log(target.foo);
// console.log(proxy.foo);
// console.log(target['foo']);
// console.log(proxy['foo']);
// console.log(Object.create(target)['foo']);
// console.log(Object.create(proxy)['foo']);
// console.log(target.id); // target
// console.log(proxy.id); // target
// target.id = 'foo';
// console.log(target.id); // foo
// console.log(proxy.id); // foo
// proxy.id = 'bar';
// console.log(target.id); // bar
// console.log(proxy.id); // bar
// console.log(target.hasOwnProperty('id')); // true
// console.log(proxy.hasOwnProperty('id')); // true
// // console.log(target instanceof Proxy); // TypeError: Function has non-object prototype 'undefined' in instanceof check
// // console.log(proxy instanceof Proxy); // TypeError: Function has non-object prototype 'undefined' in instanceof check
// console.log(target === proxy); // false
|
if (require.main === module) {
const args = process.argv.slice(2)
const releaseChannel = args[0]
const vscodeVersion = args[1]
if (releaseChannel === 'latest') {
console.log(`::set-output name=tag_name::${vscodeVersion}`)
console.log(`::set-output name=asset_name::philodendron`)
} else {
console.log(`::set-output name=tag_name::insider/${vscodeVersion}`)
console.log(`::set-output name=asset_name::philodendron-insider`)
}
}
|
const { ChallengeStatus } = require('../models');
const { validationResult } = require('express-validator');
module.exports = {
store: async (req, res) => {
const transaction = await ChallengeStatus.sequelize.transaction();
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
await transaction.rollback();
return res.status(400).json({ errors: errors.array() });
}
let { description } = req.body;
const alreadyExistis = await ChallengeStatus.findOne({ where: { description } });
if (alreadyExistis) {
await transaction.rollback();
return res.status(422).json({ error: true, msg:'Já existe um status com essa descrição'});
}
description = description[0].toUpperCase() + description.slice(1, description.length).toLowerCase();
const result = await ChallengeStatus.create({ description });
await transaction.commit();
return res.status(200).json({ result });
} catch (error) {
await transaction.rollback();
console.log(error);
return res.status(422).json({ error: true, msg:'Ocorreu um erro'});
}
},
destroy: async (req, res) => {
const transaction = await ChallengeStatus.sequelize.transaction();
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
await transaction.rollback();
return res.status(400).json({ errors: errors.array() });
}
const { id } = req.params;
let statusExists = await ChallengeStatus.findByPk(id);
if (!statusExists) {
await transaction.rollback();
return res.status(422).json({ error: true, msg:'O status já foi excluido'});
}
let result = await ChallengeStatus.destroy({ where: { id } });
await transaction.commit();
return res.status(200).json({ result });
} catch (error) {
console.log(error);
await transaction.rollback();
return res.status(422).json({ error: true, msg:'Ocorreu um erro'});
}
},
index: async (req, res) => {
try {
const { limit = 7 } = req.query;
let result = await ChallengeStatus.findAll({ limit });
return res.status(200).json({ result });
} catch (error) {
console.log(error);
return res.status(422).json({ error: true, msg:error.message});
}
},
show: async (req, res) => {
try {
const { id } = req.params;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
let result = await ChallengeStatus.findByPk(id);
return res.status(200).json({ result });
} catch (error) {
console.log(error);
return res.status(422).json({ error: true, msg:error.message});
}
},
update: async (req, res) => {
const transaction = await ChallengeStatus.sequelize.transaction();
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
await transaction.rollback();
return res.status(400).json({ errors: errors.array() });
}
let { description } = req.body;
const { id } = req.params;
if (isNaN(id)) {
await transaction.rollback();
return res.status(422).json({ error: true, msg:'Informe um id para o status'});
}
description = description[0].toUpperCase() + description.slice(1, description.length).toLowerCase();
let statusExists = await ChallengeStatus.findByPk(id);
if (!statusExists) {
await transaction.rollback();
return res.status(422).json({ error: true, msg:'O status não existe'});
}
let result = await ChallengeStatus.update({ description }, { where: { id } });
await transaction.commit();
return res.status(200).json({ result });
} catch (error) {
console.log(error);
transaction.rollback();
return res.status(422).json({ error: true, msg:error.message});
}
}
};
|
const minutes = 9;
const the_interval = 0.3 * 60 * 1000;
// Move the mouse across the screen as a sine wave.
const robot = require('robotjs');
const txtgen = require('txtgen');
// Speed up the mouse.
robot.setMouseDelay(2);
const twoPI = Math.PI * 2.0;
const screenSize = robot.getScreenSize();
const height = screenSize.height / 2 - 10;
const { width } = screenSize;
const myArray = [txtgen.paragraph(), txtgen.sentence(), txtgen.article()];
const article = myArray[Math.floor(Math.random() * myArray.length)];
setInterval(function() {
for (let x = 0; x < width; x++) {
y = height * Math.sin((twoPI * x) / width) + height;
robot.moveMouse(x, y);
}
// Type "Hello World".
robot.typeString(article);
// Press enter.
robot.keyTap('enter');
// do your stuff here
}, the_interval);
|
/*global describe, beforeEach, it */
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('yotest generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('yotest:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
'someOption': true
});
this.app.options['skip-install'] = true;
this.app.run({}, function () {
helpers.assertFile(expected);
done();
});
});
});
|
angular.module('MyApp', ['ngResource', 'ngMessages', 'ngAnimate', 'toastr', 'ui.router', 'satellizer'])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$stateProvider
.state('home', {
url: '/',
controller: 'HomeCtrl',
templateUrl: 'partials/home.html'
})
.state('login', {
url: '/login',
templateUrl: 'partials/login.html',
controller: 'LoginCtrl',
resolve: {
skipIfLoggedIn: skipIfLoggedIn
}
})
.state('signup', {
url: '/signup',
templateUrl: 'partials/signup.html',
controller: 'SignupCtrl',
resolve: {
skipIfLoggedIn: skipIfLoggedIn
}
})
.state('logout', {
url: '/logout',
template: null,
controller: 'LogoutCtrl'
})
.state('profile', {
url: '/profile',
templateUrl: 'partials/profile.html',
controller: 'ProfileCtrl',
resolve: {
loginRequired: loginRequired
}
});
$urlRouterProvider.otherwise('/');
$authProvider.facebook({
clientId: '657854390977827'
});
$authProvider.google({
clientId: '368579289805-r7q5crfule9j867b24rq0u41sel14lmu.apps.googleusercontent.com'
});
$authProvider.github({
clientId: '0ba2600b1dbdb756688b'
});
$authProvider.linkedin({
clientId: '77cw786yignpzj'
});
$authProvider.instagram({
clientId: '799d1f8ea0e44ac8b70e7f18fcacedd1'
});
$authProvider.yahoo({
clientId: 'dj0yJmk9SDVkM2RhNWJSc2ZBJmQ9WVdrOWIzVlFRMWxzTXpZbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD0yYw--'
});
$authProvider.twitter({
url: '/auth/twitter'
});
$authProvider.live({
clientId: '000000004C12E68D'
});
$authProvider.twitch({
clientId: 'qhc3lft06xipnmndydcr3wau939a20z'
});
$authProvider.bitbucket({
clientId: '48UepjQDYaZFuMWaDj'
});
$authProvider.oauth2({
name: 'foursquare',
url: '/auth/foursquare',
clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',
redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'
});
function skipIfLoggedIn($q, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.reject();
} else {
deferred.resolve();
}
return deferred.promise;
}
function loginRequired($q, $location, $auth) {
var deferred = $q.defer();
if ($auth.isAuthenticated()) {
deferred.resolve();
} else {
$location.path('/login');
}
return deferred.promise;
}
});
|
import React from 'react';
import PropTypes from "prop-types";
import get from 'lodash/get';
import Highlight from 'react-highlight.js';
import Scrollbars from "react-custom-scrollbars";
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Table from '@material-ui/core/Table';
import TableRow from '@material-ui/core/TableRow';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import Paper from '@material-ui/core/Paper';
import ArrowForward from '@material-ui/icons/ArrowForward';
import withStyles from '@material-ui/core/styles/withStyles';
import * as Enum from '../../../enum';
import {getTaskId} from "../../../getters";
import connect from './Task.connect';
import styles from './Task.styles';
import BigImageModal from "../../BigImageModal";
class Task extends React.PureComponent{
constructor(props) {
super();
this.state = {
answer: props.solution,
openBigImage: false
}
}
openBigImageClickHandler = () => {
this.setState({openBigImage: true});
}
closeBigImageClickHandler = () => {
this.setState({openBigImage: false});
}
answerChangeHandler = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
} else {
this.setState({answer: get(event, 'target.value')});
}
};
clearAnswerField = () => {
this.setState({answer: ''});
};
answerButtonClickHandler = () => {
this.props.actions.completeTask(this.state.answer);
};
goToNextTaskClickHandler = () => {
const {nextRoute} = this.props;
this.props.actions.setCurrentRouteId(nextRoute.id);
this.props.actions.getCourseTask(getTaskId(nextRoute));
};
renderAnswerField = () => {
const {classes} = this.props;
const {answer} = this.state;
const splittedAnswer = answer.split(' ');
const firstWordError = splittedAnswer[0].toLocaleLowerCase() !== 'select'
&& splittedAnswer[0].toLocaleLowerCase() !== 'update'
&& splittedAnswer[0].toLocaleLowerCase() !== 'insert'
&& splittedAnswer[0].toLocaleLowerCase() !== 'delete';
return (
<Box display={'block'} className={classes.answerFieldContainer}>
<TextField label={'Запрос'}
multiline
rowsMax={10}
rows={7}
variant={'outlined'}
fullWidth
maxwidth={500}
onChange={this.answerChangeHandler}
onKeyPress={this.answerChangeHandler}
value={answer}
// className={classes.textField}
/>
{/*<Highlight language="sql" className={classes.hightlight}>*/}
{/* {answer}*/}
{/*</Highlight>*/}
<Box display={'flex'}
justifyContent={'flex-end'}
className={classes.buttonsContainer}
>
<Button onClick={this.clearAnswerField}> Очистить </Button>
<Button color={'primary'}
variant={'outlined'}
className={classes.button}
disabled={answer.length === 0 || firstWordError}
onClick={this.answerButtonClickHandler}
>
Выполнить
</Button>
</Box>
</Box>
);
};
renderErrorTables = () => {
const {classes, tableErrorData} = this.props;
const refResult = get(tableErrorData, [Enum.ERROR_REF_RESULT, 1, 1], []);
const studentResult = get(tableErrorData, [Enum.ERROR_STUDENT_RESULT, 1, 1], []);
return (
<div>
<Typography className={classes.title}> Ошибка! </Typography>
<div className={classes.tableBody}>
<div className={classes.table}>
<Typography className={classes.tableTitle}> Правильный запрос </Typography>
<TableContainer>
<Table>
{refResult.map((row, index) =>
<TableRow key={`right-answer-row-${index}`}>
{row.map((cell, index) =>
<TableCell key={`right-answer-cell-${index}`} className={classes.tableCell}>
{cell}
</TableCell>
)}
</TableRow>
)}
</Table>
</TableContainer>
</div>
<div className={classes.table}>
<Typography className={classes.tableTitle}> Ваш запрос </Typography>
<TableContainer>
<Table>
{studentResult.map((row, index) =>
<TableRow key={`wrong-answer-row-${index}`}>
{row.map((cell, index) =>
<TableCell key={`wrong-answer-cell-${index}`} className={classes.tableCell}>
{cell}
</TableCell>
)}
</TableRow>
)}
</Table>
</TableContainer>
</div>
</div>
</div>
);
}
renderAnswerTable = () => {
const {classes, answer} = this.props;
return (
<Box className={classes.tableWrap}>
<Typography> Правильно! </Typography>
<div className={classes.tableBody}>
<div className={classes.table}>
<Typography className={classes.tableTitle}> Результат выполнения запроса</Typography>
<TableContainer component={Paper}>
<Table>
{answer.map(row =>
<TableRow>
{row.map(cell =>
<TableCell>
{cell}
</TableCell>
)}
</TableRow>
)}
</Table>
</TableContainer>
</div>
</div>
</Box>
);
}
changeTabToMethodical = (subMaterialId) => () => {
this.props.actions.setCurrentCourseTab(1);
this.props.actions.getCourseMethodicalMaterial(subMaterialId);
this.props.actions.getCourseMethodicalMaterials();
}
themes = () => {
const {classes, themes} = this.props;
return (
<div className={classes.themesContainer}>
<Typography className={classes.title}> Темы для изучения </Typography>
{themes.map(item => <div key={item.theme.id}>
<Typography className={classes.materialItem}>{item.theme.title}</Typography>
{item.theme.topic_in_themes.map(topic =>
<div key={`topic-${topic.id}`}
className={classes.materialSubItem}
onClick={this.changeTabToMethodical(topic.id)}>
<Typography>{topic.topic_name}</Typography>
</div>
)}
</div>
)}
</div>
)
}
databaseStructure = () => {
const {classes, task} = this.props;
const taskDescription = get(task, `database_description`, '');
const taskImage = get(task, `database_image`, '');
return (
<>
<Typography className={classes.title}> Описание базы данных </Typography>
<Typography dangerouslySetInnerHTML={{__html: taskDescription}} />
<div className={classes.image} onClick={this.openBigImageClickHandler}> <img src={taskImage} alt=""/> </div>
</>
)
}
getCurrentTaskErrors = () => {
const {courseId, task, errors} = this.props;
return errors[courseId]?.[task.id] || []
}
render() {
const {task, classes, error, tableErrorData, answer, nextRoute, isDone} = this.props;
const taskText = get(task, `task_text`, null);
const taskTitle = get(task, `title`, '');
const refResult = get(tableErrorData, [Enum.ERROR_REF_RESULT, 1, 1], []);
const studentResult = get(tableErrorData, [Enum.ERROR_STUDENT_RESULT, 1, 1], []);
const taskImage = get(task, `database_image`, '');
const errors = this.getCurrentTaskErrors().reverse();
const {openBigImage} = this.state;
if (!taskText) return <></>;
return (
<div className={classes.taskRoot}>
<div className={classes.leftSide}>
<Scrollbars minheight={300}>
<div style={{marginRight: '10px'}}>
<div>
<Typography className={classes.title}> {taskTitle}: </Typography>
<Typography> {taskText} </Typography>
<div className={classes.answerFieldBlock}>
{this.renderAnswerField()}
</div>
</div>
<div className={classes.taskAnswerInfoBlock}>
{error &&
<Paper className={classes.simpleErrorBlock}>
<Typography className={classes.simpleErrorText}> {error} </Typography>
</Paper>
}
{refResult.length > 0 && studentResult.length > 0 && this.renderErrorTables()}
{answer.length > 0 && this.renderAnswerTable()}
</div>
<div className={classes.errorsList}>
<Typography className={classes.historyTitle}><b>История выполнения</b></Typography>
{errors.map((item, index) =>
<div className={classes.errorBlock}>
<Typography className={classes.errorTitle}>
Ошибка
</Typography>
<Typography> {item.message} </Typography>
{index !== 0 ? <Typography> {item.answer} </Typography> : <></>}
</div>
)}
</div>
</div>
</Scrollbars>
</div>
<div className={classes.taskInfo}>
{nextRoute.id &&
<Button color={'primary'}
className={classes.nextTaskButton}
onClick={this.goToNextTaskClickHandler}
endIcon={<ArrowForward/>}
>
{isDone ? 'Следующее задание' : 'Пропустить задание'}
</Button>
}
<Scrollbars minheight={300}>
<div className={classes.taskInfoContent}>
{this.themes()}
{this.databaseStructure()}
</div>
</Scrollbars>
</div>
<BigImageModal isOpen={openBigImage}
closeImage={this.closeBigImageClickHandler}
taskImage={taskImage}
/>
</div>
)
}
}
Task.propTypes = {
changeTabToMethodical: PropTypes.func,
error: PropTypes.any,
isDone: PropTypes.bool,
task: PropTypes.object,
actions: PropTypes.object,
tableErrorData: PropTypes.object,
currentTask: PropTypes.string,
nextRoute: PropTypes.object,
};
export default withStyles(styles)(connect(Task));
|
$(function() {
consoleInit();
start(main);
});
const DBALL_CHEF_ABI = [{"inputs":[{"internalType":"contract DBallToken","name":"_dball","type":"address"},{"internalType":"address","name":"_devaddr","type":"address"},{"internalType":"address","name":"_feeAddress","type":"address"},{"internalType":"uint256","name":"_dballPerBlock","type":"uint256"},{"internalType":"uint256","name":"_startBlock","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"uint256","name":"pid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"uint256","name":"pid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"EmergencyWithdraw","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"uint256","name":"pid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdraw","type":"event"},{"inputs":[],"name":"BONUS_MULTIPLIER","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_allocPoint","type":"uint256"},{"internalType":"contract IBEP20","name":"_lpToken","type":"address"},{"internalType":"uint16","name":"_depositFeeBP","type":"uint16"},{"internalType":"uint16","name":"_unstakingFeeBP","type":"uint16"},{"internalType":"bool","name":"_withUpdate","type":"bool"}],"name":"add","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"dball","outputs":[{"internalType":"contract DBallToken","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dballPerBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_pid","type":"uint256"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_devaddr","type":"address"}],"name":"dev","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"devaddr","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_pid","type":"uint256"}],"name":"emergencyWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_from","type":"uint256"},{"internalType":"uint256","name":"_to","type":"uint256"}],"name":"getMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"massUpdatePools","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_pid","type":"uint256"},{"internalType":"address","name":"_user","type":"address"}],"name":"pendingEgg","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"poolInfo","outputs":[{"internalType":"contract IBEP20","name":"lpToken","type":"address"},{"internalType":"uint256","name":"allocPoint","type":"uint256"},{"internalType":"uint256","name":"lastRewardBlock","type":"uint256"},{"internalType":"uint256","name":"accEggPerShare","type":"uint256"},{"internalType":"uint16","name":"depositFeeBP","type":"uint16"},{"internalType":"uint16","name":"unstakingFeeBP","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"poolLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_pid","type":"uint256"},{"internalType":"uint256","name":"_allocPoint","type":"uint256"},{"internalType":"uint16","name":"_depositFeeBP","type":"uint16"},{"internalType":"uint16","name":"_unstakingFeeBP","type":"uint16"},{"internalType":"bool","name":"_withUpdate","type":"bool"}],"name":"set","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_feeAddress","type":"address"}],"name":"setFeeAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"startBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAllocPoint","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_dballPerBlock","type":"uint256"}],"name":"updateEmissionRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_pid","type":"uint256"}],"name":"updatePool","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"address","name":"","type":"address"}],"name":"userInfo","outputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"uint256","name":"rewardDebt","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"_pid","type":"uint256"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]
async function main() {
const App = await init_ethers();
_print(`Initialized ${App.YOUR_ADDRESS}\n`);
_print("Reading smart contracts...\n");
const DBALL_CHEF_ADDR = "0x8cf7044DDedbE502892B120aAf8692FeCFb71420";
const rewardTokenTicker = "DBALL";
const DBALL_CHEF = new ethers.Contract(DBALL_CHEF_ADDR, DBALL_CHEF_ABI, App.provider);
const rewardsPerWeek = await DBALL_CHEF.dballPerBlock() /1e18
* 604800 / 3;
const tokens = {};
const prices = await getBscPrices();
await loadBscChefContract(App, tokens, prices, DBALL_CHEF, DBALL_CHEF_ADDR, DBALL_CHEF_ABI, rewardTokenTicker,
"dball", null, rewardsPerWeek, "pendingEgg");
hideLoading();
}
|
/*****************************************************************************
* Open MCT, Copyright (c) 2014-2017, United States Government
* as represented by the Administrator of the National Aeronautics and Space
* Administration. All rights reserved.
*
* Open MCT is licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* Open MCT includes source code licensed under additional open source
* licenses. See the Open Source Licenses file (LICENSES.md) included with
* this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information.
*****************************************************************************/
define(
["../../src/directives/MCTResize"],
function (MCTResize) {
describe("The mct-resize directive", function () {
var mockTimeout,
mockScope,
testElement,
testAttrs,
mctResize;
beforeEach(function () {
mockTimeout = jasmine.createSpy("$timeout");
mockScope = jasmine.createSpyObj("$scope", ["$eval", "$on", "$apply"]);
testElement = { offsetWidth: 100, offsetHeight: 200 };
testAttrs = { mctResize: "some-expr" };
mctResize = new MCTResize(mockTimeout);
});
it("is applicable as an attribute only", function () {
expect(mctResize.restrict).toEqual("A");
});
it("starts tracking size changes upon link", function () {
expect(mockTimeout).not.toHaveBeenCalled();
mctResize.link(mockScope, [testElement], testAttrs);
expect(mockTimeout).toHaveBeenCalledWith(
jasmine.any(Function),
jasmine.any(Number),
false
);
expect(mockScope.$eval).toHaveBeenCalledWith(
testAttrs.mctResize,
{ bounds: { width: 100, height: 200 } }
);
});
it("reports size changes on a timeout", function () {
mctResize.link(mockScope, [testElement], testAttrs);
// Change the element's apparent size
testElement.offsetWidth = 300;
testElement.offsetHeight = 350;
// Shouldn't know about this yet...
expect(mockScope.$eval).not.toHaveBeenCalledWith(
testAttrs.mctResize,
{ bounds: { width: 300, height: 350 } }
);
// Fire the timeout
mockTimeout.mostRecentCall.args[0]();
// Should have triggered an evaluation of mctResize
// with the new width & height
expect(mockScope.$eval).toHaveBeenCalledWith(
testAttrs.mctResize,
{ bounds: { width: 300, height: 350 } }
);
});
it("stops size checking for size changes after destroy", function () {
mctResize.link(mockScope, [testElement], testAttrs);
// First, make sure there's a $destroy observer
expect(mockScope.$on)
.toHaveBeenCalledWith("$destroy", jasmine.any(Function));
// Should have scheduled the first timeout
expect(mockTimeout.calls.length).toEqual(1);
// Fire the timeout
mockTimeout.mostRecentCall.args[0]();
// Should have scheduled another timeout
expect(mockTimeout.calls.length).toEqual(2);
// Broadcast a destroy event
mockScope.$on.mostRecentCall.args[1]();
// Fire the timeout
mockTimeout.mostRecentCall.args[0]();
// Should NOT have scheduled another timeout
expect(mockTimeout.calls.length).toEqual(2);
});
it("triggers a digest cycle when size changes", function () {
var applyCount;
mctResize.link(mockScope, [testElement], testAttrs);
applyCount = mockScope.$apply.calls.length;
// Change the element's apparent size
testElement.offsetWidth = 300;
testElement.offsetHeight = 350;
// Fire the timeout
mockTimeout.mostRecentCall.args[0]();
// No more apply calls
expect(mockScope.$apply.calls.length)
.toBeGreaterThan(applyCount);
});
it("does not trigger a digest cycle when size does not change", function () {
var applyCount;
mctResize.link(mockScope, [testElement], testAttrs);
applyCount = mockScope.$apply.calls.length;
// Fire the timeout
mockTimeout.mostRecentCall.args[0]();
// No more apply calls
expect(mockScope.$apply.calls.length).toEqual(applyCount);
});
});
}
);
|
define({
tocChooseTemplate: 'Atlasīt lapas veidni',
newPage: 'Jauna lapa',
pages_upper: 'Lapas',
content_upper: 'Saturs',
body_upper: 'Pamatteksts',
tocLoading: 'Ielādē',
addPage: 'Pievienot lapu',
addLink: 'Pievienot saiti',
addFolder: 'Pievienot mapi',
addDialog: 'Pievienot logu',
makeHome: 'Izveidot sākumlapu',
makeSplash: 'Iestatīt kā uzplaiksnījuma ekrānu',
opendWithPages: 'Atvērts ar {pages}.',
hideFromMenu: 'Paslēpt no izvēlnes',
showFromMenu: 'Rādīt izvēlnē',
body: 'Pamatteksts',
header: 'Galvene',
footer: 'Kājene',
outline: 'Kontūra',
tocSetLink: 'Iestatīšanas saite',
certainly: 'Labi',
removePageTip: '{label} ir iekļautas {subCount} lapas; vai tiešām vēlaties tās noņemt?',
fullScreenApp: 'Pilnekrāna lietotne',
fullScreenAppTip: 'Vislabākā iespēja izveidot tīmekļa lietotni, kas aizņem visu pārlūka logu.',
scrollingPage: 'Lapu ritināšana',
scrollingPageTip: 'Vislabākā iespēja izveidot tīmekļa lapu, ko var ritināt pārlūka logā.',
arrange: 'Sakārtot',
align: 'Līdzināt',
});
|
const constants = {
TILESIZE: 8,
}
export default constants
|
module.exports=require('../../decode-ranges.js')('wlYHh7BAAhSABAghCBAj8BvkAIADADADALALAAAZAIADADADALAxshA4NA_AAAJMAEAAABABAI4NYOGhVF')
|
dojo.provide("sketchSpaceDesigner.designer.modes.Select");
dojo.require("sketchSpaceDesigner.designer.modes.Edit");
dojo.require("dijit.form.Button");
dojo.declare("sketchSpaceDesigner.designer.modes.Select", [sketchSpaceDesigner.designer.modes.Edit], {
isOutlineMouseDown: false,
isMoving: false,
minMarqueeSize: 10,
cursorBboxOutlineDefinitions: {select: [{color:{r:128,g:0,b:128,a:1}, width:1, style:"solid"}, {color:{r:196,g:0,b:196,a:1}, width:1, style:"solid"}]},
enable: function () {
var designer = this;
this.inherited(arguments);
this.enableOutline();
this.selectionUpdatedHandle = dojo.connect(this.designer.selection, "selectionUpdated", this, this.updateOutline);
this.viewUpdatedHandle = dojo.connect(this.designer, "viewUpdated", this, this.updateOutline);
// this.applyOption = new dijit.layout._LayoutWidget({title:"Apply options [ENTER]:"});
// this.applyOption.addChild(new dijit.form.Button({label:"Apply", onClick: function () { designer.applyOptionsToSelection(); }}));
// this.designer.ui.options.addChild(this.applyOption);
this.deleteOption = new dijit.layout._LayoutWidget({title:"Delete [DELETE]:"});
this.deleteOption.addChild(new dijit.form.Button({label:"Delete", onClick: function () { designer.deleteSelection(); }}));
this.designer.ui.options.addChild(this.deleteOption);
this.designer.ui.options.layout();
$(this.designer.container).css({'cursor': 'url(/static/html/plugins/sketchSpace/imgeditbar_select_icon.png),default'});
},
disable: function () {
dojo.disconnect(this.viewUpdatedHandle);
dojo.disconnect(this.selectionUpdatedHandle);
this.disableOutline();
this.inherited(arguments);
// this.applyOption.destroyRecursive();
this.deleteOption.destroyRecursive();
this.designer.ui.options.layout();
$(this.designer.container).css({'cursor': 'default'});
},
enableOutline: function() {
var bbox = this.designer.selection.getBbox();
if (bbox.x !== undefined) {
this.outline = this.designer.surface.createGroup();
this.outline.setTransform(dojox.gfx.matrix.translate(bbox.x, bbox.y));
this.outline.originalMatrix = this.outline.matrix;
this.outline.outlineRect = dojox.gfx.utils.deserialize(this.outline, {shape:{type:"rect", x:0, y:0, width:bbox.width, height:bbox.height}, stroke:{color:{r:196,g:196,b:196,a:1},width:1, style:"solid"}});
this.outline.outlineCornerTL = dojox.gfx.utils.deserialize(this.outline, {shape:{type:"rect", x:-2, y:-2, width:4, height:4}, stroke:{color:{r:128,g:128,b:128,a:1},width:1}, fill:{r:196,g:196,b:196,a:1}});
this.outline.outlineCornerBL = dojox.gfx.utils.deserialize(this.outline, {shape:{type:"rect", x:-2, y:bbox.height-2, width:4, height:4}, stroke:{color:{r:128,g:128,b:128,a:1},width:1}, fill:{r:196,g:196,b:196,a:1}});
this.outline.outlineCornerTH = dojox.gfx.utils.deserialize(this.outline, {shape:{type:"rect", x:bbox.width-2, y:-2, width:4, height:4}, stroke:{color:{r:128,g:128,b:128,a:1},width:1}, fill:{r:196,g:196,b:196,a:1}});
this.outline.outlineCornerBH = dojox.gfx.utils.deserialize(this.outline, {shape:{type:"rect", x:bbox.width-2, y:bbox.height-2, width:4, height:4}, stroke:{color:{r:128,g:128,b:128,a:1},width:1}, fill:{r:196,g:196,b:196,a:1}});
}
},
disableOutline: function () {
if (this.outline !== undefined) {
this.outline.removeShape();
this.outline = undefined;
}
},
updateOutline: function () {
this.disableOutline();
this.enableOutline();
},
onSetOptions: function () {
this.applyOptionsToSelection();
},
applyOptionsToSelection: function () {
this.designer.selection.applyToShapes(function (designer) {
designer.setShapeFillAndStroke(this, designer.options);
}, this.designer);
this.designer.selection.applyToShapes("save");
},
deleteSelection: function () {
this.designer.selection.applyToShapes("removeShape");
},
onShapeMouseDown: function (shape, event) {
this.downShape = shape;
this.onMouseDown(event);
},
onKeyUp: function (event) {
this.inherited(arguments);
if (event.keyCode == dojo.keys.ENTER) {
this.applyOptionsToSelection();
} else if (event.keyCode == dojo.keys.DELETE) {
this.deleteSelection();
} else if (event.keyCode == dojo.keys.HOME) {
this.designer.selection.applyToShapes(
function(){
this.zOrderMoved = true; this.moveToFront();
// console.log('Move ' + this.objId + ' to front');
}
);
this.designer.selection.applyToShapes("save");
} else if (event.keyCode == dojo.keys.END) {
this.designer.selection.applyToShapes(
function(){
this.zOrderMoved = true; this.moveToBack();
// console.log('Move ' + this.objId + ' to back');
}
);
this.designer.selection.applyToShapes("save");
} else if (event.keyCode == dojo.keys.PAGE_DOWN) {
var move = {};
this.designer.selection.applyToShapes(
function(){
this.zOrderMoved = true;
move[this.objId]=true;
}
);
var shapes={};
this.designer.forEachObjectShape(function(shape){shapes[shape.objId]=shape;});
var img = this.designer.images[this.designer.currentImage];
var myOrder = img.order.slice(0);
for(var i=0; i<myOrder.length; i++){
if(myOrder[i] in move){
if(i == 0) {
continue;
}
var tmp=myOrder[i-1];
if(myOrder[i-1] in move) {
continue;
}
myOrder[i-1] = myOrder[i];
myOrder[i]=tmp;
}
}
for(var i=0; i<myOrder.length; i++){
if(shapes[myOrder[i]]){
shapes[myOrder[i]].moveToFront();
}
}
this.designer.selection.applyToShapes("save");
} else if (event.keyCode == dojo.keys.PAGE_UP) {
var move = {};
this.designer.selection.applyToShapes(
function(){
this.zOrderMoved = true;
move[this.objId]=true;
}
);
var shapes={};
this.designer.forEachObjectShape(function(shape){shapes[shape.objId]=shape;});
var img = this.designer.images[this.designer.currentImage];
var myOrder = img.order.slice(0);
for(var i=myOrder.length-1; i>=0; i--){
if(myOrder[i] in move){
if(i == (myOrder-length-1)) {
continue;
}
var tmp=myOrder[i+1];
if(myOrder[i+1] in move) {
continue;
}
myOrder[i+1] = myOrder[i];
myOrder[i]=tmp;
}
}
for(var i=0; i<myOrder.length; i++){
if(shapes[myOrder[i]]){
shapes[myOrder[i]].moveToFront();
}
}
this.designer.selection.applyToShapes("save");
}
},
onMouseDown: function (event) {
this.inherited(arguments);
// if (!this.isOutlineMouseDown && !this.isMoving) {
if (event.button == dojo.mouseButtons.LEFT) {
this.orig = this.mouse = this.getCurrentGlobalMouse(event);
if (!event.ctrlKey && this.designer.selection.getBbox().containsPoint(this.mouse)) {
this.isOutlineMouseDown = true;
this.designer.selection.orig = this.getCurrentMouse(event, this.designer.selection.parent);
if (!this.outline) return;
this.outline.originalMatrix = this.outline.matrix;
this.designer.selection.applyToShapes(function () {
this.originalMatrix = this.matrix;
});
} else {
this.addCursorBboxOutline("select");
}
}
// }
},
onMouseUp: function(event) {
this.inherited(arguments);
var bbox = this.getCurrentCursorBbox();
if (this.isMoving) {
this.designer.selection.applyToShapes("save");
} else if (this.isOutlineMouseDown) {
// if (event.ctrlKey & this.downShape !== undefined)
// this.designer.selection.toggleShape(this.downShape, !event.ctrlKey);
} else {
if (event.button == dojo.mouseButtons.LEFT) {
if (bbox.width < this.minMarqueeSize && bbox.height < this.minMarqueeSize && this.downShape !== undefined) {
this.designer.selection.toggleShape(this.downShape, !event.ctrlKey);
} else {
if (event.ctrlKey) {
this.designer.selection.toggleShapesByBbox(bbox);
} else {
this.designer.selection.clear();
this.designer.selection.addShapesByBbox(bbox);
}
}
}
}
this.removeCursorBboxOutline("zoom");
this.isOutlineMouseDown = false;
this.isMoving = false;
this.downShape = undefined;
},
onMouseMove: function(event) {
this.inherited(arguments);
if (this.isOutlineMouseDown && this.outline) {
this.isMoving = true;
var move = this.getCurrentMove(event);
this.outline.setTransform(dojox.gfx.matrix.multiply(this.outline.originalMatrix, move));
move = this.getCurrentMove(event, this.designer.selection.parent, this.designer.selection.orig);
this.designer.selection.applyToShapes(function () {
this.setTransform(dojox.gfx.matrix.multiply(this.originalMatrix, move));
});
}
},
getContainerShape: function () { return this.designer.surface; }
});
|
'use strict';
// ---------------------------------------------------------------------------
const hitbtc = require ('./hitbtc');
const { PermissionDenied, ExchangeError, ExchangeNotAvailable, OrderNotFound, InsufficientFunds, InvalidOrder } = require ('./base/errors');
const { TRUNCATE, DECIMAL_PLACES } = require ('./base/functions/number');
// ---------------------------------------------------------------------------
module.exports = class hitbtc2 extends hitbtc {
describe () {
return this.deepExtend (super.describe (), {
'id': 'hitbtc2',
'name': 'HitBTC',
'countries': [ 'HK' ],
'rateLimit': 1500,
'version': '2',
'has': {
'createDepositAddress': true,
'fetchDepositAddress': true,
'CORS': true,
'editOrder': true,
'fetchCurrencies': true,
'fetchOHLCV': true,
'fetchTickers': true,
'fetchOrder': true,
'fetchOrders': false,
'fetchOpenOrders': true,
'fetchClosedOrders': true,
'fetchMyTrades': true,
'withdraw': true,
'fetchOrderTrades': false, // not implemented yet
'fetchDeposits': false,
'fetchWithdrawals': false,
'fetchTransactions': true,
},
'timeframes': {
'1m': 'M1',
'3m': 'M3',
'5m': 'M5',
'15m': 'M15',
'30m': 'M30', // default
'1h': 'H1',
'4h': 'H4',
'1d': 'D1',
'1w': 'D7',
'1M': '1M',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766555-8eaec20e-5edc-11e7-9c5b-6dc69fc42f5e.jpg',
'api': 'https://api.hitbtc.com',
'www': 'https://hitbtc.com',
'referral': 'https://hitbtc.com/?ref_id=5a5d39a65d466',
'doc': [
'https://api.hitbtc.com',
'https://github.com/hitbtc-com/hitbtc-api/blob/master/APIv2.md',
],
'fees': [
'https://hitbtc.com/fees-and-limits',
'https://support.hitbtc.com/hc/en-us/articles/115005148605-Fees-and-limits',
],
},
'api': {
'public': {
'get': [
'symbol', // Available Currency Symbols
'symbol/{symbol}', // Get symbol info
'currency', // Available Currencies
'currency/{currency}', // Get currency info
'ticker', // Ticker list for all symbols
'ticker/{symbol}', // Ticker for symbol
'trades/{symbol}', // Trades
'orderbook/{symbol}', // Orderbook
'candles/{symbol}', // Candles
],
},
'private': {
'get': [
'order', // List your current open orders
'order/{clientOrderId}', // Get a single order by clientOrderId
'trading/balance', // Get trading balance
'trading/fee/{symbol}', // Get trading fee rate
'history/trades', // Get historical trades
'history/order', // Get historical orders
'history/order/{id}/trades', // Get historical trades by specified order
'account/balance', // Get main acccount balance
'account/transactions', // Get account transactions
'account/transactions/{id}', // Get account transaction by id
'account/crypto/address/{currency}', // Get deposit crypro address
],
'post': [
'order', // Create new order
'account/crypto/withdraw', // Withdraw crypro
'account/crypto/address/{currency}', // Create new deposit crypro address
'account/transfer', // Transfer amount to trading
],
'put': [
'order/{clientOrderId}', // Create new order
'account/crypto/withdraw/{id}', // Commit withdraw crypro
],
'delete': [
'order', // Cancel all open orders
'order/{clientOrderId}', // Cancel order
'account/crypto/withdraw/{id}', // Rollback withdraw crypro
],
'patch': [
'order/{clientOrderId}', // Cancel Replace order
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'maker': -0.01 / 100,
'taker': 0.1 / 100,
},
'funding': {
'tierBased': false,
'percentage': false,
'withdraw': {
'BTC': 0.001,
'BCC': 0.0018,
'ETH': 0.00958,
'BCH': 0.0018,
'USDT': 100,
'DASH': 0.03,
'BTG': 0.0005,
'XRP': 0.509,
'LTC': 0.003,
'ZEC': 0.0001,
'XMR': 0.09,
'1ST': 0.84,
'ADX': 5.7,
'AE': 6.7,
'AEON': 0.01006,
'AIR': 565,
'AMM': 14,
'AMP': 342,
'ANT': 6.7,
'ARDR': 1,
'ARN': 18.5,
'ART': 26,
'ATB': 0.0004,
'ATL': 27,
'ATM': 504,
'ATS': 860,
'AVT': 1.9,
'BAS': 113,
'BCN': 0.1,
'BET': 124,
'BKB': 46,
'BMC': 32,
'BMT': 100,
'BNT': 2.57,
'BQX': 4.7,
'BTCA': 351.21,
'BTM': 40,
'BTX': 0.04,
'BUS': 0.004,
'CAPP': 97,
'CCT': 6,
'CDT': 100,
'CDX': 30,
'CFI': 61,
'CL': 13.85,
'CLD': 0.88,
'CND': 574,
'CNX': 0.04,
'COSS': 65,
'CPAY': 5.487,
'CSNO': 16,
'CTR': 15,
'CTX': 146,
'CVC': 8.46,
'DATA': 12.949,
'DBIX': 0.0168,
'DCN': 1280,
'DCT': 0.02,
'DDF': 342,
'DENT': 1000,
'DGB': 0.4,
'DGD': 0.01,
'DICE': 0.32,
'DLT': 0.26,
'DNT': 0.21,
'DOGE': 2,
'DOV': 34,
'DRPU': 24,
'DRT': 240,
'DSH': 0.017,
'EBET': 84,
'EBTC': 20,
'EBTCOLD': 6.6,
'ECAT': 14,
'EDG': 2,
'EDO': 2.9,
'EKO': 1136.36,
'ELE': 0.00172,
'ELM': 0.004,
'EMC': 0.03,
'MGO': 14,
'ENJ': 163,
'EOS': 1.5,
'ERO': 34,
'ETBS': 15,
'ETC': 0.002,
'ETP': 0.004,
'EVX': 5.4,
'EXN': 456,
'FCN': 0.000005,
'FRD': 65,
'FUEL': 123.00105,
'FUN': 202.9598309,
'FYN': 1.849,
'FYP': 66.13,
'GAME': 0.004,
'GNO': 0.0034,
'GUP': 4,
'GVT': 1.2,
'HSR': 0.04,
'HAC': 144,
'HDG': 7,
'HGT': 1082,
'HPC': 0.4,
'HVN': 120,
'ICN': 0.55,
'ICO': 34,
'ICOS': 0.35,
'IND': 76,
'INDI': 790,
'ITS': 15.0012,
'IXT': 11,
'KBR': 143,
'KICK': 112,
'KMD': 4,
'LA': 41,
'LEND': 388,
'LAT': 1.44,
'LIFE': 13000,
'LRC': 27,
'LSK': 0.3,
'LOC': 11.076,
'LUN': 0.34,
'MAID': 5,
'MANA': 143,
'MCAP': 5.44,
'MIPS': 43,
'MNE': 1.33,
'MSP': 121,
'MCO': 0.357,
'MTH': 92,
'MYB': 3.9,
'NDC': 165,
'NEBL': 0.04,
'NET': 3.96,
'NTO': 998,
'NGC': 2.368,
'NXC': 13.39,
'NXT': 3,
'OAX': 15,
'ODN': 0.004,
'OMG': 2,
'OPT': 335,
'ORME': 2.8,
'OTN': 0.57,
'PAY': 3.1,
'PIX': 96,
'PLBT': 0.33,
'PLR': 114,
'PLU': 0.87,
'POE': 784,
'POLL': 3.5,
'PPT': 2,
'PRE': 32,
'PRG': 39,
'PRO': 41,
'PRS': 60,
'PTOY': 0.5,
'QAU': 63,
'QCN': 0.03,
'QTUM': 0.04,
'QVT': 64,
'REP': 0.02,
'RKC': 15,
'RLC': 1.21,
'RVT': 14,
'SC': 30,
'SAN': 2.24,
'SBD': 0.03,
'SCL': 2.6,
'SISA': 1640,
'SKIN': 407,
'SWFTC': 352.94,
'SMART': 0.4,
'SMS': 0.0375,
'SNC': 36,
'SNGLS': 4,
'SNM': 48,
'SNT': 233,
'STAR': 0.144,
'STORM': 153.19,
'STEEM': 0.01,
'STRAT': 0.01,
'SPF': 14.4,
'STU': 14,
'STX': 11,
'SUB': 17,
'SUR': 3,
'SWT': 0.51,
'TAAS': 0.91,
'TBT': 2.37,
'TFL': 15,
'TIME': 0.03,
'TIX': 7.1,
'TKN': 1,
'TGT': 173,
'TKR': 84,
'TNT': 90,
'TRST': 1.6,
'TRX': 270,
'UET': 480,
'UGT': 15,
'UTT': 3,
'VEN': 14,
'VERI': 0.037,
'VIB': 50,
'VIBE': 145,
'VOISE': 618,
'WEALTH': 0.0168,
'WINGS': 2.4,
'WTC': 0.75,
'WRC': 48,
'XAUR': 3.23,
'XDN': 0.01,
'XEM': 15,
'XUC': 0.9,
'YOYOW': 140,
'ZAP': 24,
'ZRX': 23,
'ZSC': 191,
},
'deposit': {
'BTC': 0.0006,
'ETH': 0.003,
'BCH': 0,
'USDT': 0,
'BTG': 0,
'LTC': 0,
'ZEC': 0,
'XMR': 0,
'1ST': 0,
'ADX': 0,
'AE': 0,
'AEON': 0,
'AIR': 0,
'AMP': 0,
'ANT': 0,
'ARDR': 0,
'ARN': 0,
'ART': 0,
'ATB': 0,
'ATL': 0,
'ATM': 0,
'ATS': 0,
'AVT': 0,
'BAS': 0,
'BCN': 0,
'BET': 0,
'BKB': 0,
'BMC': 0,
'BMT': 0,
'BNT': 0,
'BQX': 0,
'BTM': 0,
'BTX': 0,
'BUS': 0,
'CCT': 0,
'CDT': 0,
'CDX': 0,
'CFI': 0,
'CLD': 0,
'CND': 0,
'CNX': 0,
'COSS': 0,
'CSNO': 0,
'CTR': 0,
'CTX': 0,
'CVC': 0,
'DBIX': 0,
'DCN': 0,
'DCT': 0,
'DDF': 0,
'DENT': 0,
'DGB': 0,
'DGD': 0,
'DICE': 0,
'DLT': 0,
'DNT': 0,
'DOGE': 0,
'DOV': 0,
'DRPU': 0,
'DRT': 0,
'DSH': 0,
'EBET': 0,
'EBTC': 0,
'EBTCOLD': 0,
'ECAT': 0,
'EDG': 0,
'EDO': 0,
'ELE': 0,
'ELM': 0,
'EMC': 0,
'EMGO': 0,
'ENJ': 0,
'EOS': 0,
'ERO': 0,
'ETBS': 0,
'ETC': 0,
'ETP': 0,
'EVX': 0,
'EXN': 0,
'FRD': 0,
'FUEL': 0,
'FUN': 0,
'FYN': 0,
'FYP': 0,
'GNO': 0,
'GUP': 0,
'GVT': 0,
'HAC': 0,
'HDG': 0,
'HGT': 0,
'HPC': 0,
'HVN': 0,
'ICN': 0,
'ICO': 0,
'ICOS': 0,
'IND': 0,
'INDI': 0,
'ITS': 0,
'IXT': 0,
'KBR': 0,
'KICK': 0,
'LA': 0,
'LAT': 0,
'LIFE': 0,
'LRC': 0,
'LSK': 0,
'LUN': 0,
'MAID': 0,
'MANA': 0,
'MCAP': 0,
'MIPS': 0,
'MNE': 0,
'MSP': 0,
'MTH': 0,
'MYB': 0,
'NDC': 0,
'NEBL': 0,
'NET': 0,
'NTO': 0,
'NXC': 0,
'NXT': 0,
'OAX': 0,
'ODN': 0,
'OMG': 0,
'OPT': 0,
'ORME': 0,
'OTN': 0,
'PAY': 0,
'PIX': 0,
'PLBT': 0,
'PLR': 0,
'PLU': 0,
'POE': 0,
'POLL': 0,
'PPT': 0,
'PRE': 0,
'PRG': 0,
'PRO': 0,
'PRS': 0,
'PTOY': 0,
'QAU': 0,
'QCN': 0,
'QTUM': 0,
'QVT': 0,
'REP': 0,
'RKC': 0,
'RVT': 0,
'SAN': 0,
'SBD': 0,
'SCL': 0,
'SISA': 0,
'SKIN': 0,
'SMART': 0,
'SMS': 0,
'SNC': 0,
'SNGLS': 0,
'SNM': 0,
'SNT': 0,
'STEEM': 0,
'STRAT': 0,
'STU': 0,
'STX': 0,
'SUB': 0,
'SUR': 0,
'SWT': 0,
'TAAS': 0,
'TBT': 0,
'TFL': 0,
'TIME': 0,
'TIX': 0,
'TKN': 0,
'TKR': 0,
'TNT': 0,
'TRST': 0,
'TRX': 0,
'UET': 0,
'UGT': 0,
'VEN': 0,
'VERI': 0,
'VIB': 0,
'VIBE': 0,
'VOISE': 0,
'WEALTH': 0,
'WINGS': 0,
'WTC': 0,
'XAUR': 0,
'XDN': 0,
'XEM': 0,
'XUC': 0,
'YOYOW': 0,
'ZAP': 0,
'ZRX': 0,
'ZSC': 0,
},
},
},
'options': {
'defaultTimeInForce': 'FOK',
},
'exceptions': {
'1003': PermissionDenied, // "Action is forbidden for this API key"
'2010': InvalidOrder, // "Quantity not a valid number"
'2011': InvalidOrder, // "Quantity too low"
'2020': InvalidOrder, // "Price not a valid number"
'20002': OrderNotFound, // canceling non-existent order
'20001': InsufficientFunds,
},
});
}
feeToPrecision (symbol, fee) {
return this.decimalToPrecision (fee, TRUNCATE, 8, DECIMAL_PLACES);
}
async fetchMarkets (params = {}) {
let markets = await this.publicGetSymbol ();
let result = [];
for (let i = 0; i < markets.length; i++) {
let market = markets[i];
let id = market['id'];
let baseId = market['baseCurrency'];
let quoteId = market['quoteCurrency'];
let base = this.commonCurrencyCode (baseId);
let quote = this.commonCurrencyCode (quoteId);
let symbol = base + '/' + quote;
let lot = this.safeFloat (market, 'quantityIncrement');
let step = this.safeFloat (market, 'tickSize');
let precision = {
'price': this.precisionFromString (market['tickSize']),
// FIXME: for lots > 1 the following line returns 0
// 'amount': this.precisionFromString (market['quantityIncrement']),
'amount': -1 * parseInt (Math.log10 (lot)),
};
let taker = this.safeFloat (market, 'takeLiquidityRate');
let maker = this.safeFloat (market, 'provideLiquidityRate');
result.push (this.extend (this.fees['trading'], {
'info': market,
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': true,
'taker': taker,
'maker': maker,
'precision': precision,
'limits': {
'amount': {
'min': lot,
'max': undefined,
},
'price': {
'min': step,
'max': undefined,
},
'cost': {
'min': lot * step,
'max': undefined,
},
},
}));
}
return result;
}
async fetchCurrencies (params = {}) {
let currencies = await this.publicGetCurrency (params);
let result = {};
for (let i = 0; i < currencies.length; i++) {
let currency = currencies[i];
let id = currency['id'];
// todo: will need to rethink the fees
// to add support for multiple withdrawal/deposit methods and
// differentiated fees for each particular method
let precision = 8; // default precision, todo: fix "magic constants"
let code = this.commonCurrencyCode (id);
let payin = this.safeValue (currency, 'payinEnabled');
let payout = this.safeValue (currency, 'payoutEnabled');
let transfer = this.safeValue (currency, 'transferEnabled');
let active = payin && payout && transfer;
if ('disabled' in currency)
if (currency['disabled'])
active = false;
let type = 'fiat';
if (('crypto' in currency) && currency['crypto'])
type = 'crypto';
result[code] = {
'id': id,
'code': code,
'type': type,
'payin': payin,
'payout': payout,
'transfer': transfer,
'info': currency,
'name': currency['fullName'],
'active': active,
'fee': this.safeFloat (currency, 'payoutFee'), // todo: redesign
'precision': precision,
'limits': {
'amount': {
'min': Math.pow (10, -precision),
'max': Math.pow (10, precision),
},
'price': {
'min': Math.pow (10, -precision),
'max': Math.pow (10, precision),
},
'cost': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': undefined,
'max': Math.pow (10, precision),
},
},
};
}
return result;
}
async fetchBalance (params = {}) {
await this.loadMarkets ();
let type = this.safeString (params, 'type', 'trading');
let method = 'privateGet' + this.capitalize (type) + 'Balance';
let query = this.omit (params, 'type');
let balances = await this[method] (query);
let result = { 'info': balances };
for (let b = 0; b < balances.length; b++) {
let balance = balances[b];
let code = balance['currency'];
let currency = this.commonCurrencyCode (code);
let account = {
'free': parseFloat (balance['available']),
'used': parseFloat (balance['reserved']),
'total': 0.0,
};
account['total'] = this.sum (account['free'], account['used']);
result[currency] = account;
}
return this.parseBalance (result);
}
parseOHLCV (ohlcv, market = undefined, timeframe = '1d', since = undefined, limit = undefined) {
let timestamp = this.parse8601 (ohlcv['timestamp']);
return [
timestamp,
parseFloat (ohlcv['open']),
parseFloat (ohlcv['max']),
parseFloat (ohlcv['min']),
parseFloat (ohlcv['close']),
parseFloat (ohlcv['volume']),
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let request = {
'symbol': market['id'],
'period': this.timeframes[timeframe],
};
if (limit !== undefined)
request['limit'] = limit;
let response = await this.publicGetCandlesSymbol (this.extend (request, params));
return this.parseOHLCVs (response, market, timeframe, since, limit);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {
'symbol': this.marketId (symbol),
};
if (limit !== undefined)
request['limit'] = limit; // default = 100, 0 = unlimited
let orderbook = await this.publicGetOrderbookSymbol (this.extend (request, params));
return this.parseOrderBook (orderbook, undefined, 'bid', 'ask', 'price', 'size');
}
parseTicker (ticker, market = undefined) {
let timestamp = this.parse8601 (ticker['timestamp']);
let symbol = undefined;
if (market)
symbol = market['symbol'];
let baseVolume = this.safeFloat (ticker, 'volume');
let quoteVolume = this.safeFloat (ticker, 'volumeQuote');
let open = this.safeFloat (ticker, 'open');
let last = this.safeFloat (ticker, 'last');
let change = undefined;
let percentage = undefined;
let average = undefined;
if (last !== undefined && open !== undefined) {
change = last - open;
average = this.sum (last, open) / 2;
if (open > 0)
percentage = change / open * 100;
}
let vwap = undefined;
if (quoteVolume !== undefined)
if (baseVolume !== undefined)
if (baseVolume > 0)
vwap = quoteVolume / baseVolume;
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (ticker, 'high'),
'low': this.safeFloat (ticker, 'low'),
'bid': this.safeFloat (ticker, 'bid'),
'bidVolume': undefined,
'ask': this.safeFloat (ticker, 'ask'),
'askVolume': undefined,
'vwap': vwap,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': change,
'percentage': percentage,
'average': average,
'baseVolume': baseVolume,
'quoteVolume': quoteVolume,
'info': ticker,
};
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
let tickers = await this.publicGetTicker (params);
let result = {};
for (let i = 0; i < tickers.length; i++) {
let ticker = tickers[i];
let id = ticker['symbol'];
let market = this.markets_by_id[id];
let symbol = market['symbol'];
result[symbol] = this.parseTicker (ticker, market);
}
return result;
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
let ticker = await this.publicGetTickerSymbol (this.extend ({
'symbol': market['id'],
}, params));
if ('message' in ticker)
throw new ExchangeError (this.id + ' ' + ticker['message']);
return this.parseTicker (ticker, market);
}
parseTrade (trade, market = undefined) {
//
// createMarketOrder
//
// { fee: "0.0004644",
// id: 386394956,
// price: "0.4644",
// quantity: "1",
// timestamp: "2018-10-25T16:41:44.780Z" }
//
// fetchTrades ...
//
// fetchMyTrades ...
//
let timestamp = this.parse8601 (trade['timestamp']);
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
} else {
let id = trade['symbol'];
if (id in this.markets_by_id) {
market = this.markets_by_id[id];
symbol = market['symbol'];
} else {
symbol = id;
}
}
let fee = undefined;
let feeCost = this.safeFloat (trade, 'fee');
if (feeCost !== undefined) {
let feeCurrency = market ? market['quote'] : undefined;
fee = {
'cost': feeCost,
'currency': feeCurrency,
};
}
let orderId = undefined;
if ('clientOrderId' in trade)
orderId = trade['clientOrderId'];
let price = this.safeFloat (trade, 'price');
let amount = this.safeFloat (trade, 'quantity');
let cost = price * amount;
let side = this.safeString (trade, 'side');
return {
'info': trade,
'id': trade['id'].toString (),
'order': orderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTransactions (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let currency = undefined;
const request = {};
if (code !== undefined) {
currency = this.currency (code);
request['asset'] = currency['id'];
}
if (since !== undefined) {
request['startTime'] = since;
}
let response = await this.privateGetAccountTransactions (this.extend (request, params));
return this.parseTransactions (response, currency, since, limit);
}
parseTransaction (transaction, currency = undefined) {
//
// {
// id: 'd53ee9df-89bf-4d09-886e-849f8be64647',
// index: 1044718371,
// type: 'payout',
// status: 'success',
// currency: 'ETH',
// amount: '4.522683200000000000000000',
// createdAt: '2018-06-07T00:43:32.426Z',
// updatedAt: '2018-06-07T00:45:36.447Z',
// hash: '0x973e5683dfdf80a1fb1e0b96e19085b6489221d2ddf864daa46903c5ec283a0f',
// address: '0xC5a59b21948C1d230c8C54f05590000Eb3e1252c',
// fee: '0.00958',
// },
// {
// id: 'e6c63331-467e-4922-9edc-019e75d20ba3',
// index: 1044714672,
// type: 'exchangeToBank',
// status: 'success',
// currency: 'ETH',
// amount: '4.532263200000000000',
// createdAt: '2018-06-07T00:42:39.543Z',
// updatedAt: '2018-06-07T00:42:39.683Z',
// },
// {
// id: '3b052faa-bf97-4636-a95c-3b5260015a10',
// index: 1009280164,
// type: 'bankToExchange',
// status: 'success',
// currency: 'CAS',
// amount: '104797.875800000000000000',
// createdAt: '2018-05-19T02:34:36.750Z',
// updatedAt: '2018-05-19T02:34:36.857Z',
// },
// {
// id: 'd525249f-7498-4c81-ba7b-b6ae2037dc08',
// index: 1009279948,
// type: 'payin',
// status: 'success',
// currency: 'CAS',
// amount: '104797.875800000000000000',
// createdAt: '2018-05-19T02:30:16.698Z',
// updatedAt: '2018-05-19T02:34:28.159Z',
// hash: '0xa6530e1231de409cf1f282196ed66533b103eac1df2aa4a7739d56b02c5f0388',
// address: '0xd53ed559a6d963af7cb3f3fcd0e7ca499054db8b',
// }
//
const id = this.safeString (transaction, 'id');
const timestamp = this.parse8601 (this.safeString (transaction, 'createdAt'));
const updated = this.parse8601 (this.safeString (transaction, 'updatedAt'));
let code = undefined;
const currencyId = this.safeString (transaction, 'currency');
if (currencyId in this.currencies_by_id) {
currency = this.currencies_by_id[currencyId];
code = currency['code'];
} else {
code = this.commonCurrencyCode (currencyId);
}
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const amount = this.safeFloat (transaction, 'amount');
let type = this.safeString (transaction, 'type');
if (type === 'payin') {
type = 'deposit';
} else if (type === 'payout') {
type = 'withdrawal';
}
const address = this.safeString (transaction, 'address');
const txid = this.safeString (transaction, 'hash');
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'address': address,
'tag': undefined,
'type': type,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': undefined,
};
}
parseTransactionStatus (status) {
let statuses = {
'pending': 'pending',
'failed': 'failed',
'success': 'ok',
};
return (status in statuses) ? statuses[status] : status;
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
const request = {
'symbol': market['id'],
};
if (limit !== undefined)
request['limit'] = limit;
if (since !== undefined) {
request['sort'] = 'ASC';
request['from'] = this.iso8601 (since);
}
let response = await this.publicGetTradesSymbol (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
let market = this.market (symbol);
// their max accepted length is 32 characters
let uuid = this.uuid ();
let parts = uuid.split ('-');
let clientOrderId = parts.join ('');
clientOrderId = clientOrderId.slice (0, 32);
amount = parseFloat (amount);
let request = {
'clientOrderId': clientOrderId,
'symbol': market['id'],
'side': side,
'quantity': this.amountToPrecision (symbol, amount),
'type': type,
};
if (type === 'limit') {
request['price'] = this.priceToPrecision (symbol, price);
} else {
request['timeInForce'] = this.options['defaultTimeInForce'];
}
let response = await this.privatePostOrder (this.extend (request, params));
let order = this.parseOrder (response);
if (order['status'] === 'rejected')
throw new InvalidOrder (this.id + ' order was rejected by the exchange ' + this.json (order));
let id = order['id'];
this.orders[id] = order;
return order;
}
async editOrder (id, symbol, type, side, amount = undefined, price = undefined, params = {}) {
await this.loadMarkets ();
// their max accepted length is 32 characters
let uuid = this.uuid ();
let parts = uuid.split ('-');
let requestClientId = parts.join ('');
requestClientId = requestClientId.slice (0, 32);
let request = {
'clientOrderId': id,
'requestClientId': requestClientId,
};
if (amount !== undefined)
request['quantity'] = this.amountToPrecision (symbol, amount);
if (price !== undefined)
request['price'] = this.priceToPrecision (symbol, price);
let response = await this.privatePatchOrderClientOrderId (this.extend (request, params));
let order = this.parseOrder (response);
this.orders[order['id']] = order;
return order;
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.privateDeleteOrderClientOrderId (this.extend ({
'clientOrderId': id,
}, params));
return this.parseOrder (response);
}
parseOrderStatus (status) {
const statuses = {
'new': 'open',
'suspended': 'open',
'partiallyFilled': 'open',
'filled': 'closed',
'canceled': 'canceled',
'expired': 'failed',
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// createMarketOrder
//
// { clientOrderId: "fe36aa5e190149bf9985fb673bbb2ea0",
// createdAt: "2018-10-25T16:41:44.780Z",
// cumQuantity: "1",
// id: "66799540063",
// quantity: "1",
// side: "sell",
// status: "filled",
// symbol: "XRPUSDT",
// timeInForce: "FOK",
// tradesReport: [ { fee: "0.0004644",
// id: 386394956,
// price: "0.4644",
// quantity: "1",
// timestamp: "2018-10-25T16:41:44.780Z" } ],
// type: "market",
// updatedAt: "2018-10-25T16:41:44.780Z" }
//
let created = this.parse8601 (this.safeString (order, 'createdAt'));
let updated = this.parse8601 (this.safeString (order, 'updatedAt'));
if (!market)
market = this.markets_by_id[order['symbol']];
let symbol = market['symbol'];
let amount = this.safeFloat (order, 'quantity');
let filled = this.safeFloat (order, 'cumQuantity');
let status = this.parseOrderStatus (this.safeString (order, 'status'));
let id = order['clientOrderId'].toString ();
let price = this.safeFloat (order, 'price');
if (price === undefined) {
if (id in this.orders)
price = this.orders[id]['price'];
}
let remaining = undefined;
let cost = undefined;
if (amount !== undefined) {
if (filled !== undefined) {
remaining = amount - filled;
if (price !== undefined) {
cost = filled * price;
}
}
}
const type = this.safeString (order, 'type');
const side = this.safeString (order, 'side');
let trades = this.safeValue (order, 'tradesReport');
let fee = undefined;
let average = undefined;
if (trades !== undefined) {
trades = this.parseTrades (trades, market);
let feeCost = undefined;
let sumOfPrices = undefined;
let numTrades = trades.length;
for (let i = 0; i < numTrades; i++) {
if (feeCost === undefined) {
feeCost = 0;
}
if (sumOfPrices === undefined) {
sumOfPrices = 0;
}
if (cost === undefined) {
cost = 0;
}
cost += trades[i]['cost'];
feeCost += trades[i]['fee']['cost'];
sumOfPrices += trades[i]['price'];
}
if ((sumOfPrices !== undefined) && (numTrades > 0)) {
average = sumOfPrices / numTrades;
if (type === 'market') {
if (price === undefined) {
price = average;
}
}
}
if (feeCost !== undefined) {
fee = {
'cost': feeCost,
'currency': market['quote'],
};
}
}
return {
'id': id,
'timestamp': created,
'datetime': this.iso8601 (created),
'lastTradeTimestamp': updated,
'status': status,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'average': average,
'amount': amount,
'cost': cost,
'filled': filled,
'remaining': remaining,
'fee': fee,
'trades': trades,
'info': order,
};
}
async fetchOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let response = await this.privateGetHistoryOrder (this.extend ({
'clientOrderId': id,
}, params));
let numOrders = response.length;
if (numOrders > 0)
return this.parseOrder (response[0]);
throw new OrderNotFound (this.id + ' order ' + id + ' not found');
}
async fetchOpenOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
let response = await this.privateGetOrderClientOrderId (this.extend ({
'clientOrderId': id,
}, params));
return this.parseOrder (response);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
let request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
let response = await this.privateGetOrder (this.extend (request, params));
return this.parseOrders (response, market, since, limit);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let market = undefined;
let request = {};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (limit !== undefined)
request['limit'] = limit;
if (since !== undefined)
request['from'] = this.iso8601 (since);
let response = await this.privateGetHistoryOrder (this.extend (request, params));
let parsedOrders = this.parseOrders (response, market);
let orders = [];
for (let i = 0; i < parsedOrders.length; i++) {
let order = parsedOrders[i];
let status = order['status'];
if ((status === 'closed') || (status === 'canceled')) {
orders.push (order);
}
}
return this.filterBySinceLimit (orders, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let request = {
// 'symbol': 'BTC/USD', // optional
// 'sort': 'DESC', // or 'ASC'
// 'by': 'timestamp', // or 'id' String timestamp by default, or id
// 'from': 'Datetime or Number', // ISO 8601
// 'till': 'Datetime or Number',
// 'limit': 100,
// 'offset': 0,
};
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined)
request['from'] = this.iso8601 (since);
if (limit !== undefined)
request['limit'] = limit;
let response = await this.privateGetHistoryTrades (this.extend (request, params));
return this.parseTrades (response, market, since, limit);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
// The id needed here is the exchange's id, and not the clientOrderID,
// which is the id that is stored in the unified order id
// To get the exchange's id you need to grab it from order['info']['id']
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined)
market = this.market (symbol);
let response = await this.privateGetHistoryOrderIdTrades (this.extend ({
'id': id,
}, params));
let numOrders = response.length;
if (numOrders > 0)
return this.parseTrades (response, market, since, limit);
throw new OrderNotFound (this.id + ' order ' + id + ' not found, ' + this.id + '.fetchOrderTrades() requires an exchange-specific order id, you need to grab it from order["info"]["id"]');
}
async createDepositAddress (code, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let response = await this.privatePostAccountCryptoAddressCurrency ({
'currency': currency['id'],
});
let address = response['address'];
this.checkAddress (address);
let tag = this.safeString (response, 'paymentId');
return {
'currency': currency,
'address': address,
'tag': tag,
'info': response,
};
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
let currency = this.currency (code);
let response = await this.privateGetAccountCryptoAddressCurrency ({
'currency': currency['id'],
});
let address = response['address'];
this.checkAddress (address);
let tag = this.safeString (response, 'paymentId');
return {
'currency': currency['code'],
'address': address,
'tag': tag,
'info': response,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
await this.loadMarkets ();
this.checkAddress (address);
let currency = this.currency (code);
let request = {
'currency': currency['id'],
'amount': parseFloat (amount),
'address': address,
};
if (tag)
request['paymentId'] = tag;
let response = await this.privatePostAccountCryptoWithdraw (this.extend (request, params));
return {
'info': response,
'id': response['id'],
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
let url = '/api/' + this.version + '/';
let query = this.omit (params, this.extractParams (path));
if (api === 'public') {
url += api + '/' + this.implodeParams (path, params);
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
this.checkRequiredCredentials ();
url += this.implodeParams (path, params);
if (method === 'GET') {
if (Object.keys (query).length)
url += '?' + this.urlencode (query);
} else {
if (Object.keys (query).length)
body = this.json (query);
}
let payload = this.encode (this.apiKey + ':' + this.secret);
let auth = this.stringToBase64 (payload);
headers = {
'Authorization': 'Basic ' + this.decode (auth),
'Content-Type': 'application/json',
};
}
url = this.urls['api'] + url;
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (code, reason, url, method, headers, body, response) {
if (typeof body !== 'string')
return;
if (code >= 400) {
const feedback = this.id + ' ' + body;
// {"code":504,"message":"Gateway Timeout","description":""}
if ((code === 503) || (code === 504))
throw new ExchangeNotAvailable (feedback);
// {"error":{"code":20002,"message":"Order not found","description":""}}
if (body[0] === '{') {
if ('error' in response) {
const code = this.safeString (response['error'], 'code');
const exceptions = this.exceptions;
if (code in exceptions) {
throw new exceptions[code] (feedback);
}
const message = this.safeString (response['error'], 'message');
if (message === 'Duplicate clientOrderId') {
throw new InvalidOrder (feedback);
}
}
}
throw new ExchangeError (feedback);
}
}
};
|
/*jshint esversion: 9 */
/*
File: ../keeper/src/data/cars.js
*/
const cars = [
{
model: "Honda Civic",
coloursByPopularity: ["black", "silver"],
speedStats: {
topSpeed: 140,
zeroToSixty: 8.5
}
},
{
model: "Tesla Model 3",
coloursByPopularity: ["red", "white"],
speedStats: {
topSpeed: 150,
zeroToSixty: 3.2
}
}
];
export default cars;
|
import React from "react";
import Layout from "../components/layout";
import { graphql, useStaticQuery } from "gatsby";
import thumbnailImg from "../images/pages/dove-dormire.jpg";
import PageContainer from "../components/styled/PageContainer";
import Hero from "../components/styled/Hero";
import { HeroTitle, HeroSubTitle } from "../components/styled/Typography";
import ArticlesContainer from "../components/styled/ArticlesContainer";
import CardAlbergo from "../components/CardAlbergo";
import SEO from "../components/seo";
import Fade from "../components/Fade";
import SlideIn from "../components/SlideIn";
const heroStyle = {
backgroundImage: `url(${thumbnailImg})`,
};
const Alberghi = ({ location }) => {
const contentfulData = useStaticQuery(graphql`
query {
allContentfulAlberghi {
edges {
node {
id
slug
nome
indirizzo
telefono
descrizione {
descrizione
}
immagine {
fluid {
src
}
}
}
}
}
}
`);
const alberghi = contentfulData.allContentfulAlberghi.edges;
const subtitle = `Negli ultimi anni sono nate a Nepi nuove strutture di accoglienza
per tutti i tipi di visitatore. L’offerta è ormai ampia ed adeguata.
Molte delle strutture sono situate nei pressi del centro
storico,quindi ideali come punto di partenza per le visite del
nostro borgo. Altre sono immerse nel verde e permettono il massimo
del relax e della tranquillità per alcuni giorni lontano dal caos
cittadino.`;
return (
<Layout location={location}>
<SEO title="Dove Dormire a Nepi" description={subtitle} />
<Hero style={heroStyle}>
<div className="content">
<Fade>
<HeroTitle>Dove Dormire</HeroTitle>
<HeroSubTitle>{subtitle}</HeroSubTitle>
</Fade>
</div>
</Hero>
<SlideIn>
<PageContainer>
<ArticlesContainer>
{alberghi
.sort(() => Math.random() - 0.5)
.map(albergo => (
<CardAlbergo key={albergo.node.id} data={albergo.node} />
))}
</ArticlesContainer>
</PageContainer>
</SlideIn>
</Layout>
);
};
export default Alberghi;
|
/* global angular */
(function (app) {
"use strict";
app.controller("admin1referalController",
["$scope", "assignmentsListService", "teachers", "AECListService", "StudentsService", '$modal', 'notify', '$http', '$localStorage',
function ($scope, assignmentsService, teachers, aec, students, $modal, notify, $http, $localStorage) {
$scope.selected = {}; // model for the possible selections (selected.student, or seleted.assignments)
$scope.currentDate = new Date(); // date on the datepicker
$scope.teacherStudents = []; // model for autocomplete
$scope.$storage = $localStorage;
// set ref table
$scope.$storage.refTable = $scope.$storage.refTable || [];
$scope.refTable = $scope.$storage.refTable; // model for dynamic table
$scope.edits = [];
$scope.$storage.eightPeriods = $scope.$storage.eightPeriods || [];
$scope.eightPeriods = $scope.$storage.eightPeriods;
$scope.$storage.ninethPeriods = $scope.$storage.ninethPeriods || [];
$scope.ninethPeriods = $scope.$storage.ninethPeriods;
$scope.teachers = teachers.query();
/**
* Watch for changes in the datepicker to add students to that date's
* AEC List
*/
$scope.$watch('form.date.$viewValue', function (newVal, oldVal) {
if (newVal) {//when date has a valid date request the List from that date
$scope.currentDate = newVal;
}
});
/* REFER A STUDENT LOGIC */
/**
* Called when a student is selected or deselected
* no action for now
*/
$scope.onSelectedStudent = function () {
return;
// add to the list
var alreadyInList = false;
for (var i = 0; i < $scope.refTable.length; i++) {
if ($scope.refTable[i].id === $scope.selected.student.user.id) {
alreadyInList = true;
}
}
if (!alreadyInList)
$scope.refTable.push($scope.selected.student.user);
else
alert('student is already in the list');
// clear the field
//$scope.selected.student = null;
};
/**
* Called when teacher is selected or deselected. Retrieves the selected
* teacher's students if a teacher is selected. If deselected
* set teacherStudents to null
*/
$scope.onSelectedTeacher = function () {
if (!$scope.selected.teacher) {// if teacher deselected
$scope.teacherStudents = null;
return;
}
$scope.selected.assignments = null;
$scope.teacherStudents = null;
var teacherId = $scope.selected.teacher.id;
students.query({teacherId: teacherId}, function (results) {
$scope.teacherStudents = results;
}, function (error) {
console.log(error);
});
};
/** New Assignment Modal
* Opens the New Assignment modal and passes in the teacher selected to be available
* in the modal context, on submit makes a post call to assignments
* to add the current assignment to the teacher
*/
$scope.openCreateNewAssignment = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/addNewAssignmentModal.html',
size: 'md',
controller: function ($scope, teacher) {
$scope.teacher = teacher;
},
resolve: {// variables that get injected into the controller (taken from current $scope)
teacher: function () {
return $scope.selected.teacher;
}
}
}); // End modalInstace
modalInstance.result.then(function (data) {
assignmentsService.save({
teacher: $scope.selected.teacher,
assignment: data
}, function (response) {
var teacher = $scope.selected.teacher;
response.assignment.Id = response.assignment.Id + "";
$scope.selected.teacher.assignments.push(response.assignment);
var assign = $scope.selected.assignments;
assign = assign ? assign : [];
assign.push(response.assignment);
}, function (response) {
});
});
};
/**
* Adds selected.student with selected.assignments to the refTable
* then clears selected.student
*/
$scope.addToList = function () {
var selectedAssignments = $scope.selected.assignments;
var referralToAdd = $scope.selected.student;
var selectedTeacher = $scope.selected.teacher;
if(!$scope.selected.assignments){
notify({
message: "Hold your horses, to add a student you need to select an assignment first.",
classes: 'alert-danger', templateUrl: 'views/common/notify.html'
});
}
console.log($scope.selected.student);
$http.get('api/classes/' + $scope.selected.student.id).then(function (response) {
referralToAdd.eightPeriod = response.data[7];
referralToAdd.ninethPeriod = response.data[8];
});
addAssignmentsToStudent(selectedAssignments, referralToAdd);
referralToAdd.teacher = $scope.selected.teacher;
$scope.refTable.unshift(referralToAdd);
console.log($scope.refTable);
$scope.selected.student = null;
};
/**
* Adds assignments to the student object
* @param {[objects]} assignments : list of assignment objects to be added
* @param {object} student :
*/
function addAssignmentsToStudent(assignments, student) {
if (!student.referred) {// current student doesnt have any assignments, add all the selected assignments
// copy assignments into referred
student.referred = assignments.slice();
return;
}
for (var i = 0; i < assignments.length; i++) {
var j = false;
for (j = 0; j < student.referred.length; j++) {// check if assignment is already in the student's list
if (student.referred[j].Id === assignments[i].Id)
break;
}
if (j === student.referred.length)// assignment is not already in the student
student.referred.unshift(assignments[i]);
}
delete student.selected; // delete the selected property;
}
/**
* POST API call to referrals. adds all the students in the refTable to the
* current date's AEC list.
* Despite the number of assignmets only 1 entry should be loged in
* into user activities with information containig the assignments
*/
$scope.submitReferedStudents = function () {
// format the data so it an be easily insterted in the database
var studentsReferred = [];
angular.forEach($scope.refTable, function (student) {
angular.forEach(student.referred, function (assignment) {
var referral = {
StudentId: student.id,
TeacherId: assignment.TeacherId,
AssignmentId: assignment.Id,
Date: $scope.currentDate
};
studentsReferred.push(referral);
});
});
if (studentsReferred.length)
aec.save({data: studentsReferred, date: $scope.currentDate},
function (response) {
notify({
message: "AEC List Was Submitted Successfully",
classes: 'alert-success', templateUrl: 'views/common/notify.html'
});
}, function (response) {
notify({
message: "Submit Failed, Please Contact The Admin",
classes: 'alert-danger', templateUrl: 'views/common/notify.html'
});
});
$scope.$storage.refTable = [];
$scope.refTable = $scope.$storage.refTable;
};
}]);
}(angular.module('Argus')));
|
import React from 'react';
import { View, StyleSheet, Text } from 'react-native';
import Colors from '../constants/colors';
const NumberContainer = (props) => {
return (
<View style={styles.container}>
<Text style={styles.number}>{props.children}</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
borderWidth: 2,
borderColor: Colors.accent,
padding: 10,
borderRadius: 10,
marginVertical: 10,
alignItems: 'center',
justifyContent: 'center',
},
number: {
color: Colors.accent,
fontSize: 22,
},
});
export default NumberContainer;
|
ko.extenders.numeric = function (target, precision) {
// Create a writeable computed observable to intercept writes to our observable.
var result = ko.computed({
read: target, //always return the original observables value
write: function (newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
// Only write if value changed.
if (valueToWrite !== current) {
target(valueToWrite);
} else {
// If the rounded value is the same but a different value was written, force a notification for the current field.
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
// Initialize with current value to make sure it is rounded appropriately.
result(target());
// Return the new computed observable.
return result;
};
ko.extenders.percent = function (target, precision) {
var result = ko.computed({
read: function () {
return (target() * 100).toFixed(precision) + "%";
},
write: function (newValue) {
target(parseFloat(newValue) / 100);
}
});
return result;
};
ko.extenders.currency = function (target, configArray) {
var precision = configArray[0],
rawValueObservable = configArray[1] || ko.observable();
// Create a writeable computed observable to intercept writes to our observable.
var result = ko.computed({
// Always return the original observable's value.
read: target,
write: function (newValue) {
newValue = newValue ? newValue : 0;
var current = target(),
cleansedValue = parseFloat(newValue.toString().replace(/[^\d.-]/g, '')),
newValueAsNum = isNaN(cleansedValue) ? 0 : parseFloat(+cleansedValue),
isNegativeValue = newValueAsNum < 0 ? true : false,
valueToFormat = parseFloat(newValue.toString().replace(/[^\.\d]/g, '')),
formattedValue = valueToFormat.formatNumber(precision),
valueToWrite = isNegativeValue ? '($' + formattedValue + ')' : '$' + formattedValue;
// Only write if value changed.
if (valueToWrite !== current) {
rawValueObservable(newValueAsNum);
target(valueToWrite);
}
//else {
// // If the rounded value is the same but a different value was written, force a notification for the current field.
// if (newValue !== current) {
// target.notifySubscribers(valueToWrite);
// }
//}
}
}).extend({ notify: 'always' });
// Initialize with current value to make sure it is rounded appropriately.
result(target());
// Return the new computed observable.
return result;
};
ko.extenders.computedCurrency = function (target, configArray) {
var precision = configArray[0],
result = ko.computed({
read: function () {
newValue = target(),
cleansedValue = parseFloat(newValue.toString().replace(/[^\d.-]/g, '')),
newValueAsNum = isNaN(cleansedValue) ? 0 : parseFloat(+cleansedValue),
isNegativeValue = newValueAsNum < 0 ? true : false,
valueToFormat = parseFloat(newValue.toString().replace(/[^\.\d]/g, '')),
formattedValue = valueToFormat.formatNumber(precision),
valueToWrite = isNegativeValue ? '($' + formattedValue + ')' : '$' + formattedValue;
return valueToWrite;
}
}).extend({ notify: 'always' });
return result;
}
// From Stack Overflow post: http://stackoverflow.com/questions/17841067/number-inputs-and-ranges-valueupdate-in-knockoutjs
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) {
value = 0;
}
$(element).slider("value", value);
}
};
ko.bindingHandlers.currencySlider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || (function () {
console.log('The [sliderOptions] binding was not found on the element.');
return {};
})(),
currencyObservable = allBindingsAccessor().currencyObservable || (function () {
console.log('The [currencyObservable] binding was not found on the element.');
return ko.observable(0);
})(),
totalObservable = allBindingsAccessor().totalObservable || (function () {
console.log('The [totalObservable] binding was not found on the element.');
return ko.observable(0);
})();
$(element).slider(options);
// Triggered on every mouse move during slide.
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
currencyObservable(Math.round(totalObservable() * (ui.value * .01)));
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) {
value = 0;
}
$(element).slider("value", value);
}
}
ko.subscribable.fn.subscribeChanged = function (callback) {
var oldValue;
this.subscribe(function (_oldValue) {
oldValue = _oldValue;
}, this, 'beforeChange');
this.subscribe(function (newValue) {
callback(newValue, oldValue);
});
};
|
export * from './components/store-notices-container';
export * from './context';
|
/**
* Copyright 2019 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f){
if (typeof define === 'function' && define.amd) {
define(["kendo.core"], f);
} else {
f();
}
}(function(){
(function( window, undefined ) {
kendo.cultures["saq-KE"] = {
name: "saq-KE",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Kenyan Shilling",
abbr: "KES",
pattern: ["-$n","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "Ksh"
}
},
calendars: {
standard: {
days: {
names: ["Mderot ee are","Mderot ee kuni","Mderot ee ong’wan","Mderot ee inet","Mderot ee ile","Mderot ee sapa","Mderot ee kwe"],
namesAbbr: ["Are","Kun","Ong","Ine","Ile","Sap","Kwe"],
namesShort: ["Are","Kun","Ong","Ine","Ile","Sap","Kwe"]
},
months: {
names: ["Lapa le obo","Lapa le waare","Lapa le okuni","Lapa le ong’wan","Lapa le imet","Lapa le ile","Lapa le sapa","Lapa le isiet","Lapa le saal","Lapa le tomon","Lapa le tomon obo","Lapa le tomon waare"],
namesAbbr: ["Obo","Waa","Oku","Ong","Ime","Ile","Sap","Isi","Saa","Tom","Tob","Tow"]
},
AM: ["AM","am","AM"],
PM: ["PM","pm","PM"],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, d MMMM yyyy",
F: "dddd, d MMMM yyyy HH:mm:ss",
g: "dd/MM/yyyy HH:mm",
G: "dd/MM/yyyy HH:mm:ss",
m: "MMMM d",
M: "MMMM d",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
}));
|
// The MIT License (MIT)
// Copyright (c) 2021 Oguzhan Soykan
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
function radar_visualization(config) {
// custom random number generator, to make random sequence reproducible
// source: https://stackoverflow.com/questions/521295
var seed = 42;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
function random_between(min, max) {
return min + random() * (max - min);
}
function normal_between(min, max) {
return min + (random() + random()) * 0.5 * (max - min);
}
// radial_min / radial_max are multiples of PI
const quadrants = [
{ radial_min: 0, radial_max: 0.5, factor_x: 1, factor_y: 1 },
{ radial_min: 0.5, radial_max: 1, factor_x: -1, factor_y: 1 },
{ radial_min: -1, radial_max: -0.5, factor_x: -1, factor_y: -1 },
{ radial_min: -0.5, radial_max: 0, factor_x: 1, factor_y: -1 },
{ radial_min: -0.3, radial_max: -0.5, factor_x: 1, factor_y: -1 }
];
const rings = [
{ radius: 130 },
{ radius: 220 },
{ radius: 310 },
{ radius: 400 }
];
const title_offset =
{ x: -675, y: -420 };
const footer_offset =
{ x: -675, y: 420 };
const legend_offset = [
{ x: 450, y: 90 },
{ x: -675, y: 90 },
{ x: -675, y: -320 },
{ x: 450, y: -320 },
{ x: 450, y: 400 }
];
function polar(cartesian) {
var x = cartesian.x;
var y = cartesian.y;
return {
t: Math.atan2(y, x),
r: Math.sqrt(x * x + y * y)
}
}
function cartesian(polar) {
return {
x: polar.r * Math.cos(polar.t),
y: polar.r * Math.sin(polar.t)
}
}
function bounded_interval(value, min, max) {
var low = Math.min(min, max);
var high = Math.max(min, max);
return Math.min(Math.max(value, low), high);
}
function bounded_ring(polar, r_min, r_max) {
return {
t: polar.t,
r: bounded_interval(polar.r, r_min, r_max)
}
}
function bounded_box(point, min, max) {
return {
x: bounded_interval(point.x, min.x, max.x),
y: bounded_interval(point.y, min.y, max.y)
}
}
function segment(quadrant, ring) {
var polar_min = {
t: quadrants[quadrant].radial_min * Math.PI,
r: ring === 0 ? 30 : rings[ring - 1].radius
};
var polar_max = {
t: quadrants[quadrant].radial_max * Math.PI,
r: rings[ring].radius
};
var cartesian_min = {
x: 15 * quadrants[quadrant].factor_x,
y: 15 * quadrants[quadrant].factor_y
};
var cartesian_max = {
x: rings[3].radius * quadrants[quadrant].factor_x,
y: rings[3].radius * quadrants[quadrant].factor_y
};
return {
clipx: function(d) {
var c = bounded_box(d, cartesian_min, cartesian_max);
var p = bounded_ring(polar(c), polar_min.r + 15, polar_max.r - 15);
d.x = cartesian(p).x; // adjust data too!
return d.x;
},
clipy: function(d) {
var c = bounded_box(d, cartesian_min, cartesian_max);
var p = bounded_ring(polar(c), polar_min.r + 15, polar_max.r - 15);
d.y = cartesian(p).y; // adjust data too!
return d.y;
},
random: function() {
return cartesian({
t: random_between(polar_min.t, polar_max.t),
r: normal_between(polar_min.r, polar_max.r)
});
}
}
}
// position each entry randomly in its segment
for (var i = 0; i < config.entries.length; i++) {
var entry = config.entries[i];
entry.segment = segment(entry.quadrant, entry.ring);
var point = entry.segment.random();
entry.x = point.x;
entry.y = point.y;
entry.color = entry.active || config.print_layout ?
config.rings[entry.ring].color : config.colors.inactive;
}
// partition entries according to segments
var segmented = new Array(5);
for (var quadrant = 0; quadrant < 5; quadrant++) {
segmented[quadrant] = new Array(5);
for (var ring = 0; ring < 4; ring++) {
segmented[quadrant][ring] = [];
}
}
for (var i=0; i<config.entries.length; i++) {
var entry = config.entries[i];
segmented[entry.quadrant][entry.ring].push(entry);
}
// assign unique sequential id to each entry
var id = 1;
for (var quadrant of [2,3,4,1,0]) {
for (var ring = 0; ring < 4; ring++) {
var entries = segmented[quadrant][ring];
entries.sort(function(a,b) { return a.label.localeCompare(b.label); })
for (var i=0; i<entries.length; i++) {
entries[i].id = "" + id++;
}
}
}
function translate(x, y) {
return "translate(" + x + "," + y + ")";
}
function viewbox(quadrant) {
return [
Math.max(0, quadrants[quadrant].factor_x * 400) - 420,
Math.max(0, quadrants[quadrant].factor_y * 400) - 420,
440,
440
].join(" ");
}
var svg = d3.select("svg#" + config.svg_id)
.style("background-color", config.colors.background)
.attr("width", config.width)
.attr("height", config.height);
var radar = svg.append("g");
if ("zoomed_quadrant" in config) {
svg.attr("viewBox", viewbox(config.zoomed_quadrant));
} else {
radar.attr("transform", translate(config.width / 2, config.height / 2));
}
var grid = radar.append("g");
// draw grid lines
grid.append("line")
.attr("x1", 0).attr("y1", -400)
.attr("x2", 0).attr("y2", 400)
.style("stroke", config.colors.grid)
.style("stroke-width", 1);
grid.append("line")
.attr("x1", -400).attr("y1", 0)
.attr("x2", 400).attr("y2", 0)
.style("stroke", config.colors.grid)
.style("stroke-width", 1);
// background color. Usage `.attr("filter", "url(#solid)")`
// SOURCE: https://stackoverflow.com/a/31013492/2609980
var defs = grid.append("defs");
var filter = defs.append("filter")
.attr("x", 0)
.attr("y", 0)
.attr("width", 1)
.attr("height", 1)
.attr("id", "solid");
filter.append("feFlood")
.attr("flood-color", "rgb(0, 0, 0, 0.8)");
filter.append("feComposite")
.attr("in", "SourceGraphic");
// draw rings
for (var i = 0; i < rings.length; i++) {
grid.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", rings[i].radius)
.style("fill", "none")
.style("stroke", config.colors.grid)
.style("stroke-width", 1);
if (config.print_layout) {
grid.append("text")
.text(config.rings[i].name)
.attr("y", -rings[i].radius + 62)
.attr("text-anchor", "middle")
.style("fill", "#e5e5e5")
.style("font-family", "Arial, Helvetica")
.style("font-size", "42px")
.style("font-weight", "bold")
.style("pointer-events", "none")
.style("user-select", "none");
}
}
function legend_transform(quadrant, ring, index=null) {
var dx = ring < 2 ? 0 : 140;
var dy = (index == null ? -16 : index * 14);
if (ring % 2 === 1) {
dy = dy + 36 + segmented[quadrant][ring-1].length * 12;
}
return translate(
legend_offset[quadrant].x + dx,
legend_offset[quadrant].y + dy
);
}
// draw title and legend (only in print layout)
if (config.print_layout) {
// title
radar.append("text")
.attr("transform", translate(title_offset.x, title_offset.y))
.text(config.title)
.style("font-family", "Arial, Helvetica")
.style("font-size", "34px");
// footer
radar.append("text")
.attr("transform", translate(footer_offset.x, footer_offset.y))
.text("▲ moved up ▼ moved down")
.attr("xml:space", "preserve")
.style("font-family", "Arial, Helvetica")
.style("font-size", "10px");
// legend
var legend = radar.append("g");
for (var quadrant = 0; quadrant < 5; quadrant++) {
legend.append("text")
.attr("transform", translate(
legend_offset[quadrant].x,
legend_offset[quadrant].y - 45
))
.text(config.quadrants[quadrant].name)
.style("font-family", "Arial, Helvetica")
.style("font-size", "18px");
for (var ring = 0; ring < 4; ring++) {
legend.append("text")
.attr("transform", legend_transform(quadrant, ring))
.text(config.rings[ring].name)
.style("font-family", "Arial, Helvetica")
.style("font-size", "12px")
.style("font-weight", "bold");
legend.selectAll(".legend" + quadrant + ring)
.data(segmented[quadrant][ring])
.enter()
.append("a")
.attr("href", function (d, i) {
return d.link ? d.link : "#"; // stay on same page if no link was provided
})
.append("text")
.attr("transform", function(d, i) { return legend_transform(quadrant, ring, i); })
.attr("class", "legend" + quadrant + ring)
.attr("id", function(d, i) { return "legendItem" + d.id; })
.text(function(d, i) { return d.id + ". " + d.label; })
.style("font-family", "Arial, Helvetica")
.style("font-size", "11px")
.on("mouseover", function(d) { showBubble(d); highlightLegendItem(d); })
.on("mouseout", function(d) { hideBubble(d); unhighlightLegendItem(d); });
}
}
}
// layer for entries
var rink = radar.append("g")
.attr("id", "rink");
// rollover bubble (on top of everything else)
var bubble = radar.append("g")
.attr("id", "bubble")
.attr("x", 0)
.attr("y", 0)
.style("opacity", 0)
.style("pointer-events", "none")
.style("user-select", "none");
bubble.append("rect")
.attr("rx", 4)
.attr("ry", 4)
.style("fill", "#333");
bubble.append("text")
.style("font-family", "sans-serif")
.style("font-size", "10px")
.style("fill", "#fff");
bubble.append("path")
.attr("d", "M 0,0 10,0 5,8 z")
.style("fill", "#333");
function showBubble(d) {
if (d.active || config.print_layout) {
var tooltip = d3.select("#bubble text")
.text(d.label);
var bbox = tooltip.node().getBBox();
d3.select("#bubble")
.attr("transform", translate(d.x - bbox.width / 2, d.y - 16))
.style("opacity", 0.8);
d3.select("#bubble rect")
.attr("x", -5)
.attr("y", -bbox.height)
.attr("width", bbox.width + 10)
.attr("height", bbox.height + 4);
d3.select("#bubble path")
.attr("transform", translate(bbox.width / 2 - 5, 3));
}
}
function hideBubble(d) {
var bubble = d3.select("#bubble")
.attr("transform", translate(0,0))
.style("opacity", 0);
}
function highlightLegendItem(d) {
var legendItem = document.getElementById("legendItem" + d.id);
legendItem.setAttribute("filter", "url(#solid)");
legendItem.setAttribute("fill", "white");
}
function unhighlightLegendItem(d) {
var legendItem = document.getElementById("legendItem" + d.id);
legendItem.removeAttribute("filter");
legendItem.removeAttribute("fill");
}
// draw blips on radar
var blips = rink.selectAll(".blip")
.data(config.entries)
.enter()
.append("g")
.attr("class", "blip")
.attr("transform", function(d, i) { return legend_transform(d.quadrant, d.ring, i); })
.on("mouseover", function(d) { showBubble(d); highlightLegendItem(d); })
.on("mouseout", function(d) { hideBubble(d); unhighlightLegendItem(d); });
// configure each blip
blips.each(function(d) {
var blip = d3.select(this);
// blip link
if (!config.print_layout && d.active && d.hasOwnProperty("link")) {
blip = blip.append("a")
.attr("xlink:href", d.link);
}
// blip shape
if (d.moved > 0) {
blip.append("path")
.attr("d", "M -11,5 11,5 0,-13 z") // triangle pointing up
.style("fill", d.color);
} else if (d.moved < 0) {
blip.append("path")
.attr("d", "M -11,-5 11,-5 0,13 z") // triangle pointing down
.style("fill", d.color);
} else {
blip.append("circle")
.attr("r", 9)
.attr("fill", d.color);
}
// blip text
if (d.active || config.print_layout) {
var blip_text = config.print_layout ? d.id : d.label.match(/[a-z]/i);
blip.append("text")
.text(blip_text)
.attr("y", 3)
.attr("text-anchor", "middle")
.style("fill", "#fff")
.style("font-family", "Arial, Helvetica")
.style("font-size", function(d) { return blip_text.length > 2 ? "8px" : "9px"; })
.style("pointer-events", "none")
.style("user-select", "none");
}
});
// make sure that blips stay inside their segment
function ticked() {
blips.attr("transform", function(d) {
return translate(d.segment.clipx(d), d.segment.clipy(d));
})
}
// distribute blips, while avoiding collisions
d3.forceSimulation()
.nodes(config.entries)
.velocityDecay(0.19) // magic number (found by experimentation)
.force("collision", d3.forceCollide().radius(12).strength(0.85))
.on("tick", ticked);
}
|
(function (angular, $, _) {
angular.module('crmMailing', [
'crmUtil', 'crmAttachment', 'crmAutosave', 'ngRoute', 'ui.utils', 'crmUi', 'dialogService'
]);
angular.module('crmMailing').config([
'$routeProvider',
function ($routeProvider) {
$routeProvider.when('/mailing', {
template: '<div></div>',
controller: 'ListMailingsCtrl'
});
if (!CRM || !CRM.crmMailing) {
return;
}
$routeProvider.when('/mailing/new', {
template: '<p>' + ts('Initializing...') + '</p>',
controller: 'CreateMailingCtrl',
resolve: {
selectedMail: function(crmMailingMgr) {
var m = crmMailingMgr.create({
template_type: CRM.crmMailing.templateTypes[0].name
});
return crmMailingMgr.save(m);
}
}
});
$routeProvider.when('/mailing/new/:templateType', {
template: '<p>' + ts('Initializing...') + '</p>',
controller: 'CreateMailingCtrl',
resolve: {
selectedMail: function($route, crmMailingMgr) {
var m = crmMailingMgr.create({
template_type: $route.current.params.templateType
});
return crmMailingMgr.save(m);
}
}
});
$routeProvider.when('/mailing/:id', {
templateUrl: '~/crmMailing/EditMailingCtrl/base.html',
controller: 'EditMailingCtrl',
resolve: {
selectedMail: function($route, crmMailingMgr) {
return crmMailingMgr.get($route.current.params.id);
},
attachments: function($route, CrmAttachments) {
var attachments = new CrmAttachments(function () {
return {entity_table: 'civicrm_mailing', entity_id: $route.current.params.id};
});
return attachments.load();
}
}
});
}
]);
})(angular, CRM.$, CRM._);
|
'use strict';
var Message = require('../message');
var inherits = require('util').inherits;
var umbrucore = require('umbrucore-lib');
var BufferReader = umbrucore.encoding.BufferReader;
var BufferWriter = umbrucore.encoding.BufferWriter;
var $ = umbrucore.util.preconditions;
function GetMnListDiffMessage(args, options) {
Message.call(this, options);
this.command = 'getmnlistdiff';
if (!args) {
args = {};
}
this.baseBlockHash = args.baseBlockHash;
this.blockHash = args.blockHash;
}
inherits(GetMnListDiffMessage, Message);
GetMnListDiffMessage.prototype.setPayload = function (payload) {
var parser = new BufferReader(payload);
$.checkArgument(!parser.finished(), 'No data received in payload');
this.baseBlockHash = parser.read(32).toString('hex');
this.blockHash = parser.read(32).toString('hex');
};
GetMnListDiffMessage.prototype.getPayload = function () {
var bw = new BufferWriter();
bw.write(new Buffer(this.baseBlockHash, 'hex'));
bw.write(new Buffer(this.blockHash, 'hex'));
return bw.concat();
};
module.exports = GetMnListDiffMessage;
|
'use strict'
const gulp = require('gulp')
const sass = require('gulp-sass')
const clipboard = require('gulp-clipboard')
const copy = require('copy-paste').copy
const log = require('fancy-log')
const p = require('path')
const fs = require('fs')
const paths = {
input: 'scss/styles.scss',
output: './web_root/scripts/CHANGE PATH HERE'
}
gulp.task('css', () => {
return gulp.src(paths.input)
.pipe(sass().on('error', sass.logError))
.pipe(clipboard())
.pipe(gulp.dest(paths.output))
})
gulp.task('default', ['css'], () => {
gulp.watch('scss/**/*.scss', ['css'])
gulp.watch('web_root/**/*', e => {
if (e.type !== 'changed') {
return;
}
fs.readFile(e.path, 'utf8', (err, data) => {
copy(data, () => {
log(`Copied ${p.basename(e.path)} to clipboard`)
})
})
})
})
|
import React, { useEffect} from 'react';
export const PinMap = (props) => {
useEffect(()=>{
},[])
return(
props.fill?
<PinMapIco />
://or
<PinMapFillIco />
)
}
const PinMapFillIco = (props) => {
return(
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-pin-map" viewBox="0 0 16 16">
<path fillRule="evenodd" d="M3.1 11.2a.5.5 0 0 1 .4-.2H6a.5.5 0 0 1 0 1H3.75L1.5 15h13l-2.25-3H10a.5.5 0 0 1 0-1h2.5a.5.5 0 0 1 .4.2l3 4a.5.5 0 0 1-.4.8H.5a.5.5 0 0 1-.4-.8l3-4z"/>
<path fillRule="evenodd" d="M8 1a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM4 4a4 4 0 1 1 4.5 3.969V13.5a.5.5 0 0 1-1 0V7.97A4 4 0 0 1 4 3.999z"/>
</svg>
)
}
const PinMapIco = (props) => {
return(
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" className="bi bi-pin-map-fill" viewBox="0 0 16 16">
<path fillRule="evenodd" d="M3.1 11.2a.5.5 0 0 1 .4-.2H6a.5.5 0 0 1 0 1H3.75L1.5 15h13l-2.25-3H10a.5.5 0 0 1 0-1h2.5a.5.5 0 0 1 .4.2l3 4a.5.5 0 0 1-.4.8H.5a.5.5 0 0 1-.4-.8l3-4z"/>
<path fillRule="evenodd" d="M4 4a4 4 0 1 1 4.5 3.969V13.5a.5.5 0 0 1-1 0V7.97A4 4 0 0 1 4 3.999z"/>
</svg>
)
}
|
//
// Charts
//
'use strict';
//
// Sales chart
//
var SalesChart = (function () {
// Variables
var $chart = $('#chart-sales-dark');
// Methods
function init($this) {
var salesChart = new Chart($this, {
type: 'line',
options: {
scales: {
yAxes: [
{
gridLines: {
color: Charts.colors.gray[700],
zeroLineColor: Charts.colors.gray[700],
},
ticks: {},
},
],
},
},
data: {
labels: ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [
{
label: 'Performance',
data: [0, 20, 10, 30, 15, 40, 20, 60, 60],
},
],
},
});
// Save to jQuery object
$this.data('chart', salesChart);
}
// Events
if ($chart.length) {
init($chart);
}
})();
|
import React from 'react';
import { View, Text, StyleSheet, Linking } from 'react-native';
const styles = StyleSheet.create({
boxStyle: {
flexDirection: 'column', alignItems: 'center', alignItems: 'center', backgroundColor: 'white',
padding: 10, marginTop: 10, margin: 5,
shadowColor: "#000", shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84,
elevation: 5, borderWidth: 0.3, borderColor: 'black'
},
linkText: { textDecorationLine: 'underline', color: '#995555' }
});
export default class GriffinCard extends React.Component {
render() {
return (
<View style={styles.boxStyle}>
<Text> Also, if you like hot sauce please visit: </Text>
<Text onPress={() => Linking.openURL('http://www.griffinsauce.com')} style={styles.linkText}>
http://www.griffinsauce.com
</Text>
</View>
);
}
}
|
import React from 'react';
import { observer } from 'mobx-react';
import { useRouter } from 'next/router';
import CompleteResetPassword from '@@/components/CompleteResetPassword';
import Layout from '@@/components/Layout';
import { sendNewUserEmail } from '@@/utils/API';
const SetPassword = () => {
const router = useRouter();
const { uuid, token } = router.query;
return (
<Layout>
<CompleteResetPassword
uuid={uuid}
token={token}
action="set"
resendEmail={() => sendNewUserEmail({ portunus_uuid: uuid })}
/>
</Layout>
);
};
SetPassword.public = true;
export default observer(SetPassword);
|
"use strict";
//local imports
const { newState } = require("../../../../../schemas");
const { actions } = require("../../../../../scripts/client/state/actions/actions");
const { testReducer } = require("../../../test-helpers");
//list clear state
test("reducer accepts LIST_CLEAR_STATE actions", () => {
const { listClearState } = actions;
testReducer(listClearState(), {
list: {
data: [{}],
menu: { search: "Apple" }
}
}, {
list: newState().list
});
});
//list set search
test("reducer accepts LIST_SET_SEARCH actions", () => {
const { listSetSearch } = actions;
testReducer(listSetSearch("Apple"), null, { list: { menu: { search: "Apple" } } });
});
|
module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'plugin:react/recommended',
'airbnb',
],
parserOptions: {
ecmaFeatures: {
js: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'react',
'react-hooks',
],
rules: {
'react/prop-types': 0,
'react/react-in-jsx-scope': 0,
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'import/no-unresolved': [2, { caseSensitive: false }],
'linebreak-style': 0,
'global-require': 0,
'eslint linebreak-style': [0, 'error', 'windows'],
'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx'] }],
'jsx-a11y/anchor-is-valid': 0,
},
};
|
const config = require('../config');
const mongojs = require('mongojs');
const logger = require('winston');
require('sugar').extend();
function stringId2ObjectId(obj) {
if (obj) {
Object.keys(obj).forEach((key) => {
if (key === '_id') {
if (typeof obj[key] == 'string') {
obj[key] = mongojs.ObjectId(obj[key]);
} else if (typeof obj[key] == 'object' && obj[key].$in) {
obj[key].$in = obj[key].$in.map((_id) => mongojs.ObjectId(_id));
}
} else if (typeof obj[key] == 'object') {
obj[key] = stringId2ObjectId(obj[key]);
}
});
}
return obj;
}
function buildFilter(realm, inputfilter) {
const filter = stringId2ObjectId(inputfilter);
if (realm) {
const realmFilter = {
realmId: realm._id,
};
const andArray = filter.$query ? filter.$query.$and : null;
if (andArray) {
andArray.push(realmFilter);
} else {
if (!filter.$query) {
filter.$query = {};
}
filter.$query.$and = [realmFilter];
}
}
return filter;
}
function logDBError(err) {
logger.error(new Error().stack);
logger.error(err);
}
const collections = [];
let db;
module.exports = {
init() {
if (!db) {
return new Promise((resolve, reject) => {
logger.debug(`connecting database ${config.MONGO_URL}...`);
db = mongojs(config.MONGO_URL, collections);
db.listCollections(() => {}); // Run this command to force connection a this stage
db.on('connect', function () {
logger.info(`connected to ${config.MONGO_URL}`);
resolve(db);
});
db.on('error', function (err) {
logger.error(`cannot connect to ${config.MONGO_URL}`);
reject(err);
});
});
}
logger.debug('database already connected');
return Promise.resolve(db);
},
exists() {
return new Promise((resolve /*, reject*/) => {
db.getCollectionNames((error, collectionNames) => {
resolve(!(error || !collectionNames || collectionNames.length === 0));
});
});
},
addCollection(collection) {
if (collections.indexOf(collection.toLowerCase()) >= 0) {
logger.silly(`db collection ${collection} already added`);
return;
}
collections.push(collection.toLowerCase());
logger.silly(`db collections have been updated ${collections}`);
},
findItemById(realm, collection, id, callback) {
logger.info(
`find item by id in collection ${collection} ${
realm && realm.length > 0 ? 'in realm: ' + realm.name : ''
}`
);
const query = buildFilter(realm, {
$query: {
_id: id,
},
});
logger.debug(`\tfilter is ${JSON.stringify(query)}`);
db[collection].find(query, function (err, dbItems) {
if (err || !dbItems || dbItems.length < 0) {
if (err) {
logDBError(err);
}
callback(['item has not been found in database']);
return;
}
logger.silly('\treturned values', dbItems.join('\n'));
callback([], dbItems);
});
},
listWithFilter(realm, collection, filter, callback) {
logger.info(
`find items in collection: ${collection}${
realm && realm.length > 0 ? ' in realm: ' + realm.name : ''
}`
);
const query = buildFilter(realm, filter);
if (query) {
logger.debug(`\tfilter is ${JSON.stringify(query)}`);
}
db[collection].find(query, function (err, dbItems) {
if (err) {
logDBError(err);
callback(['item has not been found in database']);
return;
}
if (dbItems) {
logger.silly('\treturned values', dbItems.join('\n'));
} else {
logger.silly('\treturned an empty list');
}
callback([], dbItems || []);
});
},
add(realm, collection, item, callback) {
logger.info(
`insert item in collection ${collection} ${
realm && realm.length > 0 ? 'in realm: ' + realm.name : ''
}`
);
item._id = mongojs.ObjectId();
if (realm) {
item.realmName = realm.name;
item.realmId = realm._id;
}
logger.debug('\titem is', item);
db[collection].save(item, function (err, saved) {
if (err || !saved) {
if (err) {
logDBError(err);
}
callback(['item not added in database']);
return;
}
item._id = item._id.toString();
logger.silly('\treturned values is', item);
callback([], item);
});
},
update(realm, collection, item, callback) {
logger.info(
`update items in collection: ${collection}${
realm && realm.length > 0 ? ' in realm: ' + realm.name : ''
}`
);
const _id = item._id.toString();
delete item._id;
const filter = buildFilter(null, { _id });
const itemToUpdate = {
$set: item,
};
if (realm) {
itemToUpdate.$set = Object.merge(item, {
realmName: realm.name,
realmId: realm._id,
});
}
logger.debug(`\tfilter is ${JSON.stringify(filter)}`);
logger.silly(`\titem to update is ${JSON.stringify(itemToUpdate)}`);
db[collection].update(
filter,
itemToUpdate,
{
multi: true,
},
(err, saved) => {
if (err || !saved) {
if (err) {
logDBError(err);
}
callback(['item has not been updated in database']);
return;
}
item._id = _id;
logger.silly('\treturned value is', item);
callback([], item);
}
);
},
upsert(realm, collection, query, fieldsToSet, fieldsToSetOnInsert, callback) {
logger.info(
`upsert in collection ${collection} ${
realm && realm.length > 0 ? 'in realm: ' + realm.name : ''
}`
);
const fieldsToUpdate = {
$set: fieldsToSet,
$setOnInsert: fieldsToSetOnInsert,
};
if (realm) {
fieldsToUpdate.$set = Object.merge(fieldsToSet, {
realmName: realm.name,
realmId: realm._id,
});
}
const options = {
upsert: true,
};
logger.debug(`\tfilter is ${JSON.stringify(query)}`);
logger.silly(`\titem to update is ${JSON.stringify(fieldsToSet)}`);
logger.silly(`\titem to insert is ${JSON.stringify(fieldsToSetOnInsert)}`);
db[collection].update(query, fieldsToUpdate, options, (err, saved) => {
if (err || !saved) {
if (err) {
logDBError(err);
}
callback(['item has not been updated in database']);
return;
}
callback([]);
});
},
remove(realm, collection, items, callback) {
logger.info(
`remove items in collection: ${collection}${
realm && realm.length > 0 ? 'in realm: ' + realm.name : ''
}`
);
const filter = buildFilter(null, {
$or: items.map((item) => {
return { _id: item };
}),
});
logger.debug(`\tfilter is ${JSON.stringify(filter)}`);
db[collection].remove(filter, function (err, deleted) {
if (err || !deleted) {
if (err) {
logDBError(err);
}
callback(['item has not been deleted in database']);
return;
}
callback([]);
});
},
};
|
var searchData=
[
['updatebeatcount_218',['UpdateBeatCount',['../class_performance_indicator.html#a1dc851536bf2e405aef31fe7958d51a6',1,'PerformanceIndicator']]],
['updatedynamicvalues_219',['updateDynamicValues',['../class_controller_data_updater.html#a7583f24652a79ee14fdf35387948586c',1,'ControllerDataUpdater']]],
['updatestaticvalues_220',['updateStaticValues',['../class_controller_data_updater.html#afa1159a2150837e6192fa0801bc7b9af',1,'ControllerDataUpdater']]],
['updatevalueswithconductorsample_221',['updateValuesWithConductorSample',['../class_controller_data_updater.html#a27995608c74f718598fc9045c274f0c5',1,'ControllerDataUpdater.updateValuesWithConductorSample()'],['../class_trial_display_behaviour.html#aa45a6bdfacde3a5c451ebe947740d02e',1,'TrialDisplayBehaviour.updateValuesWithConductorSample()']]]
];
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=/users/hansl/sources/hansl/angular-cli/src/webpack.js.map
|
import React, {Component} from 'react'
import {PropTypes} from 'prop-types'
import {SummaryPos} from './index'
class Summary extends Component {
constructor(props) {
super(props);
}
static propTypes = {
schedulerData: PropTypes.object.isRequired,
summary: PropTypes.object.isRequired,
left: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
top: PropTypes.number.isRequired,
}
render() {
const {summary, left, width, top, schedulerData} = this.props;
const {config} = schedulerData;
let color = config.summaryColor;
if(summary.color != undefined)
color = summary.color;
let textAlign = 'center';
if(config.summaryPos === SummaryPos.TopRight || config.summaryPos === SummaryPos.BottomRight)
textAlign = 'right';
else if(config.summaryPos === SummaryPos.TopLeft || config.summaryPos === SummaryPos.BottomLeft)
textAlign = 'left';
let style = {height: config.indicatorHeight, color: color, textAlign: textAlign, marginLeft: '6px', marginRight: '6px'};
if(summary.fontSize != undefined)
style = {...style, fontSize: summary.fontSize};
return (
<a className="timeline-event header2-text" style={{left: left, width: width, top: top, cursor: 'default'}} >
<div style={style}>
{summary.text}
</div>
</a>
);
}
}
export default Summary
|
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson (MPL-1.1 OR Apache-2.0 OR GPL-2.0-or-later)
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
import { makeMap, no } from 'shared/util'
import { isNonPhrasingTag } from 'web/compiler/util'
import { unicodeRegExp } from 'core/util/lang'
// Regular Expressions for parsing tags and attributes
// 解析标签和属性的正则表达式
const attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
const dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/
const ncname = `[a-zA-Z_][\\-\\.0-9_a-zA-Z${unicodeRegExp.source}]*` // 返回正则表达式的源文本内容,不包括标志, 比如/g等
const qnameCapture = `((?:${ncname}\\:)?${ncname})`
const startTagOpen = new RegExp(`^<${qnameCapture}`)
const startTagClose = /^\s*(\/?)>/
const endTag = new RegExp(`^<\\/${qnameCapture}[^>]*>`)
const doctype = /^<!DOCTYPE [^>]+>/i
// #7298: escape - to avoid being passed as HTML comment when inlined in page
// HTML中的注释 <!-- -->
const comment = /^<!\--/
// 条件注释
// <![if IE]>
// <![endif]>
const conditionalComment = /^<!\[/
// Special Elements (can contain anything)
// 纯文本元素
export const isPlainTextElement = makeMap('script,style,textarea', true) // expectsLowerCase为true
const reCache = {}
// 解码映射
const decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n',
'	': '\t',
''': "'"
}
// 已编码属性的正则表达式
const encodedAttr = /&(?:lt|gt|quot|amp|#39);/g
// 包括 \n 和 \t
const encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g
// #5992
// <pre> <textarea> 忽略\n
const isIgnoreNewlineTag = makeMap('pre,textarea', true)
// 是pre 或者 textarea标签, 且第一个字符是 \n
const shouldIgnoreFirstNewline = (tag, html) => tag && isIgnoreNewlineTag(tag) && html[0] === '\n'
// 解码操作, 比如: 将 < 解码成 <
function decodeAttr (value, shouldDecodeNewlines) {
const re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr
// 把value中与正则表达式re匹配的子串match 替换成 decodingMap[match] 因为re有/g 会替换所有匹配的子串,否则只替换第一个匹配的子串
return value.replace(re, match => decodingMap[match])
}
// HTML解析函数
export function parseHTML (html, options) {
// stack中存在的是开始标签
const stack = []
const expectHTML = options.expectHTML
const isUnaryTag = options.isUnaryTag || no // unary tag 一元标签
// 可以缺失闭合标签, 自己可以闭合
const canBeLeftOpenTag = options.canBeLeftOpenTag || no
// 全局索引变量
let index = 0
// lastTag代表stack中的最后一个标签
let last, lastTag
// 循环遍历html的每个字符
while (html) {
last = html
// Make sure we're not in a plaintext content element like script/style
if (!lastTag || !isPlainTextElement(lastTag)) {
// < 标志文本的结束, <之前的是文本
let textEnd = html.indexOf('<')
// 以 < 开始, 没有text文本
if (textEnd === 0) {
// Comment: 注释
// RegExp.test(str) 如果str中包含与RegExp匹配的文本返回true,否则返回false
if (comment.test(html)) {
const commentEnd = html.indexOf('-->')
if (commentEnd >= 0) {
if (options.shouldKeepComment) {
// <!-- --> 分别是4个字符和3个字符
// 为注释新建一个ASTText, 并添加到抽象语法树中 options.comment定义在./index.js中
options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3)
}
// advance(n), index右移n html赋值为[n, 末尾]
advance(commentEnd + 3)
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
// downlevel revealed conditional comment
if (conditionalComment.test(html)) {
const conditionalEnd = html.indexOf(']>')
// 右移2位
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2)
continue
}
}
// Doctype: 文档类型
// match(substr or reg) 返回 null 或 数组 数组[0]是匹配的文本
const doctypeMatch = html.match(doctype)
// 非null, 表示匹配成功
if (doctypeMatch) {
// 向右移动匹配子串的长度
advance(doctypeMatch[0].length)
continue
}
// End tag:
const endTagMatch = html.match(endTag)
if (endTagMatch) {
const curIndex = index
advance(endTagMatch[0].length)
// 解析闭合标签
parseEndTag(endTagMatch[1], curIndex, index)
continue
}
// Start tag:
const startTagMatch = parseStartTag()
if (startTagMatch) {
// ?
handleStartTag(startTagMatch)
if (shouldIgnoreFirstNewline(startTagMatch.tagName, html)) {
advance(1)
}
continue
}
}
// 有text文本内容
let text, rest, next
if (textEnd >= 0) {
// 获取剩余的html内容 [textEnd ...]
rest = html.slice(textEnd)
while (
!endTag.test(rest) &&
!startTagOpen.test(rest) &&
!comment.test(rest) &&
!conditionalComment.test(rest)
) {
// < in plain text, be forgiving and treat it as text
// 纯文本中的字符'<' 被视为文本
next = rest.indexOf('<', 1) // 从位置1开始查找
if (next < 0) break
textEnd += next
rest = html.slice(textEnd)
}
// 文本字符串
text = html.substring(0, textEnd)
}
// 整个html是文本
if (textEnd < 0) {
text = html
}
if (text) {
advance(text.length)
}
// 解析文本节点
if (options.chars && text) {
options.chars(text, index - text.length, index)
}
} else {
//
let endTagLength = 0
const stackedTag = lastTag.toLowerCase()
const reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'))
const rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length
if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') {
text = text
.replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')
}
if (shouldIgnoreFirstNewline(stackedTag, text)) {
text = text.slice(1)
}
// 为text创建 ASTNode
if (options.chars) {
options.chars(text)
}
return ''
})
index += html.length - rest.length
html = rest
parseEndTag(stackedTag, index - endTagLength, index)
}
if (html === last) {
options.chars && options.chars(html)
if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) {
options.warn(`Mal-formatted tag at end of template: "${html}"`, { start: index + html.length })
}
break
}
}
// Clean up any remaining tags
// 将stack中存在的未闭合的标签处理完毕
parseEndTag()
function advance (n) {
index += n
// substring(start, end) 从[start end)的子串, 缺省end代表到末尾
html = html.substring(n)
}
// 解析开始标签, 包括标签名 属性数组 等 返回一个match对象
function parseStartTag () {
const start = html.match(startTagOpen)
if (start) {
// 开始标签 属性
const match = {
tagName: start[1],
attrs: [],
start: index
}
advance(start[0].length)
let end, attr
// 获取标签的属性
while (!(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute))) {
attr.start = index
advance(attr[0].length)
attr.end = index
match.attrs.push(attr)
}
// 到开始标签的最后了
if (end) {
match.unarySlash = end[1] // 一元 斜杠 <br />
advance(end[0].length)
match.end = index
return match
}
}
}
// 处理开始标签
function handleStartTag (match) {
const tagName = match.tagName
const unarySlash = match.unarySlash
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag)
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName)
}
}
const unary = isUnaryTag(tagName) || !!unarySlash
const l = match.attrs.length
const attrs = new Array(l)
// 循环处理开始标签的每个属性
for (let i = 0; i < l; i++) {
const args = match.attrs[i]
const value = args[3] || args[4] || args[5] || ''
const shouldDecodeNewlines = tagName === 'a' && args[1] === 'href'
? options.shouldDecodeNewlinesForHref
: options.shouldDecodeNewlines
attrs[i] = {
name: args[1],
value: decodeAttr(value, shouldDecodeNewlines)
}
if (process.env.NODE_ENV !== 'production' && options.outputSourceRange) {
attrs[i].start = args.start + args[0].match(/^\s*/).length
attrs[i].end = args.end
}
}
// 如果不是一元标签,将此标签信息存入stack,并将其设置为lastTag
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs, start: match.start, end: match.end })
lastTag = tagName
}
// 生成 ASTElement
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end)
}
}
// 解析结束标签,
function parseEndTag (tagName, start, end) {
let pos, lowerCasedTagName
if (start == null) start = index
if (end == null) end = index
// Find the closest opened tag of the same type
// 在stack中查询最近的相同类型的未闭合标签
// stack中存在的是开始标签
if (tagName) {
lowerCasedTagName = tagName.toLowerCase()
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
// 没有提供标签名
pos = 0
}
if (pos >= 0) {
// 沿着堆栈 关闭所有未闭合的标签
// Close all the open elements, up the stack
for (let i = stack.length - 1; i >= pos; i--) {
// stack[i]标签没有闭合,也没有机会闭合了
if (process.env.NODE_ENV !== 'production' &&
(i > pos || !tagName) &&
options.warn
) {
// 给出标签未闭合错误信息
options.warn(
`tag <${stack[i].tag}> has no matching end tag.`,
{ start: stack[i].start, end: stack[i].end }
)
}
if (options.end) {
// 闭合标签 stack[i].tag, 组装抽象语法树AST
options.end(stack[i].tag, start, end)
}
}
// Remove the open elements from the stack
// 将未闭合的标签从stack中移除
stack.length = pos
// stack中的最后一个标签
lastTag = pos && stack[pos - 1].tag
} else if (lowerCasedTagName === 'br') { // <br> <br /> 没有闭合标签 </br>是错误的
if (options.start) {
// br是一元标签 生成一个ASTElement 然后调用closeElement(element) 闭合标签
options.start(tagName, [], true, start, end) // tagname attrs unary start end
}
} else if (lowerCasedTagName === 'p') {
// p不是一元标签,先调用start生成ASTElement, 再调用end组装抽象语法树AST
if (options.start) {
options.start(tagName, [], false, start, end)
}
if (options.end) {
options.end(tagName, start, end)
}
}
}
}
|
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.ReactBootstrap=t(require("react"),require("react-dom")):e.ReactBootstrap=t(e.React,e.ReactDOM)}(window,(function(e,t){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var a=t[r]={i:r,l:!1,exports:{}};return e[r].call(a.exports,a,a.exports,n),a.l=!0,a.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)n.d(r,a,function(t){return e[t]}.bind(null,a));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=11)}([function(t,n){t.exports=e},function(e,t,n){e.exports=n(8)()},function(e,t,n){var r;
/*!
Copyright (c) 2017 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/!function(){"use strict";var n={}.hasOwnProperty;function a(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r)&&r.length){var i=a.apply(null,r);i&&e.push(i)}else if("object"===o)for(var s in r)n.call(r,s)&&r[s]&&e.push(s)}}return e.join(" ")}e.exports?(a.default=a,e.exports=a):void 0===(r=function(){return a}.apply(t,[]))||(e.exports=r)}()},function(e,n){e.exports=t},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t,n){"use strict";e.exports=function(e,t,n,r,a,o,i,s){if(!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,a,o,i,s],u=0;(l=new Error(t.replace(/%s/g,(function(){return c[u++]})))).name="Invariant Violation"}throw l.framesToPop=1,l}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return function(t,n,r,a,o){var i=r||"<<anonymous>>",s=o||n;if(null==t[n])return new Error("The "+a+" `"+s+"` is required to make `"+i+"` accessible for users of assistive technologies such as screen readers.");for(var l=arguments.length,c=Array(l>5?l-5:0),u=5;u<l;u++)c[u-5]=arguments[u];return e.apply(void 0,[t,n,r,a,o].concat(c))}},e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];function r(){for(var e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];var a=null;return t.forEach((function(e){if(null==a){var t=e.apply(void 0,n);null!=t&&(a=t)}})),a}return(0,o.default)(r)};var r,a=n(10),o=(r=a)&&r.__esModule?r:{default:r};e.exports=t.default},function(e,t,n){"use strict";var r=n(9);function a(){}function o(){}o.resetWarningCache=a,e.exports=function(){function e(e,t,n,a,o,i){if(i!==r){var s=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw s.name="Invariant Violation",s}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:o,resetWarningCache:a};return n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(t,n,r,a,o,i){var s=a||"<<anonymous>>",l=i||r;if(null==n[r])return t?new Error("Required "+o+" `"+l+"` was not specified in `"+s+"`."):null;for(var c=arguments.length,u=Array(c>6?c-6:0),d=6;d<c;d++)u[d-6]=arguments[d];return e.apply(void 0,[n,r,s,o,l].concat(u))}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n},e.exports=t.default},function(e,t,n){"use strict";function r(){return(r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function a(e,t){if(null==e)return{};var n,r,a={},o=Object.keys(e);for(r=0;r<o.length;r++)n=o[r],t.indexOf(n)>=0||(a[n]=e[n]);return a}n.r(t),n.d(t,"Accordion",(function(){return fe})),n.d(t,"AccordionContext",(function(){return P})),n.d(t,"AccordionCollapse",(function(){return ue})),n.d(t,"AccordionToggle",(function(){return k})),n.d(t,"useAccordionToggle",(function(){return j})),n.d(t,"Alert",(function(){return De})),n.d(t,"Badge",(function(){return Ae})),n.d(t,"Breadcrumb",(function(){return _e})),n.d(t,"BreadcrumbItem",(function(){return Be})),n.d(t,"Button",(function(){return ze})),n.d(t,"ButtonGroup",(function(){return qe})),n.d(t,"ButtonToolbar",(function(){return We})),n.d(t,"Card",(function(){return lt})),n.d(t,"CardColumns",(function(){return ct})),n.d(t,"CardDeck",(function(){return ut})),n.d(t,"CardImg",(function(){return Ye})),n.d(t,"CardGroup",(function(){return dt})),n.d(t,"Carousel",(function(){return Pt})),n.d(t,"CarouselItem",(function(){return yt})),n.d(t,"CloseButton",(function(){return Ee})),n.d(t,"Col",(function(){return Tt})),n.d(t,"Collapse",(function(){return le})),n.d(t,"Dropdown",(function(){return _r})),n.d(t,"DropdownButton",(function(){return Vr})),n.d(t,"Fade",(function(){return ge})),n.d(t,"Form",(function(){return ga})),n.d(t,"FormControl",(function(){return sa})),n.d(t,"FormCheck",(function(){return Qr})),n.d(t,"FormFile",(function(){return oa})),n.d(t,"FormGroup",(function(){return ca})),n.d(t,"FormLabel",(function(){return da})),n.d(t,"FormText",(function(){return pa})),n.d(t,"Container",(function(){return xa})),n.d(t,"Image",(function(){return Oa})),n.d(t,"Figure",(function(){return ka})),n.d(t,"InputGroup",(function(){return Ia})),n.d(t,"Jumbotron",(function(){return Fa})),n.d(t,"ListGroup",(function(){return Wa})),n.d(t,"ListGroupItem",(function(){return Va})),n.d(t,"Media",(function(){return Ya})),n.d(t,"Modal",(function(){return Io})),n.d(t,"ModalBody",(function(){return xo})),n.d(t,"ModalDialog",(function(){return Oo})),n.d(t,"ModalFooter",(function(){return No})),n.d(t,"ModalTitle",(function(){return ko})),n.d(t,"Nav",(function(){return _o})),n.d(t,"Navbar",(function(){return $o})),n.d(t,"NavbarBrand",(function(){return zo})),n.d(t,"NavDropdown",(function(){return Zo})),n.d(t,"NavItem",(function(){return Fo})),n.d(t,"NavLink",(function(){return Bo})),n.d(t,"Overlay",(function(){return ri})),n.d(t,"OverlayTrigger",(function(){return si})),n.d(t,"PageItem",(function(){return ci})),n.d(t,"Pagination",(function(){return hi})),n.d(t,"Popover",(function(){return Ei})),n.d(t,"PopoverTitle",(function(){return gi})),n.d(t,"PopoverContent",(function(){return yi})),n.d(t,"ProgressBar",(function(){return Ci})),n.d(t,"ResponsiveEmbed",(function(){return ji})),n.d(t,"Row",(function(){return Ti})),n.d(t,"SafeAnchor",(function(){return ke})),n.d(t,"Spinner",(function(){return Mi})),n.d(t,"SplitButton",(function(){return Fi})),n.d(t,"Tab",(function(){return Hi})),n.d(t,"TabContainer",(function(){return Ai})),n.d(t,"TabContent",(function(){return Li})),n.d(t,"Table",(function(){return zi})),n.d(t,"TabPane",(function(){return Ki})),n.d(t,"Tabs",(function(){return Ui})),n.d(t,"ThemeProvider",(function(){return w})),n.d(t,"Toast",(function(){return Ji})),n.d(t,"ToastBody",(function(){return $i})),n.d(t,"ToastHeader",(function(){return Xi})),n.d(t,"ToggleButton",(function(){return es})),n.d(t,"ToggleButtonGroup",(function(){return ns})),n.d(t,"Tooltip",(function(){return as}));var o=n(2),i=n.n(o),s=n(0),l=n.n(s),c=n(5),u=n.n(c);function d(e){return"default"+e.charAt(0).toUpperCase()+e.substr(1)}function f(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:String(t)}function p(e,t,n){var r=Object(s.useRef)(void 0!==e),a=Object(s.useState)(t),o=a[0],i=a[1],l=void 0!==e,c=r.current;return r.current=l,!l&&c&&o!==t&&i(t),[l?e:o,Object(s.useCallback)((function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),a=1;a<t;a++)r[a-1]=arguments[a];n&&n.apply(void 0,[e].concat(r)),i(e)}),[n])]}function m(e,t){return Object.keys(t).reduce((function(n,o){var i,s=n,l=s[d(o)],c=s[o],u=a(s,[d(o),o].map(f)),m=t[o],v=p(c,l,e[m]),b=v[0],h=v[1];return r({},u,((i={})[o]=b,i[m]=h,i))}),e)}function v(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function b(){var e=this.constructor.getDerivedStateFromProps(this.props,this.state);null!=e&&this.setState(e)}function h(e){this.setState(function(t){var n=this.constructor.getDerivedStateFromProps(e,t);return null!=n?n:null}.bind(this))}function g(e,t){try{var n=this.props,r=this.state;this.props=e,this.state=t,this.__reactInternalSnapshotFlag=!0,this.__reactInternalSnapshot=this.getSnapshotBeforeUpdate(n,r)}finally{this.props=n,this.state=r}}b.__suppressDeprecationWarning=!0,h.__suppressDeprecationWarning=!0,g.__suppressDeprecationWarning=!0;var y=l.a.createContext({}),x=(y.Consumer,y.Provider);function E(e,t){var n=Object(s.useContext)(y);return e||n[t]||t}var w=function(e){var t=e.prefixes,n=e.children,a=Object(s.useMemo)((function(){return r({},t)}),[t]);return l.a.createElement(x,{value:a},n)},O=function(e,t){return void 0===t&&(t=null),null!=e?String(e):t||null},N=l.a.createContext(null),C=l.a.createContext(null);C.displayName="AccordionContext";var P=C;function j(e,t){var n=Object(s.useContext)(P),r=Object(s.useContext)(N);return function(a){r&&r(e===n?null:e,a),t&&t(a)}}var k=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"button":n,i=e.children,s=e.eventKey,c=e.onClick,u=a(e,["as","children","eventKey","onClick"]),d=j(s,c);return"button"===o&&(u.type="button"),l.a.createElement(o,r({ref:t,onClick:d},u),i)}));function R(e){return e&&e.ownerDocument||document}function T(e,t){return function(e){var t=R(e);return t&&t.defaultView||window}(e).getComputedStyle(e,t)}var S=/([A-Z])/g;var M=/^ms-/;function I(e){return function(e){return e.replace(S,"-$1").toLowerCase()}(e).replace(M,"-ms-")}var D=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i;var F=function(e,t){var n="",r="";if("string"==typeof t)return e.style.getPropertyValue(I(t))||T(e).getPropertyValue(I(t));Object.keys(t).forEach((function(a){var o=t[a];o||0===o?!function(e){return!(!e||!D.test(e))}(a)?n+=I(a)+": "+o+";":r+=a+"("+o+") ":e.style.removeProperty(I(a))})),r&&(n+="transform: "+r+";"),e.style.cssText+=";"+n},A=!("undefined"==typeof window||!window.document||!window.document.createElement),L=!1,B=!1;try{var K={get passive(){return L=!0},get once(){return B=L=!0}};A&&(window.addEventListener("test",K,K),window.removeEventListener("test",K,!0))}catch(e){}var _=function(e,t,n,r){if(r&&"boolean"!=typeof r&&!B){var a=r.once,o=r.capture,i=n;!B&&a&&(i=n.__once||function e(r){this.removeEventListener(t,e,o),n.call(this,r)},n.__once=i),e.addEventListener(t,i,L?r:o)}e.addEventListener(t,n,r)};var H=function(e,t,n,r){var a=r&&"boolean"!=typeof r?r.capture:r;e.removeEventListener(t,n,a),n.__once&&e.removeEventListener(t,n.__once,a)};var z=function(e,t,n,r){return _(e,t,n,r),function(){H(e,t,n,r)}};function V(e,t,n){void 0===n&&(n=5);var r=!1,a=setTimeout((function(){r||function(e){var t=document.createEvent("HTMLEvents");t.initEvent("transitionend",!0,!0),e.dispatchEvent(t)}(e)}),t+n),o=z(e,"transitionend",(function(){r=!0}),{once:!0});return function(){clearTimeout(a),o()}}function q(e,t,n,r){var a,o;null==n&&(a=F(e,"transitionDuration")||"",o=-1===a.indexOf("ms")?1e3:1,n=parseFloat(a)*o||0);var i=V(e,n,r),s=z(e,"transitionend",t);return function(){i(),s()}}var U=n(1),W=n.n(U),G=n(3),X=n.n(G),$=!1,Y=l.a.createContext(null),J=function(e){function t(t,n){var r;r=e.call(this,t,n)||this;var a,o=n&&!n.isMounting?t.enter:t.appear;return r.appearStatus=null,t.in?o?(a="exited",r.appearStatus="entering"):a="entered":a=t.unmountOnExit||t.mountOnEnter?"unmounted":"exited",r.state={status:a},r.nextCallback=null,r}v(t,e),t.getDerivedStateFromProps=function(e,t){return e.in&&"unmounted"===t.status?{status:"exited"}:null};var n=t.prototype;return n.componentDidMount=function(){this.updateStatus(!0,this.appearStatus)},n.componentDidUpdate=function(e){var t=null;if(e!==this.props){var n=this.state.status;this.props.in?"entering"!==n&&"entered"!==n&&(t="entering"):"entering"!==n&&"entered"!==n||(t="exiting")}this.updateStatus(!1,t)},n.componentWillUnmount=function(){this.cancelNextCallback()},n.getTimeouts=function(){var e,t,n,r=this.props.timeout;return e=t=n=r,null!=r&&"number"!=typeof r&&(e=r.exit,t=r.enter,n=void 0!==r.appear?r.appear:t),{exit:e,enter:t,appear:n}},n.updateStatus=function(e,t){void 0===e&&(e=!1),null!==t?(this.cancelNextCallback(),"entering"===t?this.performEnter(e):this.performExit()):this.props.unmountOnExit&&"exited"===this.state.status&&this.setState({status:"unmounted"})},n.performEnter=function(e){var t=this,n=this.props.enter,r=this.context?this.context.isMounting:e,a=this.props.nodeRef?[r]:[X.a.findDOMNode(this),r],o=a[0],i=a[1],s=this.getTimeouts(),l=r?s.appear:s.enter;!e&&!n||$?this.safeSetState({status:"entered"},(function(){t.props.onEntered(o)})):(this.props.onEnter(o,i),this.safeSetState({status:"entering"},(function(){t.props.onEntering(o,i),t.onTransitionEnd(l,(function(){t.safeSetState({status:"entered"},(function(){t.props.onEntered(o,i)}))}))})))},n.performExit=function(){var e=this,t=this.props.exit,n=this.getTimeouts(),r=this.props.nodeRef?void 0:X.a.findDOMNode(this);t&&!$?(this.props.onExit(r),this.safeSetState({status:"exiting"},(function(){e.props.onExiting(r),e.onTransitionEnd(n.exit,(function(){e.safeSetState({status:"exited"},(function(){e.props.onExited(r)}))}))}))):this.safeSetState({status:"exited"},(function(){e.props.onExited(r)}))},n.cancelNextCallback=function(){null!==this.nextCallback&&(this.nextCallback.cancel(),this.nextCallback=null)},n.safeSetState=function(e,t){t=this.setNextCallback(t),this.setState(e,t)},n.setNextCallback=function(e){var t=this,n=!0;return this.nextCallback=function(r){n&&(n=!1,t.nextCallback=null,e(r))},this.nextCallback.cancel=function(){n=!1},this.nextCallback},n.onTransitionEnd=function(e,t){this.setNextCallback(t);var n=this.props.nodeRef?this.props.nodeRef.current:X.a.findDOMNode(this),r=null==e&&!this.props.addEndListener;if(n&&!r){if(this.props.addEndListener){var a=this.props.nodeRef?[this.nextCallback]:[n,this.nextCallback],o=a[0],i=a[1];this.props.addEndListener(o,i)}null!=e&&setTimeout(this.nextCallback,e)}else setTimeout(this.nextCallback,0)},n.render=function(){var e=this.state.status;if("unmounted"===e)return null;var t=this.props,n=t.children,r=(t.in,t.mountOnEnter,t.unmountOnExit,t.appear,t.enter,t.exit,t.timeout,t.addEndListener,t.onEnter,t.onEntering,t.onEntered,t.onExit,t.onExiting,t.onExited,t.nodeRef,a(t,["children","in","mountOnEnter","unmountOnExit","appear","enter","exit","timeout","addEndListener","onEnter","onEntering","onEntered","onExit","onExiting","onExited","nodeRef"]));return l.a.createElement(Y.Provider,{value:null},"function"==typeof n?n(e,r):l.a.cloneElement(l.a.Children.only(n),r))},t}(l.a.Component);function Z(){}J.contextType=Y,J.propTypes={},J.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:Z,onEntering:Z,onEntered:Z,onExit:Z,onExiting:Z,onExited:Z},J.UNMOUNTED="unmounted",J.EXITED="exited",J.ENTERING="entering",J.ENTERED="entered",J.EXITING="exiting";var Q=J;var ee,te=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter((function(e){return null!=e})).reduce((function(e,t){if("function"!=typeof t)throw new Error("Invalid Argument Type, must only provide functions, undefined, or null.");return null===e?t:function(){for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];e.apply(this,r),t.apply(this,r)}}),null)};function ne(e){e.offsetHeight}var re={height:["marginTop","marginBottom"],width:["marginLeft","marginRight"]};function ae(e,t){var n=t["offset"+e[0].toUpperCase()+e.slice(1)],r=re[e];return n+parseInt(F(t,r[0]),10)+parseInt(F(t,r[1]),10)}var oe=((ee={}).exited="collapse",ee.exiting="collapsing",ee.entering="collapsing",ee.entered="collapse show",ee),ie={in:!1,timeout:300,mountOnEnter:!1,unmountOnExit:!1,appear:!1,getDimensionValue:ae},se=l.a.forwardRef((function(e,t){var n=e.onEnter,o=e.onEntering,c=e.onEntered,u=e.onExit,d=e.onExiting,f=e.className,p=e.children,m=e.dimension,v=void 0===m?"height":m,b=e.getDimensionValue,h=void 0===b?ae:b,g=a(e,["onEnter","onEntering","onEntered","onExit","onExiting","className","children","dimension","getDimensionValue"]),y="function"==typeof v?v():v,x=Object(s.useMemo)((function(){return te((function(e){e.style[y]="0"}),n)}),[y,n]),E=Object(s.useMemo)((function(){return te((function(e){var t="scroll"+y[0].toUpperCase()+y.slice(1);e.style[y]=e[t]+"px"}),o)}),[y,o]),w=Object(s.useMemo)((function(){return te((function(e){e.style[y]=null}),c)}),[y,c]),O=Object(s.useMemo)((function(){return te((function(e){e.style[y]=h(y,e)+"px",ne(e)}),u)}),[u,h,y]),N=Object(s.useMemo)((function(){return te((function(e){e.style[y]=null}),d)}),[y,d]);return l.a.createElement(Q,r({ref:t,addEndListener:q},g,{"aria-expanded":g.role?g.in:null,onEnter:x,onEntering:E,onEntered:w,onExit:O,onExiting:N}),(function(e,t){return l.a.cloneElement(p,r({},t,{className:i()(f,p.props.className,oe[e],"width"===y&&"width")}))}))}));se.defaultProps=ie;var le=se,ce=l.a.forwardRef((function(e,t){var n=e.children,o=e.eventKey,i=a(e,["children","eventKey"]),c=Object(s.useContext)(P);return l.a.createElement(N.Provider,{value:null},l.a.createElement(le,r({ref:t,in:c===o},i),l.a.createElement("div",null,l.a.Children.only(n))))}));ce.displayName="AccordionCollapse";var ue=ce,de=l.a.forwardRef((function(e,t){var n=m(e,{activeKey:"onSelect"}),o=n.as,s=void 0===o?"div":o,c=n.activeKey,u=n.bsPrefix,d=n.children,f=n.className,p=n.onSelect,v=a(n,["as","activeKey","bsPrefix","children","className","onSelect"]),b=i()(f,E(u,"accordion"));return l.a.createElement(P.Provider,{value:c||null},l.a.createElement(N.Provider,{value:p||null},l.a.createElement(s,r({ref:t},v,{className:b}),d)))}));de.displayName="Accordion",de.Toggle=k,de.Collapse=ue;var fe=de;var pe,me=function(e){var t=Object(s.useRef)(e);return Object(s.useEffect)((function(){t.current=e}),[e]),t};function ve(e){var t=me(e);return Object(s.useCallback)((function(){return t.current&&t.current.apply(t,arguments)}),[t])}var be=((pe={}).entering="show",pe.entered="show",pe),he=l.a.forwardRef((function(e,t){var n=e.className,o=e.children,c=a(e,["className","children"]),u=Object(s.useCallback)((function(e){ne(e),c.onEnter&&c.onEnter(e)}),[c]);return l.a.createElement(Q,r({ref:t,addEndListener:q},c,{onEnter:u}),(function(e,t){return l.a.cloneElement(o,r({},t,{className:i()("fade",n,o.props.className,be[e])}))}))}));he.defaultProps={in:!1,timeout:300,mountOnEnter:!1,unmountOnExit:!1,appear:!1},he.displayName="Fade";var ge=he,ye={label:W.a.string.isRequired,onClick:W.a.func},xe=l.a.forwardRef((function(e,t){var n=e.label,o=e.onClick,s=e.className,c=a(e,["label","onClick","className"]);return l.a.createElement("button",r({ref:t,type:"button",className:i()("close",s),onClick:o},c),l.a.createElement("span",{"aria-hidden":"true"},"×"),l.a.createElement("span",{className:"sr-only"},n))}));xe.displayName="CloseButton",xe.propTypes=ye,xe.defaultProps={label:"Close"};var Ee=xe,we=function(e){return l.a.forwardRef((function(t,n){return l.a.createElement("div",r({},t,{ref:n,className:i()(t.className,e)}))}))},Oe=/-(.)/g;var Ne=function(e){return e[0].toUpperCase()+(t=e,t.replace(Oe,(function(e,t){return t.toUpperCase()}))).slice(1);var t};function Ce(e,t){var n=void 0===t?{}:t,o=n.displayName,s=void 0===o?Ne(e):o,c=n.Component,u=n.defaultProps,d=l.a.forwardRef((function(t,n){var o=t.className,s=t.bsPrefix,u=t.as,d=void 0===u?c||"div":u,f=a(t,["className","bsPrefix","as"]),p=E(s,e);return l.a.createElement(d,r({ref:n,className:i()(o,p)},f))}));return d.defaultProps=u,d.displayName=s,d}function Pe(e){return!e||"#"===e.trim()}var je=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"a":n,i=e.disabled,s=e.onKeyDown,c=a(e,["as","disabled","onKeyDown"]),u=function(e){var t=c.href,n=c.onClick;(i||Pe(t))&&e.preventDefault(),i?e.stopPropagation():n&&n(e)};return Pe(c.href)&&(c.role=c.role||"button",c.href=c.href||"#"),i&&(c.tabIndex=-1,c["aria-disabled"]=!0),l.a.createElement(o,r({ref:t},c,{onClick:u,onKeyDown:te((function(e){" "===e.key&&(e.preventDefault(),u(e))}),s)}))}));je.displayName="SafeAnchor";var ke=je,Re=we("h4");Re.displayName="DivStyledAsH4";var Te=Ce("alert-heading",{Component:Re}),Se=Ce("alert-link",{Component:ke}),Me={show:!0,transition:ge,closeLabel:"Close alert"},Ie=l.a.forwardRef((function(e,t){var n=m(e,{show:"onClose"}),o=n.bsPrefix,s=n.show,c=n.closeLabel,u=n.className,d=n.children,f=n.variant,p=n.onClose,v=n.dismissible,b=n.transition,h=a(n,["bsPrefix","show","closeLabel","className","children","variant","onClose","dismissible","transition"]),g=E(o,"alert"),y=ve((function(e){p&&p(!1,e)})),x=!0===b?ge:b,w=l.a.createElement("div",r({role:"alert"},x?h:void 0,{ref:t,className:i()(u,g,f&&g+"-"+f,v&&g+"-dismissible")}),v&&l.a.createElement(Ee,{onClick:y,label:c}),d);return x?l.a.createElement(x,r({unmountOnExit:!0},h,{ref:void 0,in:s}),w):s?w:null}));Ie.displayName="Alert",Ie.defaultProps=Me,Ie.Link=Se,Ie.Heading=Te;var De=Ie,Fe=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.variant,s=e.pill,c=e.className,u=e.as,d=void 0===u?"span":u,f=a(e,["bsPrefix","variant","pill","className","as"]),p=E(n,"badge");return l.a.createElement(d,r({ref:t},f,{className:i()(c,p,s&&p+"-pill",o&&p+"-"+o)}))}));Fe.displayName="Badge",Fe.defaultProps={pill:!1};var Ae=Fe,Le=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.active,s=e.children,c=e.className,u=e.as,d=void 0===u?"li":u,f=e.linkAs,p=void 0===f?ke:f,m=e.linkProps,v=e.href,b=e.title,h=e.target,g=a(e,["bsPrefix","active","children","className","as","linkAs","linkProps","href","title","target"]),y=E(n,"breadcrumb-item");return l.a.createElement(d,r({ref:t},g,{className:i()(y,c,{active:o}),"aria-current":o?"page":void 0}),o?s:l.a.createElement(p,r({},m,{href:v,title:b,target:h}),s))}));Le.displayName="BreadcrumbItem",Le.defaultProps={active:!1,linkProps:{}};var Be=Le,Ke=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.listProps,c=e.children,u=e.label,d=e.as,f=void 0===d?"nav":d,p=a(e,["bsPrefix","className","listProps","children","label","as"]),m=E(n,"breadcrumb");return l.a.createElement(f,r({"aria-label":u,className:o,ref:t},p),l.a.createElement("ol",r({},s,{className:i()(m,null==s?void 0:s.className)}),c))}));Ke.displayName="Breadcrumb",Ke.defaultProps={label:"breadcrumb",listProps:{}},Ke.Item=Be;var _e=Ke,He=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.variant,s=e.size,c=e.active,u=e.className,d=e.block,f=e.type,p=e.as,m=a(e,["bsPrefix","variant","size","active","className","block","type","as"]),v=E(n,"btn"),b=i()(u,v,c&&"active",v+"-"+o,d&&v+"-block",s&&v+"-"+s);if(m.href)return l.a.createElement(ke,r({},m,{as:p,ref:t,className:i()(b,m.disabled&&"disabled")}));t&&(m.ref=t),f?m.type=f:p||(m.type="button");var h=p||"button";return l.a.createElement(h,r({},m,{className:b}))}));He.displayName="Button",He.defaultProps={variant:"primary",active:!1,disabled:!1};var ze=He,Ve=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.size,s=e.toggle,c=e.vertical,u=e.className,d=e.as,f=void 0===d?"div":d,p=a(e,["bsPrefix","size","toggle","vertical","className","as"]),m=E(n,"btn-group"),v=m;return c&&(v=m+"-vertical"),l.a.createElement(f,r({},p,{ref:t,className:i()(u,v,o&&m+"-"+o,s&&m+"-toggle")}))}));Ve.displayName="ButtonGroup",Ve.defaultProps={vertical:!1,toggle:!1,role:"group"};var qe=Ve,Ue=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=a(e,["bsPrefix","className"]),c=E(n,"btn-toolbar");return l.a.createElement("div",r({},s,{ref:t,className:i()(o,c)}))}));Ue.displayName="ButtonToolbar",Ue.defaultProps={role:"toolbar"};var We=Ue,Ge=l.a.createContext(null);Ge.displayName="CardContext";var Xe=Ge,$e=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.variant,c=e.as,u=void 0===c?"img":c,d=a(e,["bsPrefix","className","variant","as"]),f=E(n,"card-img");return l.a.createElement(u,r({ref:t,className:i()(s?f+"-"+s:f,o)},d))}));$e.displayName="CardImg",$e.defaultProps={variant:null};var Ye=$e,Je=we("h5"),Ze=we("h6"),Qe=Ce("card-body"),et=Ce("card-title",{Component:Je}),tt=Ce("card-subtitle",{Component:Ze}),nt=Ce("card-link",{Component:"a"}),rt=Ce("card-text",{Component:"p"}),at=Ce("card-header"),ot=Ce("card-footer"),it=Ce("card-img-overlay"),st=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.bg,u=e.text,d=e.border,f=e.body,p=e.children,m=e.as,v=void 0===m?"div":m,b=a(e,["bsPrefix","className","bg","text","border","body","children","as"]),h=E(n,"card"),g=Object(s.useMemo)((function(){return{cardHeaderBsPrefix:h+"-header"}}),[h]);return l.a.createElement(Xe.Provider,{value:g},l.a.createElement(v,r({ref:t},b,{className:i()(o,h,c&&"bg-"+c,u&&"text-"+u,d&&"border-"+d)}),f?l.a.createElement(Qe,null,p):p))}));st.displayName="Card",st.defaultProps={body:!1},st.Img=Ye,st.Title=et,st.Subtitle=tt,st.Body=Qe,st.Link=nt,st.Text=rt,st.Header=at,st.Footer=ot,st.ImgOverlay=it;var lt=st,ct=Ce("card-columns"),ut=Ce("card-deck"),dt=Ce("card-group");var ft=function(e,t){var n=Object(s.useRef)(!0);Object(s.useEffect)((function(){if(!n.current)return e();n.current=!1}),t)};function pt(){var e=Object(s.useRef)(!0),t=Object(s.useRef)((function(){return e.current}));return Object(s.useEffect)((function(){return function(){e.current=!1}}),[]),t.current}function mt(e){var t,n,r=(t=e,(n=Object(s.useRef)(t)).current=t,n);Object(s.useEffect)((function(){return function(){return r.current()}}),[])}var vt=Math.pow(2,31)-1;function bt(){var e=pt(),t=Object(s.useRef)();return mt((function(){return clearTimeout(t.current)})),Object(s.useMemo)((function(){var n=function(){return clearTimeout(t.current)};return{set:function(r,a){void 0===a&&(a=0),e()&&(n(),a<=vt?t.current=setTimeout(r,a):function e(t,n,r){var a=r-Date.now();t.current=a<=vt?setTimeout(n,a):setTimeout((function(){return e(t,n,r)}),vt)}(t,r,Date.now()+a))},clear:n}}),[])}var ht=Ce("carousel-caption"),gt=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"div":n,s=e.bsPrefix,c=e.children,u=e.className,d=a(e,["as","bsPrefix","children","className"]),f=i()(u,E(s,"carousel-item"));return l.a.createElement(o,r({ref:t},d,{className:f}),c)}));gt.displayName="CarouselItem";var yt=gt;function xt(e,t){var n=0;return l.a.Children.map(e,(function(e){return l.a.isValidElement(e)?t(e,n++):e}))}function Et(e,t){var n=0;l.a.Children.forEach(e,(function(e){l.a.isValidElement(e)&&t(e,n++)}))}var wt={bsPrefix:W.a.string,as:W.a.elementType,slide:W.a.bool,fade:W.a.bool,controls:W.a.bool,indicators:W.a.bool,activeIndex:W.a.number,onSelect:W.a.func,onSlide:W.a.func,onSlid:W.a.func,interval:W.a.number,keyboard:W.a.bool,pause:W.a.oneOf(["hover",!1]),wrap:W.a.bool,touch:W.a.bool,prevIcon:W.a.node,prevLabel:W.a.string,nextIcon:W.a.node,nextLabel:W.a.string},Ot={slide:!0,fade:!1,controls:!0,indicators:!0,defaultActiveIndex:0,interval:5e3,keyboard:!0,pause:"hover",wrap:!0,touch:!0,prevIcon:l.a.createElement("span",{"aria-hidden":"true",className:"carousel-control-prev-icon"}),prevLabel:"Previous",nextIcon:l.a.createElement("span",{"aria-hidden":"true",className:"carousel-control-next-icon"}),nextLabel:"Next"};function Nt(e,t){var n=m(e,{activeIndex:"onSelect"}),o=n.as,c=void 0===o?"div":o,u=n.bsPrefix,d=n.slide,f=n.fade,p=n.controls,v=n.indicators,b=n.activeIndex,h=n.onSelect,g=n.onSlide,y=n.onSlid,x=n.interval,w=n.keyboard,O=n.onKeyDown,N=n.pause,C=n.onMouseOver,P=n.onMouseOut,j=n.wrap,k=n.touch,R=n.onTouchStart,T=n.onTouchMove,S=n.onTouchEnd,M=n.prevIcon,I=n.prevLabel,D=n.nextIcon,F=n.nextLabel,A=n.className,L=n.children,B=a(n,["as","bsPrefix","slide","fade","controls","indicators","activeIndex","onSelect","onSlide","onSlid","interval","keyboard","onKeyDown","pause","onMouseOver","onMouseOut","wrap","touch","onTouchStart","onTouchMove","onTouchEnd","prevIcon","prevLabel","nextIcon","nextLabel","className","children"]),K=E(u,"carousel"),_=Object(s.useRef)(null),H=Object(s.useState)("next"),z=H[0],V=H[1],U=Object(s.useState)(!1),W=U[0],G=U[1],X=Object(s.useState)(b||0),$=X[0],Y=X[1];W||b===$||(_.current?V(_.current):V((b||0)>$?"next":"prev"),d&&G(!0),Y(b||0)),Object(s.useEffect)((function(){_.current&&(_.current=null)}));var J,Z=0;Et(L,(function(e,t){++Z,t===b&&(J=e.props.interval)}));var ee=me(J),te=Object(s.useCallback)((function(e){if(!W){var t=$-1;if(t<0){if(!j)return;t=Z-1}_.current="prev",h&&h(t,e)}}),[W,$,h,j,Z]),re=ve((function(e){if(!W){var t=$+1;if(t>=Z){if(!j)return;t=0}_.current="next",h&&h(t,e)}})),ae=Object(s.useRef)();Object(s.useImperativeHandle)(t,(function(){return{element:ae.current,prev:te,next:re}}));var oe=ve((function(){!document.hidden&&function(e){if(!(e&&e.style&&e.parentNode&&e.parentNode.style))return!1;var t=getComputedStyle(e);return"none"!==t.display&&"hidden"!==t.visibility&&"none"!==getComputedStyle(e.parentNode).display}(ae.current)&&re()})),ie="next"===z?"left":"right";ft((function(){d||(g&&g($,ie),y&&y($,ie))}),[$]);var se=K+"-item-"+z,le=K+"-item-"+ie,ce=Object(s.useCallback)((function(e){ne(e),g&&g($,ie)}),[g,$,ie]),ue=Object(s.useCallback)((function(){G(!1),y&&y($,ie)}),[y,$,ie]),de=Object(s.useCallback)((function(e){if(w&&!/input|textarea/i.test(e.target.tagName))switch(e.key){case"ArrowLeft":return e.preventDefault(),void te(e);case"ArrowRight":return e.preventDefault(),void re(e)}O&&O(e)}),[w,O,te,re]),fe=Object(s.useState)(!1),pe=fe[0],be=fe[1],he=Object(s.useCallback)((function(e){"hover"===N&&be(!0),C&&C(e)}),[N,C]),ge=Object(s.useCallback)((function(e){be(!1),P&&P(e)}),[P]),ye=Object(s.useRef)(0),xe=Object(s.useRef)(0),Ee=Object(s.useState)(!1),we=Ee[0],Oe=Ee[1],Ne=bt(),Ce=Object(s.useCallback)((function(e){ye.current=e.touches[0].clientX,xe.current=0,k&&Oe(!0),R&&R(e)}),[k,R]),Pe=Object(s.useCallback)((function(e){e.touches&&e.touches.length>1?xe.current=0:xe.current=e.touches[0].clientX-ye.current,T&&T(e)}),[T]),je=Object(s.useCallback)((function(e){if(k){var t=xe.current;if(Math.abs(t)<=40)return;t>0?te(e):re(e)}Ne.set((function(){Oe(!1)}),x||void 0),S&&S(e)}),[k,te,re,Ne,x,S]),Re=null!=x&&!pe&&!we&&!W,Te=Object(s.useRef)();Object(s.useEffect)((function(){var e,t;if(Re)return Te.current=window.setInterval(document.visibilityState?oe:re,null!=(e=null!=(t=ee.current)?t:x)?e:void 0),function(){null!==Te.current&&clearInterval(Te.current)}}),[Re,re,ee,x,oe]);var Se=Object(s.useMemo)((function(){return v&&Array.from({length:Z},(function(e,t){return function(e){h&&h(t,e)}}))}),[v,Z,h]);return l.a.createElement(c,r({ref:ae},B,{onKeyDown:de,onMouseOver:he,onMouseOut:ge,onTouchStart:Ce,onTouchMove:Pe,onTouchEnd:je,className:i()(A,K,d&&"slide",f&&K+"-fade")}),v&&l.a.createElement("ol",{className:K+"-indicators"},xt(L,(function(e,t){return l.a.createElement("li",{key:t,className:t===$?"active":void 0,onClick:Se?Se[t]:void 0})}))),l.a.createElement("div",{className:K+"-inner"},xt(L,(function(e,t){var n=t===$;return d?l.a.createElement(Q,{in:n,onEnter:n?ce:void 0,onEntered:n?ue:void 0,addEndListener:q},(function(t){return l.a.cloneElement(e,{className:i()(e.props.className,n&&"entered"!==t&&se,("entered"===t||"exiting"===t)&&"active",("entering"===t||"exiting"===t)&&le)})})):l.a.cloneElement(e,{className:i()(e.props.className,n&&"active")})}))),p&&l.a.createElement(l.a.Fragment,null,(j||0!==b)&&l.a.createElement(ke,{className:K+"-control-prev",onClick:te},M,I&&l.a.createElement("span",{className:"sr-only"},I)),(j||b!==Z-1)&&l.a.createElement(ke,{className:K+"-control-next",onClick:re},D,F&&l.a.createElement("span",{className:"sr-only"},F))))}var Ct=l.a.forwardRef(Nt);Ct.displayName="Carousel",Ct.propTypes=wt,Ct.defaultProps=Ot,Ct.Caption=ht,Ct.Item=yt;var Pt=Ct,jt=["xl","lg","md","sm","xs"],kt=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.as,c=void 0===s?"div":s,u=a(e,["bsPrefix","className","as"]),d=E(n,"col"),f=[],p=[];return jt.forEach((function(e){var t,n,r,a=u[e];if(delete u[e],"object"==typeof a&&null!=a){var o=a.span;t=void 0===o||o,n=a.offset,r=a.order}else t=a;var i="xs"!==e?"-"+e:"";t&&f.push(!0===t?""+d+i:""+d+i+"-"+t),null!=r&&p.push("order"+i+"-"+r),null!=n&&p.push("offset"+i+"-"+n)})),f.length||f.push(d),l.a.createElement(c,r({},u,{ref:t,className:i.a.apply(void 0,[o].concat(f,p))}))}));kt.displayName="Col";var Rt,Tt=kt;var St=Function.prototype.bind.call(Function.prototype.call,[].slice);function Mt(e,t){return St(e.querySelectorAll(t))}function It(e){var t=Object(s.useRef)(null);return Object(s.useEffect)((function(){t.current=e})),t.current}function Dt(){return Object(s.useState)(null)}function Ft(){return Object(s.useReducer)((function(e){return!e}),!1)[1]}var At=l.a.createContext(null);var Lt=function(e){var t=pt();return[e[0],Object(s.useCallback)((function(n){if(t())return e[1](n)}),[t,e[1]])]};function Bt(e){return e.split("-")[0]}function Kt(e){return{x:e.offsetLeft,y:e.offsetTop,width:e.offsetWidth,height:e.offsetHeight}}function _t(e,t){var n=Boolean(t.getRootNode&&t.getRootNode().host);if(e.contains(t))return!0;if(n){var r=t;do{if(r&&e.isSameNode(r))return!0;r=r.parentNode||r.host}while(r)}return!1}function Ht(e){if("[object Window]"!==e.toString()){var t=e.ownerDocument;return t?t.defaultView:window}return e}function zt(e){return e?(e.nodeName||"").toLowerCase():null}function Vt(e){return Ht(e).getComputedStyle(e)}function qt(e){return e instanceof Ht(e).Element||e instanceof Element}function Ut(e){return e instanceof Ht(e).HTMLElement||e instanceof HTMLElement}function Wt(e){return["table","td","th"].indexOf(zt(e))>=0}function Gt(e){return(qt(e)?e.ownerDocument:e.document).documentElement}function Xt(e){return"html"===zt(e)?e:e.assignedSlot||e.parentNode||e.host||Gt(e)}function $t(e){if(!Ut(e)||"fixed"===Vt(e).position)return null;var t=e.offsetParent;if(t){var n=Gt(t);if("body"===zt(t)&&"static"===Vt(t).position&&"static"!==Vt(n).position)return n}return t}function Yt(e){for(var t=Ht(e),n=$t(e);n&&Wt(n)&&"static"===Vt(n).position;)n=$t(n);return n&&"body"===zt(n)&&"static"===Vt(n).position?t:n||function(e){for(var t=Xt(e);Ut(t)&&["html","body"].indexOf(zt(t))<0;){var n=Vt(t);if("none"!==n.transform||"none"!==n.perspective||n.willChange&&"auto"!==n.willChange)return t;t=t.parentNode}return null}(e)||t}function Jt(e){return["top","bottom"].indexOf(e)>=0?"x":"y"}function Zt(e,t,n){return Math.max(e,Math.min(t,n))}function Qt(e){return Object.assign(Object.assign({},{top:0,right:0,bottom:0,left:0}),e)}function en(e,t){return t.reduce((function(t,n){return t[n]=e,t}),{})}var tn="top",nn="bottom",rn="right",an="left",on=[tn,nn,rn,an],sn=on.reduce((function(e,t){return e.concat([t+"-start",t+"-end"])}),[]),ln=[].concat(on,["auto"]).reduce((function(e,t){return e.concat([t,t+"-start",t+"-end"])}),[]),cn=["beforeRead","read","afterRead","beforeMain","main","afterMain","beforeWrite","write","afterWrite"];var un={name:"arrow",enabled:!0,phase:"main",fn:function(e){var t,n=e.state,r=e.name,a=n.elements.arrow,o=n.modifiersData.popperOffsets,i=Bt(n.placement),s=Jt(i),l=[an,rn].indexOf(i)>=0?"height":"width";if(a&&o){var c=n.modifiersData[r+"#persistent"].padding,u=Kt(a),d="y"===s?tn:an,f="y"===s?nn:rn,p=n.rects.reference[l]+n.rects.reference[s]-o[s]-n.rects.popper[l],m=o[s]-n.rects.reference[s],v=Yt(a),b=v?"y"===s?v.clientHeight||0:v.clientWidth||0:0,h=p/2-m/2,g=c[d],y=b-u[l]-c[f],x=b/2-u[l]/2+h,E=Zt(g,x,y),w=s;n.modifiersData[r]=((t={})[w]=E,t.centerOffset=E-x,t)}},effect:function(e){var t=e.state,n=e.options,r=e.name,a=n.element,o=void 0===a?"[data-popper-arrow]":a,i=n.padding,s=void 0===i?0:i;null!=o&&("string"!=typeof o||(o=t.elements.popper.querySelector(o)))&&_t(t.elements.popper,o)&&(t.elements.arrow=o,t.modifiersData[r+"#persistent"]={padding:Qt("number"!=typeof s?s:en(s,on))})},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},dn={top:"auto",right:"auto",bottom:"auto",left:"auto"};function fn(e){var t,n=e.popper,r=e.popperRect,a=e.placement,o=e.offsets,i=e.position,s=e.gpuAcceleration,l=e.adaptive,c=function(e){var t=e.x,n=e.y,r=window.devicePixelRatio||1;return{x:Math.round(t*r)/r||0,y:Math.round(n*r)/r||0}}(o),u=c.x,d=c.y,f=o.hasOwnProperty("x"),p=o.hasOwnProperty("y"),m=an,v=tn,b=window;if(l){var h=Yt(n);h===Ht(n)&&(h=Gt(n)),a===tn&&(v=nn,d-=h.clientHeight-r.height,d*=s?1:-1),a===an&&(m=rn,u-=h.clientWidth-r.width,u*=s?1:-1)}var g,y=Object.assign({position:i},l&&dn);return s?Object.assign(Object.assign({},y),{},((g={})[v]=p?"0":"",g[m]=f?"0":"",g.transform=(b.devicePixelRatio||1)<2?"translate("+u+"px, "+d+"px)":"translate3d("+u+"px, "+d+"px, 0)",g)):Object.assign(Object.assign({},y),{},((t={})[v]=p?d+"px":"",t[m]=f?u+"px":"",t.transform="",t))}var pn={name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function(e){var t=e.state,n=e.options,r=n.gpuAcceleration,a=void 0===r||r,o=n.adaptive,i=void 0===o||o,s={placement:Bt(t.placement),popper:t.elements.popper,popperRect:t.rects.popper,gpuAcceleration:a};null!=t.modifiersData.popperOffsets&&(t.styles.popper=Object.assign(Object.assign({},t.styles.popper),fn(Object.assign(Object.assign({},s),{},{offsets:t.modifiersData.popperOffsets,position:t.options.strategy,adaptive:i})))),null!=t.modifiersData.arrow&&(t.styles.arrow=Object.assign(Object.assign({},t.styles.arrow),fn(Object.assign(Object.assign({},s),{},{offsets:t.modifiersData.arrow,position:"absolute",adaptive:!1})))),t.attributes.popper=Object.assign(Object.assign({},t.attributes.popper),{},{"data-popper-placement":t.placement})},data:{}},mn={passive:!0};var vn={name:"eventListeners",enabled:!0,phase:"write",fn:function(){},effect:function(e){var t=e.state,n=e.instance,r=e.options,a=r.scroll,o=void 0===a||a,i=r.resize,s=void 0===i||i,l=Ht(t.elements.popper),c=[].concat(t.scrollParents.reference,t.scrollParents.popper);return o&&c.forEach((function(e){e.addEventListener("scroll",n.update,mn)})),s&&l.addEventListener("resize",n.update,mn),function(){o&&c.forEach((function(e){e.removeEventListener("scroll",n.update,mn)})),s&&l.removeEventListener("resize",n.update,mn)}},data:{}},bn={left:"right",right:"left",bottom:"top",top:"bottom"};function hn(e){return e.replace(/left|right|bottom|top/g,(function(e){return bn[e]}))}var gn={start:"end",end:"start"};function yn(e){return e.replace(/start|end/g,(function(e){return gn[e]}))}function xn(e){var t=e.getBoundingClientRect();return{width:t.width,height:t.height,top:t.top,right:t.right,bottom:t.bottom,left:t.left,x:t.left,y:t.top}}function En(e){var t=Ht(e);return{scrollLeft:t.pageXOffset,scrollTop:t.pageYOffset}}function wn(e){return xn(Gt(e)).left+En(e).scrollLeft}function On(e){var t=Vt(e),n=t.overflow,r=t.overflowX,a=t.overflowY;return/auto|scroll|overlay|hidden/.test(n+a+r)}function Nn(e,t){void 0===t&&(t=[]);var n=function e(t){return["html","body","#document"].indexOf(zt(t))>=0?t.ownerDocument.body:Ut(t)&&On(t)?t:e(Xt(t))}(e),r="body"===zt(n),a=Ht(n),o=r?[a].concat(a.visualViewport||[],On(n)?n:[]):n,i=t.concat(o);return r?i:i.concat(Nn(Xt(o)))}function Cn(e){return Object.assign(Object.assign({},e),{},{left:e.x,top:e.y,right:e.x+e.width,bottom:e.y+e.height})}function Pn(e,t){return"viewport"===t?Cn(function(e){var t=Ht(e),n=Gt(e),r=t.visualViewport,a=n.clientWidth,o=n.clientHeight,i=0,s=0;return r&&(a=r.width,o=r.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(i=r.offsetLeft,s=r.offsetTop)),{width:a,height:o,x:i+wn(e),y:s}}(e)):Ut(t)?function(e){var t=xn(e);return t.top=t.top+e.clientTop,t.left=t.left+e.clientLeft,t.bottom=t.top+e.clientHeight,t.right=t.left+e.clientWidth,t.width=e.clientWidth,t.height=e.clientHeight,t.x=t.left,t.y=t.top,t}(t):Cn(function(e){var t=Gt(e),n=En(e),r=e.ownerDocument.body,a=Math.max(t.scrollWidth,t.clientWidth,r?r.scrollWidth:0,r?r.clientWidth:0),o=Math.max(t.scrollHeight,t.clientHeight,r?r.scrollHeight:0,r?r.clientHeight:0),i=-n.scrollLeft+wn(e),s=-n.scrollTop;return"rtl"===Vt(r||t).direction&&(i+=Math.max(t.clientWidth,r?r.clientWidth:0)-a),{width:a,height:o,x:i,y:s}}(Gt(e)))}function jn(e,t,n){var r="clippingParents"===t?function(e){var t=Nn(Xt(e)),n=["absolute","fixed"].indexOf(Vt(e).position)>=0&&Ut(e)?Yt(e):e;return qt(n)?t.filter((function(e){return qt(e)&&_t(e,n)&&"body"!==zt(e)})):[]}(e):[].concat(t),a=[].concat(r,[n]),o=a[0],i=a.reduce((function(t,n){var r=Pn(e,n);return t.top=Math.max(r.top,t.top),t.right=Math.min(r.right,t.right),t.bottom=Math.min(r.bottom,t.bottom),t.left=Math.max(r.left,t.left),t}),Pn(e,o));return i.width=i.right-i.left,i.height=i.bottom-i.top,i.x=i.left,i.y=i.top,i}function kn(e){return e.split("-")[1]}function Rn(e){var t,n=e.reference,r=e.element,a=e.placement,o=a?Bt(a):null,i=a?kn(a):null,s=n.x+n.width/2-r.width/2,l=n.y+n.height/2-r.height/2;switch(o){case tn:t={x:s,y:n.y-r.height};break;case nn:t={x:s,y:n.y+n.height};break;case rn:t={x:n.x+n.width,y:l};break;case an:t={x:n.x-r.width,y:l};break;default:t={x:n.x,y:n.y}}var c=o?Jt(o):null;if(null!=c){var u="y"===c?"height":"width";switch(i){case"start":t[c]=Math.floor(t[c])-Math.floor(n[u]/2-r[u]/2);break;case"end":t[c]=Math.floor(t[c])+Math.ceil(n[u]/2-r[u]/2)}}return t}function Tn(e,t){void 0===t&&(t={});var n=t,r=n.placement,a=void 0===r?e.placement:r,o=n.boundary,i=void 0===o?"clippingParents":o,s=n.rootBoundary,l=void 0===s?"viewport":s,c=n.elementContext,u=void 0===c?"popper":c,d=n.altBoundary,f=void 0!==d&&d,p=n.padding,m=void 0===p?0:p,v=Qt("number"!=typeof m?m:en(m,on)),b="popper"===u?"reference":"popper",h=e.elements.reference,g=e.rects.popper,y=e.elements[f?b:u],x=jn(qt(y)?y:y.contextElement||Gt(e.elements.popper),i,l),E=xn(h),w=Rn({reference:E,element:g,strategy:"absolute",placement:a}),O=Cn(Object.assign(Object.assign({},g),w)),N="popper"===u?O:E,C={top:x.top-N.top+v.top,bottom:N.bottom-x.bottom+v.bottom,left:x.left-N.left+v.left,right:N.right-x.right+v.right},P=e.modifiersData.offset;if("popper"===u&&P){var j=P[a];Object.keys(C).forEach((function(e){var t=[rn,nn].indexOf(e)>=0?1:-1,n=[tn,nn].indexOf(e)>=0?"y":"x";C[e]+=j[n]*t}))}return C}var Sn={name:"flip",enabled:!0,phase:"main",fn:function(e){var t=e.state,n=e.options,r=e.name;if(!t.modifiersData[r]._skip){for(var a=n.mainAxis,o=void 0===a||a,i=n.altAxis,s=void 0===i||i,l=n.fallbackPlacements,c=n.padding,u=n.boundary,d=n.rootBoundary,f=n.altBoundary,p=n.flipVariations,m=void 0===p||p,v=n.allowedAutoPlacements,b=t.options.placement,h=Bt(b),g=l||(h===b||!m?[hn(b)]:function(e){if("auto"===Bt(e))return[];var t=hn(e);return[yn(e),t,yn(t)]}(b)),y=[b].concat(g).reduce((function(e,n){return e.concat("auto"===Bt(n)?function(e,t){void 0===t&&(t={});var n=t,r=n.placement,a=n.boundary,o=n.rootBoundary,i=n.padding,s=n.flipVariations,l=n.allowedAutoPlacements,c=void 0===l?ln:l,u=kn(r),d=u?s?sn:sn.filter((function(e){return kn(e)===u})):on,f=d.filter((function(e){return c.indexOf(e)>=0}));0===f.length&&(f=d);var p=f.reduce((function(t,n){return t[n]=Tn(e,{placement:n,boundary:a,rootBoundary:o,padding:i})[Bt(n)],t}),{});return Object.keys(p).sort((function(e,t){return p[e]-p[t]}))}(t,{placement:n,boundary:u,rootBoundary:d,padding:c,flipVariations:m,allowedAutoPlacements:v}):n)}),[]),x=t.rects.reference,E=t.rects.popper,w=new Map,O=!0,N=y[0],C=0;C<y.length;C++){var P=y[C],j=Bt(P),k="start"===kn(P),R=[tn,nn].indexOf(j)>=0,T=R?"width":"height",S=Tn(t,{placement:P,boundary:u,rootBoundary:d,altBoundary:f,padding:c}),M=R?k?rn:an:k?nn:tn;x[T]>E[T]&&(M=hn(M));var I=hn(M),D=[];if(o&&D.push(S[j]<=0),s&&D.push(S[M]<=0,S[I]<=0),D.every((function(e){return e}))){N=P,O=!1;break}w.set(P,D)}if(O)for(var F=function(e){var t=y.find((function(t){var n=w.get(t);if(n)return n.slice(0,e).every((function(e){return e}))}));if(t)return N=t,"break"},A=m?3:1;A>0;A--){if("break"===F(A))break}t.placement!==N&&(t.modifiersData[r]._skip=!0,t.placement=N,t.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}};function Mn(e,t,n){return void 0===n&&(n={x:0,y:0}),{top:e.top-t.height-n.y,right:e.right-t.width+n.x,bottom:e.bottom-t.height+n.y,left:e.left-t.width-n.x}}function In(e){return[tn,rn,nn,an].some((function(t){return e[t]>=0}))}var Dn={name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function(e){var t=e.state,n=e.name,r=t.rects.reference,a=t.rects.popper,o=t.modifiersData.preventOverflow,i=Tn(t,{elementContext:"reference"}),s=Tn(t,{altBoundary:!0}),l=Mn(i,r),c=Mn(s,a,o),u=In(l),d=In(c);t.modifiersData[n]={referenceClippingOffsets:l,popperEscapeOffsets:c,isReferenceHidden:u,hasPopperEscaped:d},t.attributes.popper=Object.assign(Object.assign({},t.attributes.popper),{},{"data-popper-reference-hidden":u,"data-popper-escaped":d})}};var Fn={name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function(e){var t=e.state,n=e.options,r=e.name,a=n.offset,o=void 0===a?[0,0]:a,i=ln.reduce((function(e,n){return e[n]=function(e,t,n){var r=Bt(e),a=[an,tn].indexOf(r)>=0?-1:1,o="function"==typeof n?n(Object.assign(Object.assign({},t),{},{placement:e})):n,i=o[0],s=o[1];return i=i||0,s=(s||0)*a,[an,rn].indexOf(r)>=0?{x:s,y:i}:{x:i,y:s}}(n,t.rects,o),e}),{}),s=i[t.placement],l=s.x,c=s.y;null!=t.modifiersData.popperOffsets&&(t.modifiersData.popperOffsets.x+=l,t.modifiersData.popperOffsets.y+=c),t.modifiersData[r]=i}};var An={name:"popperOffsets",enabled:!0,phase:"read",fn:function(e){var t=e.state,n=e.name;t.modifiersData[n]=Rn({reference:t.rects.reference,element:t.rects.popper,strategy:"absolute",placement:t.placement})},data:{}};var Ln={name:"preventOverflow",enabled:!0,phase:"main",fn:function(e){var t=e.state,n=e.options,r=e.name,a=n.mainAxis,o=void 0===a||a,i=n.altAxis,s=void 0!==i&&i,l=n.boundary,c=n.rootBoundary,u=n.altBoundary,d=n.padding,f=n.tether,p=void 0===f||f,m=n.tetherOffset,v=void 0===m?0:m,b=Tn(t,{boundary:l,rootBoundary:c,padding:d,altBoundary:u}),h=Bt(t.placement),g=kn(t.placement),y=!g,x=Jt(h),E="x"===x?"y":"x",w=t.modifiersData.popperOffsets,O=t.rects.reference,N=t.rects.popper,C="function"==typeof v?v(Object.assign(Object.assign({},t.rects),{},{placement:t.placement})):v,P={x:0,y:0};if(w){if(o){var j="y"===x?tn:an,k="y"===x?nn:rn,R="y"===x?"height":"width",T=w[x],S=w[x]+b[j],M=w[x]-b[k],I=p?-N[R]/2:0,D="start"===g?O[R]:N[R],F="start"===g?-N[R]:-O[R],A=t.elements.arrow,L=p&&A?Kt(A):{width:0,height:0},B=t.modifiersData["arrow#persistent"]?t.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},K=B[j],_=B[k],H=Zt(0,O[R],L[R]),z=y?O[R]/2-I-H-K-C:D-H-K-C,V=y?-O[R]/2+I+H+_+C:F+H+_+C,q=t.elements.arrow&&Yt(t.elements.arrow),U=q?"y"===x?q.clientTop||0:q.clientLeft||0:0,W=t.modifiersData.offset?t.modifiersData.offset[t.placement][x]:0,G=w[x]+z-W-U,X=w[x]+V-W,$=Zt(p?Math.min(S,G):S,T,p?Math.max(M,X):M);w[x]=$,P[x]=$-T}if(s){var Y="x"===x?tn:an,J="x"===x?nn:rn,Z=w[E],Q=Zt(Z+b[Y],Z,Z-b[J]);w[E]=Q,P[E]=Q-Z}t.modifiersData[r]=P}},requiresIfExists:["offset"]};function Bn(e,t,n){void 0===n&&(n=!1);var r,a,o=Gt(t),i=xn(e),s=Ut(t),l={scrollLeft:0,scrollTop:0},c={x:0,y:0};return(s||!s&&!n)&&(("body"!==zt(t)||On(o))&&(l=(r=t)!==Ht(r)&&Ut(r)?{scrollLeft:(a=r).scrollLeft,scrollTop:a.scrollTop}:En(r)),Ut(t)?((c=xn(t)).x+=t.clientLeft,c.y+=t.clientTop):o&&(c.x=wn(o))),{x:i.left+l.scrollLeft-c.x,y:i.top+l.scrollTop-c.y,width:i.width,height:i.height}}function Kn(e){var t=new Map,n=new Set,r=[];return e.forEach((function(e){t.set(e.name,e)})),e.forEach((function(e){n.has(e.name)||function e(a){n.add(a.name),[].concat(a.requires||[],a.requiresIfExists||[]).forEach((function(r){if(!n.has(r)){var a=t.get(r);a&&e(a)}})),r.push(a)}(e)})),r}var _n={placement:"bottom",modifiers:[],strategy:"absolute"};function Hn(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return!t.some((function(e){return!(e&&"function"==typeof e.getBoundingClientRect)}))}function zn(e){void 0===e&&(e={});var t=e,n=t.defaultModifiers,r=void 0===n?[]:n,a=t.defaultOptions,o=void 0===a?_n:a;return function(e,t,n){void 0===n&&(n=o);var a,i,s={placement:"bottom",orderedModifiers:[],options:Object.assign(Object.assign({},_n),o),modifiersData:{},elements:{reference:e,popper:t},attributes:{},styles:{}},l=[],c=!1,u={state:s,setOptions:function(n){d(),s.options=Object.assign(Object.assign(Object.assign({},o),s.options),n),s.scrollParents={reference:qt(e)?Nn(e):e.contextElement?Nn(e.contextElement):[],popper:Nn(t)};var a=function(e){var t=Kn(e);return cn.reduce((function(e,n){return e.concat(t.filter((function(e){return e.phase===n})))}),[])}(function(e){var t=e.reduce((function(e,t){var n=e[t.name];return e[t.name]=n?Object.assign(Object.assign(Object.assign({},n),t),{},{options:Object.assign(Object.assign({},n.options),t.options),data:Object.assign(Object.assign({},n.data),t.data)}):t,e}),{});return Object.keys(t).map((function(e){return t[e]}))}([].concat(r,s.options.modifiers)));return s.orderedModifiers=a.filter((function(e){return e.enabled})),s.orderedModifiers.forEach((function(e){var t=e.name,n=e.options,r=void 0===n?{}:n,a=e.effect;if("function"==typeof a){var o=a({state:s,name:t,instance:u,options:r});l.push(o||function(){})}})),u.update()},forceUpdate:function(){if(!c){var e=s.elements,t=e.reference,n=e.popper;if(Hn(t,n)){s.rects={reference:Bn(t,Yt(n),"fixed"===s.options.strategy),popper:Kt(n)},s.reset=!1,s.placement=s.options.placement,s.orderedModifiers.forEach((function(e){return s.modifiersData[e.name]=Object.assign({},e.data)}));for(var r=0;r<s.orderedModifiers.length;r++)if(!0!==s.reset){var a=s.orderedModifiers[r],o=a.fn,i=a.options,l=void 0===i?{}:i,d=a.name;"function"==typeof o&&(s=o({state:s,options:l,name:d,instance:u})||s)}else s.reset=!1,r=-1}}},update:(a=function(){return new Promise((function(e){u.forceUpdate(),e(s)}))},function(){return i||(i=new Promise((function(e){Promise.resolve().then((function(){i=void 0,e(a())}))}))),i}),destroy:function(){d(),c=!0}};if(!Hn(e,t))return u;function d(){l.forEach((function(e){return e()})),l=[]}return u.setOptions(n).then((function(e){!c&&n.onFirstUpdate&&n.onFirstUpdate(e)})),u}}var Vn=zn({defaultModifiers:[Dn,An,pn,vn,Fn,Sn,Ln,un]}),qn=function(e){return{position:e,top:"0",left:"0",opacity:"0",pointerEvents:"none"}},Un={name:"applyStyles",enabled:!1},Wn={name:"ariaDescribedBy",enabled:!0,phase:"afterWrite",effect:function(e){var t=e.state;return function(){var e=t.elements,n=e.reference,r=e.popper;if("removeAttribute"in n){var a=(n.getAttribute("aria-describedby")||"").split(",").filter((function(e){return e.trim()!==r.id}));a.length?n.setAttribute("aria-describedby",a.join(",")):n.removeAttribute("aria-describedby")}}},fn:function(e){var t,n=e.state.elements,r=n.popper,a=n.reference,o=null==(t=r.getAttribute("role"))?void 0:t.toLowerCase();if(r.id&&"tooltip"===o&&"setAttribute"in a){var i=a.getAttribute("aria-describedby");a.setAttribute("aria-describedby",i?i+","+r.id:r.id)}}},Gn=[];var Xn=function(e,t,n){var o=void 0===n?{}:n,i=o.enabled,l=void 0===i||i,c=o.placement,u=void 0===c?"bottom":c,d=o.strategy,f=void 0===d?"absolute":d,p=o.modifiers,m=void 0===p?Gn:p,v=a(o,["enabled","placement","strategy","modifiers"]),b=Object(s.useRef)(),h=Object(s.useCallback)((function(){var e;null==(e=b.current)||e.update()}),[]),g=Object(s.useCallback)((function(){var e;null==(e=b.current)||e.forceUpdate()}),[]),y=Lt(Object(s.useState)({placement:u,update:h,forceUpdate:g,attributes:{},styles:{popper:qn(f),arrow:{}}})),x=y[0],E=y[1],w=Object(s.useMemo)((function(){return{name:"updateStateModifier",enabled:!0,phase:"write",requires:["computeStyles"],fn:function(e){var t=e.state,n={},r={};Object.keys(t.elements).forEach((function(e){n[e]=t.styles[e],r[e]=t.attributes[e]})),E({state:t,styles:n,attributes:r,update:h,forceUpdate:g,placement:t.placement})}}}),[h,g,E]);return Object(s.useEffect)((function(){b.current&&l&&b.current.setOptions({placement:u,strategy:f,modifiers:[].concat(m,[w,Un])})}),[f,u,w,l]),Object(s.useEffect)((function(){if(l&&null!=e&&null!=t)return b.current=Vn(e,t,r({},v,{placement:u,strategy:f,modifiers:[].concat(m,[Wn,w])})),function(){null!=b.current&&(b.current.destroy(),b.current=void 0,E((function(e){return r({},e,{attributes:{},styles:{popper:qn(f)}})})))}}),[l,e,t]),x};function $n(e,t){return e.contains?e.contains(t):e.compareDocumentPosition?e===t||!!(16&e.compareDocumentPosition(t)):void 0}var Yn=n(4),Jn=n.n(Yn);function Zn(e){return e&&"setState"in e?X.a.findDOMNode(e):null!=e?e:null}var Qn=function(){};var er=function(e){return e&&("current"in e?e.current:e)};var tr=function(e,t,n){var r=void 0===n?{}:n,a=r.disabled,o=r.clickTrigger,i=void 0===o?"click":o,l=Object(s.useRef)(!1),c=t||Qn,u=Object(s.useCallback)((function(t){var n,r=er(e);Jn()(!!r,"RootClose captured a close event but does not have a ref to compare it to. useRootClose(), should be passed a ref that resolves to a DOM node"),l.current=!(r&&(n=t,!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey))&&function(e){return 0===e.button}(t)&&!$n(r,t.target))}),[e]),d=ve((function(e){l.current||c(e)})),f=ve((function(e){27===e.keyCode&&c(e)}));Object(s.useEffect)((function(){if(!a&&null!=e){var t=R(Zn(er(e))),n=z(t,i,u,!0),r=z(t,i,d),o=z(t,"keyup",f),s=[];return"ontouchstart"in t.documentElement&&(s=[].slice.call(t.body.children).map((function(e){return z(e,"mousemove",Qn)}))),function(){n(),r(),o(),s.forEach((function(e){return e()}))}}}),[e,a,i,u,d,f])};function nr(e){return void 0===e&&(e={}),Array.isArray(e)?e:Object.keys(e).map((function(t){return e[t].name=t,e[t]}))}function rr(e){var t,n,a,o,i=e.enabled,s=e.enableEvents,l=e.placement,c=e.flip,u=e.offset,d=e.containerPadding,f=e.arrowElement,p=e.popperConfig,m=void 0===p?{}:p,v=function(e){var t={};return Array.isArray(e)?(null==e||e.forEach((function(e){t[e.name]=e})),t):e||t}(m.modifiers);return r({},m,{placement:l,enabled:i,modifiers:nr(r({},v,{eventListeners:{enabled:s},preventOverflow:r({},v.preventOverflow,{options:d?r({padding:d},null==(t=v.preventOverflow)?void 0:t.options):null==(n=v.preventOverflow)?void 0:n.options}),offset:{options:r({offset:u},null==(a=v.offset)?void 0:a.options)},arrow:r({},v.arrow,{enabled:!!f,options:r({},null==(o=v.arrow)?void 0:o.options,{element:f})}),flip:r({enabled:!!c},v.flip)}))})}var ar=function(){};function or(e){void 0===e&&(e={});var t=Object(s.useContext)(At),n=Dt(),o=n[0],i=n[1],l=Object(s.useRef)(!1),c=e,u=c.flip,d=c.offset,f=c.rootCloseEvent,p=c.popperConfig,m=void 0===p?{}:p,v=c.usePopper,b=void 0===v?!!t:v,h=null==(null==t?void 0:t.show)?e.show:t.show,g=null==(null==t?void 0:t.alignEnd)?e.alignEnd:t.alignEnd;h&&!l.current&&(l.current=!0);var y=function(e){null==t||t.toggle(!1,e)},x=t||{},E=x.drop,w=x.setMenu,O=x.menuElement,N=x.toggleElement,C=g?"bottom-end":"bottom-start";"up"===E?C=g?"top-end":"top-start":"right"===E?C=g?"right-end":"right-start":"left"===E&&(C=g?"left-end":"left-start");var P,j=Xn(N,O,rr({placement:C,enabled:!(!b||!h),enableEvents:h,offset:d,flip:u,arrowElement:o,popperConfig:m})),k=j.styles,R=j.attributes,T=a(j,["styles","attributes"]),S={ref:w||ar,"aria-labelledby":null==N?void 0:N.id},M={show:h,alignEnd:g,hasShown:l.current,close:y};return P=b?r({},T,M,{props:r({},S,R.popper,{style:k.popper}),arrowProps:r({ref:i},R.arrow,{style:k.arrow})}):r({},M,{props:S}),tr(O,y,{clickTrigger:f,disabled:!(P&&h)}),P}var ir={children:W.a.func.isRequired,show:W.a.bool,alignEnd:W.a.bool,flip:W.a.bool,usePopper:W.a.oneOf([!0,!1]),popperConfig:W.a.object,rootCloseEvent:W.a.string};function sr(e){var t=e.children,n=or(a(e,["children"]));return l.a.createElement(l.a.Fragment,null,n.hasShown?t(n):null)}sr.displayName="ReactOverlaysDropdownMenu",sr.propTypes=ir,sr.defaultProps={usePopper:!0};var lr=sr,cr=function(){};function ur(){var e=Object(s.useContext)(At)||{},t=e.show,n=void 0!==t&&t,r=e.toggle,a=void 0===r?cr:r;return[{ref:e.setToggle||cr,"aria-haspopup":!0,"aria-expanded":!!n},{show:n,toggle:a}]}var dr={children:W.a.func.isRequired};function fr(e){var t=e.children,n=ur(),r=n[0],a=n[1],o=a.show,i=a.toggle;return l.a.createElement(l.a.Fragment,null,t({show:o,toggle:i,props:r}))}fr.displayName="ReactOverlaysDropdownToggle",fr.propTypes=dr;var pr=fr,mr={children:W.a.func.isRequired,drop:W.a.oneOf(["up","left","right","down"]),focusFirstItemOnShow:W.a.oneOf([!1,!0,"keyboard"]),itemSelector:W.a.string,alignEnd:W.a.bool,show:W.a.bool,defaultShow:W.a.bool,onToggle:W.a.func};function vr(e){var t=e.drop,n=e.alignEnd,r=e.defaultShow,a=e.show,o=e.onToggle,i=e.itemSelector,c=void 0===i?"* > *":i,u=e.focusFirstItemOnShow,d=e.children,f=Ft(),m=p(a,r,o),v=m[0],b=m[1],h=Dt(),g=h[0],y=h[1],x=Object(s.useRef)(null),E=x.current,w=Object(s.useCallback)((function(e){x.current=e,f()}),[f]),O=It(v),N=Object(s.useRef)(null),C=Object(s.useRef)(!1),P=Object(s.useCallback)((function(e){b(!v,e)}),[b,v]),j=Object(s.useMemo)((function(){return{toggle:P,drop:t,show:v,alignEnd:n,menuElement:E,toggleElement:g,setMenu:w,setToggle:y}}),[P,t,v,n,E,g,w,y]);E&&O&&!v&&(C.current=E.contains(document.activeElement));var k=ve((function(){g&&g.focus&&g.focus()})),R=ve((function(){var e=N.current,t=u;if(null==t&&(t=!(!x.current||!function(e,t){if(!Rt){var n=document.body,r=n.matches||n.matchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector||n.msMatchesSelector;Rt=function(e,t){return r.call(e,t)}}return Rt(e,t)}(x.current,"[role=menu]"))&&"keyboard"),!1!==t&&("keyboard"!==t||/^key.+$/.test(e))){var n=Mt(x.current,c)[0];n&&n.focus&&n.focus()}}));Object(s.useEffect)((function(){v?R():C.current&&(C.current=!1,k())}),[v,C,k,R]),Object(s.useEffect)((function(){N.current=null}));var T=function(e,t){if(!x.current)return null;var n=Mt(x.current,c),r=n.indexOf(e)+t;return n[r=Math.max(0,Math.min(r,n.length))]};return l.a.createElement(At.Provider,{value:j},d({props:{onKeyDown:function(e){var t=e.key,n=e.target;if(!/input|textarea/i.test(n.tagName)||!(" "===t||"Escape"!==t&&x.current&&x.current.contains(n)))switch(N.current=e.type,t){case"ArrowUp":var r=T(n,-1);return r&&r.focus&&r.focus(),void e.preventDefault();case"ArrowDown":if(e.preventDefault(),v){var a=T(n,1);a&&a.focus&&a.focus()}else P(e);return;case"Escape":case"Tab":b(!1,e)}}}}))}vr.displayName="ReactOverlaysDropdown",vr.propTypes=mr,vr.Menu=lr,vr.Toggle=pr;var br=vr,hr=l.a.createContext(null);hr.displayName="NavContext";var gr=hr,yr={as:ke,disabled:!1},xr=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.children,u=e.eventKey,d=e.disabled,f=e.href,p=e.onClick,m=e.onSelect,v=e.active,b=e.as,h=a(e,["bsPrefix","className","children","eventKey","disabled","href","onClick","onSelect","active","as"]),g=E(n,"dropdown-item"),y=Object(s.useContext)(N),x=(Object(s.useContext)(gr)||{}).activeKey,w=O(u,f),C=null==v&&null!=w?O(x)===w:v,P=ve((function(e){d||(p&&p(e),y&&y(w,e),m&&m(w,e))}));return l.a.createElement(b,r({},h,{ref:t,href:f,disabled:d,className:i()(o,g,C&&"active",d&&"disabled"),onClick:P}),c)}));xr.displayName="DropdownItem",xr.defaultProps=yr;var Er=xr,wr=function(e){return e&&"function"!=typeof e?function(t){e.current=t}:e};var Or=function(e,t){return Object(s.useMemo)((function(){return function(e,t){var n=wr(e),r=wr(t);return function(e){n&&n(e),r&&r(e)}}(e,t)}),[e,t])},Nr=l.a.createContext(null);Nr.displayName="NavbarContext";var Cr=Nr;function Pr(e,t){return e}function jr(e,t){return e.classList?!!t&&e.classList.contains(t):-1!==(" "+(e.className.baseVal||e.className)+" ").indexOf(" "+t+" ")}function kr(e){var t=window.getComputedStyle(e);return{top:parseFloat(t.marginTop)||0,right:parseFloat(t.marginRight)||0,bottom:parseFloat(t.marginBottom)||0,left:parseFloat(t.marginLeft)||0}}function Rr(){var e=Object(s.useRef)(null),t=Object(s.useRef)(null),n=E(void 0,"popover"),r=E(void 0,"dropdown-menu");return[Object(s.useCallback)((function(a){a&&(jr(a,n)||jr(a,r))&&(t.current=kr(a),a.style.margin="0",e.current=a)}),[n,r]),[Object(s.useMemo)((function(){return{name:"offset",options:{offset:function(e){var n=e.placement;if(!t.current)return[0,0];var r=t.current,a=r.top,o=r.left,i=r.bottom,s=r.right;switch(n.split("-")[0]){case"top":return[0,i];case"left":return[0,s];case"bottom":return[0,a];case"right":return[0,o];default:return[0,0]}}}}}),[t]),Object(s.useMemo)((function(){return{name:"popoverArrowMargins",enabled:!0,phase:"main",requiresIfExists:["arrow"],effect:function(t){var r=t.state;if(e.current&&r.elements.arrow&&jr(e.current,n)&&r.modifiersData["arrow#persistent"]){var a=kr(r.elements.arrow),o=a.top,i=a.right,s=o||i;return r.modifiersData["arrow#persistent"].padding={top:s,left:s,right:s,bottom:s},r.elements.arrow.style.margin="0",function(){r.elements.arrow&&(r.elements.arrow.style.margin="")}}}}}),[n])]]}var Tr=W.a.oneOf(["left","right"]),Sr=W.a.oneOfType([Tr,W.a.shape({sm:Tr}),W.a.shape({md:Tr}),W.a.shape({lg:Tr}),W.a.shape({xl:Tr})]),Mr=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.align,u=e.alignRight,d=e.rootCloseEvent,f=e.flip,p=e.show,m=e.renderOnMount,v=e.as,b=void 0===v?"div":v,h=e.popperConfig,g=a(e,["bsPrefix","className","align","alignRight","rootCloseEvent","flip","show","renderOnMount","as","popperConfig"]),y=Object(s.useContext)(Cr),x=E(n,"dropdown-menu"),w=Rr(),O=w[0],N=w[1],C=[];if(c)if("object"==typeof c){var P=Object.keys(c);if(P.length){var j=P[0],k=c[j];u="left"===k,C.push(x+"-"+j+"-"+k)}}else"right"===c&&(u=!0);var R=or({flip:f,rootCloseEvent:d,show:p,alignEnd:u,usePopper:!y&&0===C.length,popperConfig:r({},h,{modifiers:N.concat((null==h?void 0:h.modifiers)||[])})}),T=R.hasShown,S=R.placement,M=R.show,I=R.alignEnd,D=R.close,F=R.props;return F.ref=Or(O,Or(Pr(t),F.ref)),T||m?("string"!=typeof b&&(F.show=M,F.close=D,F.alignRight=I),S&&(g.style=r({},g.style,F.style),g["x-placement"]=S),l.a.createElement(b,r({},g,F,{className:i.a.apply(void 0,[o,x,M&&"show",I&&x+"-right"].concat(C))}))):null}));Mr.displayName="DropdownMenu",Mr.defaultProps={align:"left",alignRight:!1,flip:!0};var Ir=Mr,Dr=(n(6),l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.split,s=e.className,c=e.childBsPrefix,u=e.as,d=void 0===u?ze:u,f=a(e,["bsPrefix","split","className","childBsPrefix","as"]),p=E(n,"dropdown-toggle");void 0!==c&&(f.bsPrefix=c);var m=ur(),v=m[0],b=m[1].toggle;return v.ref=Or(v.ref,Pr(t)),l.a.createElement(d,r({onClick:b,className:i()(s,p,o&&p+"-split")},v,f))})));Dr.displayName="DropdownToggle";var Fr=Dr,Ar=Ce("dropdown-header",{defaultProps:{role:"heading"}}),Lr=Ce("dropdown-divider",{defaultProps:{role:"separator"}}),Br=Ce("dropdown-item-text",{Component:"span"}),Kr=l.a.forwardRef((function(e,t){var n=m(e,{show:"onToggle"}),o=n.bsPrefix,c=n.drop,u=n.show,d=n.className,f=n.alignRight,p=n.onSelect,v=n.onToggle,b=n.focusFirstItemOnShow,h=n.as,g=void 0===h?"div":h,y=(n.navbar,a(n,["bsPrefix","drop","show","className","alignRight","onSelect","onToggle","focusFirstItemOnShow","as","navbar"])),x=Object(s.useContext)(N),w=E(o,"dropdown"),O=ve((function(e,t,n){void 0===n&&(n=t.type),t.currentTarget===document&&(n="rootClose"),v&&v(e,t,{source:n})})),C=ve((function(e,t){x&&x(e,t),p&&p(e,t),O(!1,t,"select")}));return l.a.createElement(N.Provider,{value:C},l.a.createElement(br,{drop:c,show:u,alignEnd:f,onToggle:O,focusFirstItemOnShow:b,itemSelector:"."+w+"-item:not(.disabled):not(:disabled)"},(function(e){var n=e.props;return l.a.createElement(g,r({},y,n,{ref:t,className:i()(d,u&&"show",(!c||"down"===c)&&w,"up"===c&&"dropup","right"===c&&"dropright","left"===c&&"dropleft")}))})))}));Kr.displayName="Dropdown",Kr.defaultProps={navbar:!1},Kr.Divider=Lr,Kr.Header=Ar,Kr.Item=Er,Kr.ItemText=Br,Kr.Menu=Ir,Kr.Toggle=Fr;var _r=Kr,Hr={id:W.a.any,href:W.a.string,onClick:W.a.func,title:W.a.node.isRequired,disabled:W.a.bool,menuAlign:Sr,menuRole:W.a.string,renderMenuOnMount:W.a.bool,rootCloseEvent:W.a.string,bsPrefix:W.a.string,variant:W.a.string,size:W.a.string},zr=l.a.forwardRef((function(e,t){var n=e.title,o=e.children,i=e.bsPrefix,s=e.rootCloseEvent,c=e.variant,u=e.size,d=e.menuAlign,f=e.menuRole,p=e.renderMenuOnMount,m=e.disabled,v=e.href,b=e.id,h=a(e,["title","children","bsPrefix","rootCloseEvent","variant","size","menuAlign","menuRole","renderMenuOnMount","disabled","href","id"]);return l.a.createElement(_r,r({ref:t},h),l.a.createElement(Fr,{id:b,href:v,size:u,variant:c,disabled:m,childBsPrefix:i},n),l.a.createElement(Ir,{align:d,role:f,renderOnMount:p,rootCloseEvent:s},o))}));zr.displayName="DropdownButton",zr.propTypes=Hr;var Vr=zr,qr=(n(7),{type:W.a.string,tooltip:W.a.bool,as:W.a.elementType}),Ur=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"div":n,s=e.className,c=e.type,u=void 0===c?"valid":c,d=e.tooltip,f=void 0!==d&&d,p=a(e,["as","className","type","tooltip"]);return l.a.createElement(o,r({},p,{ref:t,className:i()(s,u+"-"+(f?"tooltip":"feedback"))}))}));Ur.displayName="Feedback",Ur.propTypes=qr;var Wr=Ur,Gr=l.a.createContext({controlId:void 0}),Xr=l.a.forwardRef((function(e,t){var n=e.id,o=e.bsPrefix,c=e.bsCustomPrefix,u=e.className,d=e.type,f=void 0===d?"checkbox":d,p=e.isValid,m=void 0!==p&&p,v=e.isInvalid,b=void 0!==v&&v,h=e.isStatic,g=e.as,y=void 0===g?"input":g,x=a(e,["id","bsPrefix","bsCustomPrefix","className","type","isValid","isInvalid","isStatic","as"]),w=Object(s.useContext)(Gr),O=w.controlId,N=w.custom?[c,"custom-control-input"]:[o,"form-check-input"];return o=E(N[0],N[1]),l.a.createElement(y,r({},x,{ref:t,type:f,id:n||O,className:i()(u,o,m&&"is-valid",b&&"is-invalid",h&&"position-static")}))}));Xr.displayName="FormCheckInput";var $r=Xr,Yr=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.bsCustomPrefix,c=e.className,u=e.htmlFor,d=a(e,["bsPrefix","bsCustomPrefix","className","htmlFor"]),f=Object(s.useContext)(Gr),p=f.controlId,m=f.custom?[o,"custom-control-label"]:[n,"form-check-label"];return n=E(m[0],m[1]),l.a.createElement("label",r({},d,{ref:t,htmlFor:u||p,className:i()(c,n)}))}));Yr.displayName="FormCheckLabel";var Jr=Yr,Zr=l.a.forwardRef((function(e,t){var n=e.id,o=e.bsPrefix,c=e.bsCustomPrefix,u=e.inline,d=void 0!==u&&u,f=e.disabled,p=void 0!==f&&f,m=e.isValid,v=void 0!==m&&m,b=e.isInvalid,h=void 0!==b&&b,g=e.feedbackTooltip,y=void 0!==g&&g,x=e.feedback,w=e.className,O=e.style,N=e.title,C=void 0===N?"":N,P=e.type,j=void 0===P?"checkbox":P,k=e.label,R=e.children,T=e.custom,S=e.as,M=void 0===S?"input":S,I=a(e,["id","bsPrefix","bsCustomPrefix","inline","disabled","isValid","isInvalid","feedbackTooltip","feedback","className","style","title","type","label","children","custom","as"]),D="switch"===j||T,F=D?[c,"custom-control"]:[o,"form-check"];o=E(F[0],F[1]);var A=Object(s.useContext)(Gr).controlId,L=Object(s.useMemo)((function(){return{controlId:n||A,custom:D}}),[A,D,n]),B=null!=k&&!1!==k&&!R,K=l.a.createElement($r,r({},I,{type:"switch"===j?"checkbox":j,ref:t,isValid:v,isInvalid:h,isStatic:!B,disabled:p,as:M}));return l.a.createElement(Gr.Provider,{value:L},l.a.createElement("div",{style:O,className:i()(w,o,D&&"custom-"+j,d&&o+"-inline")},R||l.a.createElement(l.a.Fragment,null,K,B&&l.a.createElement(Jr,{title:C},k),(v||h)&&l.a.createElement(Wr,{type:v?"valid":"invalid",tooltip:y},x))))}));Zr.displayName="FormCheck",Zr.Input=$r,Zr.Label=Jr;var Qr=Zr,ea=l.a.forwardRef((function(e,t){var n=e.id,o=e.bsPrefix,c=e.bsCustomPrefix,u=e.className,d=e.isValid,f=e.isInvalid,p=e.lang,m=e.as,v=void 0===m?"input":m,b=a(e,["id","bsPrefix","bsCustomPrefix","className","isValid","isInvalid","lang","as"]),h=Object(s.useContext)(Gr),g=h.controlId,y=h.custom?[c,"custom-file-input"]:[o,"form-control-file"];return o=E(y[0],y[1]),l.a.createElement(v,r({},b,{ref:t,id:n||g,type:"file",lang:p,className:i()(u,o,d&&"is-valid",f&&"is-invalid")}))}));ea.displayName="FormFileInput";var ta=ea,na=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.bsCustomPrefix,c=e.className,u=e.htmlFor,d=a(e,["bsPrefix","bsCustomPrefix","className","htmlFor"]),f=Object(s.useContext)(Gr),p=f.controlId,m=f.custom?[o,"custom-file-label"]:[n,"form-file-label"];return n=E(m[0],m[1]),l.a.createElement("label",r({},d,{ref:t,htmlFor:u||p,className:i()(c,n),"data-browse":d["data-browse"]}))}));na.displayName="FormFileLabel";var ra=na,aa=l.a.forwardRef((function(e,t){var n=e.id,o=e.bsPrefix,c=e.bsCustomPrefix,u=e.disabled,d=void 0!==u&&u,f=e.isValid,p=void 0!==f&&f,m=e.isInvalid,v=void 0!==m&&m,b=e.feedbackTooltip,h=void 0!==b&&b,g=e.feedback,y=e.className,x=e.style,w=e.label,O=e.children,N=e.custom,C=e.lang,P=e["data-browse"],j=e.as,k=void 0===j?"div":j,R=e.inputAs,T=void 0===R?"input":R,S=a(e,["id","bsPrefix","bsCustomPrefix","disabled","isValid","isInvalid","feedbackTooltip","feedback","className","style","label","children","custom","lang","data-browse","as","inputAs"]),M=N?[c,"custom"]:[o,"form-file"];o=E(M[0],M[1]);var I=Object(s.useContext)(Gr).controlId,D=Object(s.useMemo)((function(){return{controlId:n||I,custom:N}}),[I,N,n]),F=null!=w&&!1!==w&&!O,A=l.a.createElement(ta,r({},S,{ref:t,isValid:p,isInvalid:v,disabled:d,as:T,lang:C}));return l.a.createElement(Gr.Provider,{value:D},l.a.createElement(k,{style:x,className:i()(y,o,N&&"custom-file")},O||l.a.createElement(l.a.Fragment,null,N?l.a.createElement(l.a.Fragment,null,A,F&&l.a.createElement(ra,{"data-browse":P},w)):l.a.createElement(l.a.Fragment,null,F&&l.a.createElement(ra,null,w),A),(p||v)&&l.a.createElement(Wr,{type:p?"valid":"invalid",tooltip:h},g))))}));aa.displayName="FormFile",aa.Input=ta,aa.Label=ra;var oa=aa,ia=l.a.forwardRef((function(e,t){var n,o,c=e.bsPrefix,u=e.bsCustomPrefix,d=e.type,f=e.size,p=e.htmlSize,m=e.id,v=e.className,b=e.isValid,h=void 0!==b&&b,g=e.isInvalid,y=void 0!==g&&g,x=e.plaintext,w=e.readOnly,O=e.custom,N=e.as,C=void 0===N?"input":N,P=a(e,["bsPrefix","bsCustomPrefix","type","size","htmlSize","id","className","isValid","isInvalid","plaintext","readOnly","custom","as"]),j=Object(s.useContext)(Gr).controlId,k=O?[u,"custom"]:[c,"form-control"];if(c=E(k[0],k[1]),x)(o={})[c+"-plaintext"]=!0,n=o;else if("file"===d){var R;(R={})[c+"-file"]=!0,n=R}else if("range"===d){var T;(T={})[c+"-range"]=!0,n=T}else if("select"===C&&O){var S;(S={})[c+"-select"]=!0,S[c+"-select-"+f]=f,n=S}else{var M;(M={})[c]=!0,M[c+"-"+f]=f,n=M}return l.a.createElement(C,r({},P,{type:d,size:p,ref:t,readOnly:w,id:m||j,className:i()(v,n,h&&"is-valid",y&&"is-invalid")}))}));ia.displayName="FormControl";var sa=Object.assign(ia,{Feedback:Wr}),la=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.children,u=e.controlId,d=e.as,f=void 0===d?"div":d,p=a(e,["bsPrefix","className","children","controlId","as"]);n=E(n,"form-group");var m=Object(s.useMemo)((function(){return{controlId:u}}),[u]);return l.a.createElement(Gr.Provider,{value:m},l.a.createElement(f,r({},p,{ref:t,className:i()(o,n)}),c))}));la.displayName="FormGroup";var ca=la,ua=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"label":n,c=e.bsPrefix,u=e.column,d=e.srOnly,f=e.className,p=e.htmlFor,m=a(e,["as","bsPrefix","column","srOnly","className","htmlFor"]),v=Object(s.useContext)(Gr).controlId;c=E(c,"form-label");var b="col-form-label";"string"==typeof u&&(b=b+" "+b+"-"+u);var h=i()(f,c,d&&"sr-only",u&&b);return p=p||v,u?l.a.createElement(Tt,r({as:"label",className:h,htmlFor:p},m)):l.a.createElement(o,r({ref:t,className:h,htmlFor:p},m))}));ua.displayName="FormLabel",ua.defaultProps={column:!1,srOnly:!1};var da=ua,fa=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.as,c=void 0===s?"small":s,u=e.muted,d=a(e,["bsPrefix","className","as","muted"]);return n=E(n,"form-text"),l.a.createElement(c,r({},d,{ref:t,className:i()(o,n,u&&"text-muted")}))}));fa.displayName="FormText";var pa=fa,ma=l.a.forwardRef((function(e,t){return l.a.createElement(Qr,r({},e,{ref:t,type:"switch"}))}));ma.displayName="Switch",ma.Input=Qr.Input,ma.Label=Qr.Label;var va=ma,ba=Ce("form-row"),ha=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.inline,s=e.className,c=e.validated,u=e.as,d=void 0===u?"form":u,f=a(e,["bsPrefix","inline","className","validated","as"]);return n=E(n,"form"),l.a.createElement(d,r({},f,{ref:t,className:i()(s,c&&"was-validated",o&&n+"-inline")}))}));ha.displayName="Form",ha.defaultProps={inline:!1},ha.Row=ba,ha.Group=ca,ha.Control=sa,ha.Check=Qr,ha.File=oa,ha.Switch=va,ha.Label=da,ha.Text=pa;var ga=ha,ya=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.fluid,s=e.as,c=void 0===s?"div":s,u=e.className,d=a(e,["bsPrefix","fluid","as","className"]),f=E(n,"container"),p="string"==typeof o?"-"+o:"-fluid";return l.a.createElement(c,r({ref:t},d,{className:i()(u,o?""+f+p:f)}))}));ya.displayName="Container",ya.defaultProps={fluid:!1};var xa=ya,Ea={bsPrefix:W.a.string,fluid:W.a.bool,rounded:W.a.bool,roundedCircle:W.a.bool,thumbnail:W.a.bool},wa=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.fluid,c=e.rounded,u=e.roundedCircle,d=e.thumbnail,f=a(e,["bsPrefix","className","fluid","rounded","roundedCircle","thumbnail"]);n=E(n,"img");var p=i()(s&&n+"-fluid",c&&"rounded",u&&"rounded-circle",d&&n+"-thumbnail");return l.a.createElement("img",r({ref:t},f,{className:i()(o,p)}))}));wa.displayName="Image",wa.defaultProps={fluid:!1,rounded:!1,roundedCircle:!1,thumbnail:!1};var Oa=wa,Na=l.a.forwardRef((function(e,t){var n=e.className,o=a(e,["className"]);return l.a.createElement(Oa,r({ref:t},o,{className:i()(n,"figure-img")}))}));Na.displayName="FigureImage",Na.propTypes=Ea,Na.defaultProps={fluid:!0};var Ca=Na,Pa=Ce("figure-caption",{Component:"figcaption"}),ja=Ce("figure",{Component:"figure"});ja.Image=Ca,ja.Caption=Pa;var ka=ja,Ra=Ce("input-group-append"),Ta=Ce("input-group-prepend"),Sa=Ce("input-group-text",{Component:"span"}),Ma=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.size,s=e.className,c=e.as,u=void 0===c?"div":c,d=a(e,["bsPrefix","size","className","as"]);return n=E(n,"input-group"),l.a.createElement(u,r({ref:t},d,{className:i()(s,n,o&&n+"-"+o)}))}));Ma.displayName="InputGroup";var Ia=r({},Ma,{Text:Sa,Radio:function(e){return l.a.createElement(Sa,null,l.a.createElement("input",r({type:"radio"},e)))},Checkbox:function(e){return l.a.createElement(Sa,null,l.a.createElement("input",r({type:"checkbox"},e)))},Append:Ra,Prepend:Ta}),Da=l.a.forwardRef((function(e,t){var n,o=e.as,s=void 0===o?"div":o,c=e.className,u=e.fluid,d=e.bsPrefix,f=a(e,["as","className","fluid","bsPrefix"]),p=((n={})[d=E(d,"jumbotron")]=!0,n[d+"-fluid"]=u,n);return l.a.createElement(s,r({ref:t},f,{className:i()(c,p)}))}));Da.defaultProps={fluid:!1},Da.displayName="Jumbotron";var Fa=Da,Aa=l.a.createContext(null),La=function(){},Ba=l.a.forwardRef((function(e,t){var n,o,i=e.as,c=void 0===i?"ul":i,u=e.onSelect,d=e.activeKey,f=e.role,p=e.onKeyDown,m=a(e,["as","onSelect","activeKey","role","onKeyDown"]),v=Ft(),b=Object(s.useRef)(!1),h=Object(s.useContext)(N),g=Object(s.useContext)(Aa);g&&(f=f||"tablist",d=g.activeKey,n=g.getControlledId,o=g.getControllerId);var y=Object(s.useRef)(null),x=function(e){var t=y.current;if(!t)return null;var n=Mt(t,"[data-rb-event-key]:not(.disabled)"),r=t.querySelector(".active");if(!r)return null;var a=n.indexOf(r);if(-1===a)return null;var o=a+e;return o>=n.length&&(o=0),o<0&&(o=n.length-1),n[o]},E=function(e,t){null!=e&&(u&&u(e,t),h&&h(e,t))};Object(s.useEffect)((function(){if(y.current&&b.current){var e=y.current.querySelector("[data-rb-event-key].active");e&&e.focus()}b.current=!1}));var w=Or(t,y);return l.a.createElement(N.Provider,{value:E},l.a.createElement(gr.Provider,{value:{role:f,activeKey:O(d),getControlledId:n||La,getControllerId:o||La}},l.a.createElement(c,r({},m,{onKeyDown:function(e){var t;switch(p&&p(e),e.key){case"ArrowLeft":case"ArrowUp":t=x(-1);break;case"ArrowRight":case"ArrowDown":t=x(1);break;default:return}t&&(e.preventDefault(),E(t.dataset.rbEventKey,e),b.current=!0,v())},ref:w,role:f}))))})),Ka=l.a.forwardRef((function(e,t){var n=e.active,o=e.className,c=e.eventKey,u=e.onSelect,d=e.onClick,f=e.as,p=a(e,["active","className","eventKey","onSelect","onClick","as"]),m=O(c,p.href),v=Object(s.useContext)(N),b=Object(s.useContext)(gr),h=n;if(b){p.role||"tablist"!==b.role||(p.role="tab");var g=b.getControllerId(m),y=b.getControlledId(m);p["data-rb-event-key"]=m,p.id=g||p.id,p["aria-controls"]=y||p["aria-controls"],h=null==n&&null!=m?b.activeKey===m:n}"tab"===p.role&&(p.tabIndex=h?p.tabIndex:-1,p["aria-selected"]=h);var x=ve((function(e){d&&d(e),null!=m&&(u&&u(m,e),v&&v(m,e))}));return l.a.createElement(f,r({},p,{ref:t,onClick:x,className:i()(o,h&&"active")}))}));Ka.defaultProps={disabled:!1};var _a=Ka,Ha={variant:void 0,active:!1,disabled:!1},za=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.active,c=e.disabled,u=e.className,d=e.variant,f=e.action,p=e.as,m=e.eventKey,v=e.onClick,b=a(e,["bsPrefix","active","disabled","className","variant","action","as","eventKey","onClick"]);n=E(n,"list-group-item");var h=Object(s.useCallback)((function(e){if(c)return e.preventDefault(),void e.stopPropagation();v&&v(e)}),[c,v]);return l.a.createElement(_a,r({ref:t},b,{eventKey:O(m,b.href),as:p||(f?b.href?"a":"button":"div"),onClick:h,className:i()(u,n,o&&"active",c&&"disabled",d&&n+"-"+d,f&&n+"-action")}))}));za.defaultProps=Ha,za.displayName="ListGroupItem";var Va=za,qa={variant:void 0,horizontal:void 0},Ua=l.a.forwardRef((function(e,t){var n,o=m(e,{activeKey:"onSelect"}),s=o.className,c=o.bsPrefix,u=o.variant,d=o.horizontal,f=o.as,p=void 0===f?"div":f,v=a(o,["className","bsPrefix","variant","horizontal","as"]),b=E(c,"list-group");return n=d?!0===d?"horizontal":"horizontal-"+d:null,l.a.createElement(Ba,r({ref:t},v,{as:p,className:i()(s,b,u&&b+"-"+u,n&&b+"-"+n)}))}));Ua.defaultProps=qa,Ua.displayName="ListGroup",Ua.Item=Va;var Wa=Ua,Ga=Ce("media-body"),Xa=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.as,c=void 0===s?"div":s,u=a(e,["bsPrefix","className","as"]),d=E(n,"media");return l.a.createElement(c,r({},u,{ref:t,className:i()(o,d)}))}));Xa.displayName="Media",Xa.Body=Ga;var $a,Ya=Xa;function Ja(e){if((!$a&&0!==$a||e)&&A){var t=document.createElement("div");t.style.position="absolute",t.style.top="-9999px",t.style.width="50px",t.style.height="50px",t.style.overflow="scroll",document.body.appendChild(t),$a=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return $a}function Za(e){void 0===e&&(e=R());try{var t=e.activeElement;return t&&t.nodeName?t:null}catch(t){return e.body}}function Qa(e,t){e.classList?e.classList.add(t):jr(e,t)||("string"==typeof e.className?e.className=e.className+" "+t:e.setAttribute("class",(e.className&&e.className.baseVal||"")+" "+t))}function eo(e,t){return e.replace(new RegExp("(^|\\s)"+t+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,"")}function to(e,t){e.classList?e.classList.remove(t):"string"==typeof e.className?e.className=eo(e.className,t):e.setAttribute("class",eo(e.className&&e.className.baseVal||"",t))}function no(e){return"window"in e&&e.window===e?e:"nodeType"in(t=e)&&t.nodeType===document.DOCUMENT_NODE&&e.defaultView||!1;var t}function ro(e){var t;return no(e)||(t=e)&&"body"===t.tagName.toLowerCase()?function(e){var t=no(e)?R():R(e),n=no(e)||t.defaultView;return t.body.clientWidth<n.innerWidth}(e):e.scrollHeight>e.clientHeight}var ao=["template","script","style"],oo=function(e,t,n){[].forEach.call(e.children,(function(e){var r,a,o;-1===t.indexOf(e)&&(a=(r=e).nodeType,o=r.tagName,1===a&&-1===ao.indexOf(o.toLowerCase()))&&n(e)}))};function io(e,t){t&&(e?t.setAttribute("aria-hidden","true"):t.removeAttribute("aria-hidden"))}var so,lo=function(){function e(e){var t=void 0===e?{}:e,n=t.hideSiblingNodes,r=void 0===n||n,a=t.handleContainerOverflow,o=void 0===a||a;this.hideSiblingNodes=void 0,this.handleContainerOverflow=void 0,this.modals=void 0,this.containers=void 0,this.data=void 0,this.scrollbarSize=void 0,this.hideSiblingNodes=r,this.handleContainerOverflow=o,this.modals=[],this.containers=[],this.data=[],this.scrollbarSize=Ja()}var t=e.prototype;return t.isContainerOverflowing=function(e){var t=this.data[this.containerIndexFromModal(e)];return t&&t.overflowing},t.containerIndexFromModal=function(e){return t=this.data,n=function(t){return-1!==t.modals.indexOf(e)},r=-1,t.some((function(e,t){return!!n(e,t)&&(r=t,!0)})),r;var t,n,r},t.setContainerStyle=function(e,t){var n={overflow:"hidden"};e.style={overflow:t.style.overflow,paddingRight:t.style.paddingRight},e.overflowing&&(n.paddingRight=parseInt(F(t,"paddingRight")||"0",10)+this.scrollbarSize+"px"),F(t,n)},t.removeContainerStyle=function(e,t){Object.assign(t.style,e.style)},t.add=function(e,t,n){var r=this.modals.indexOf(e),a=this.containers.indexOf(t);if(-1!==r)return r;if(r=this.modals.length,this.modals.push(e),this.hideSiblingNodes&&function(e,t){var n=t.dialog,r=t.backdrop;oo(e,[n,r],(function(e){return io(!0,e)}))}(t,e),-1!==a)return this.data[a].modals.push(e),r;var o={modals:[e],classes:n?n.split(/\s+/):[],overflowing:ro(t)};return this.handleContainerOverflow&&this.setContainerStyle(o,t),o.classes.forEach(Qa.bind(null,t)),this.containers.push(t),this.data.push(o),r},t.remove=function(e){var t=this.modals.indexOf(e);if(-1!==t){var n=this.containerIndexFromModal(e),r=this.data[n],a=this.containers[n];if(r.modals.splice(r.modals.indexOf(e),1),this.modals.splice(t,1),0===r.modals.length)r.classes.forEach(to.bind(null,a)),this.handleContainerOverflow&&this.removeContainerStyle(r,a),this.hideSiblingNodes&&function(e,t){var n=t.dialog,r=t.backdrop;oo(e,[n,r],(function(e){return io(!1,e)}))}(a,e),this.containers.splice(n,1),this.data.splice(n,1);else if(this.hideSiblingNodes){var o=r.modals[r.modals.length-1],i=o.backdrop;io(!1,o.dialog),io(!1,i)}}},t.isTopModal=function(e){return!!this.modals.length&&this.modals[this.modals.length-1]===e},e}(),co=function(e){var t;return"undefined"==typeof document?null:null==e?R().body:("function"==typeof e&&(e=e()),e&&"current"in e&&(e=e.current),(null==(t=e)?void 0:t.nodeType)&&e||null)};function uo(e,t){var n=Object(s.useState)((function(){return co(e)})),r=n[0],a=n[1];if(!r){var o=co(e);o&&a(o)}return Object(s.useEffect)((function(){t&&r&&t(r)}),[t,r]),Object(s.useEffect)((function(){var t=co(e);t!==r&&a(t)}),[e,r]),r}function fo(e){var t=e||(so||(so=new lo),so),n=Object(s.useRef)({dialog:null,backdrop:null});return Object.assign(n.current,{add:function(e,r){return t.add(n.current,e,r)},remove:function(){return t.remove(n.current)},isTopModal:function(){return t.isTopModal(n.current)},setDialogRef:Object(s.useCallback)((function(e){n.current.dialog=e}),[]),setBackdropRef:Object(s.useCallback)((function(e){n.current.backdrop=e}),[])})}var po=Object(s.forwardRef)((function(e,t){var n=e.show,o=void 0!==n&&n,i=e.role,c=void 0===i?"dialog":i,u=e.className,d=e.style,f=e.children,p=e.backdrop,m=void 0===p||p,v=e.keyboard,b=void 0===v||v,h=e.onBackdropClick,g=e.onEscapeKeyDown,y=e.transition,x=e.backdropTransition,E=e.autoFocus,w=void 0===E||E,O=e.enforceFocus,N=void 0===O||O,C=e.restoreFocus,P=void 0===C||C,j=e.restoreFocusOptions,k=e.renderDialog,R=e.renderBackdrop,T=void 0===R?function(e){return l.a.createElement("div",e)}:R,S=e.manager,M=e.container,I=e.containerClassName,D=e.onShow,F=e.onHide,L=void 0===F?function(){}:F,B=e.onExit,K=e.onExited,_=e.onExiting,H=e.onEnter,V=e.onEntering,q=e.onEntered,U=a(e,["show","role","className","style","children","backdrop","keyboard","onBackdropClick","onEscapeKeyDown","transition","backdropTransition","autoFocus","enforceFocus","restoreFocus","restoreFocusOptions","renderDialog","renderBackdrop","manager","container","containerClassName","onShow","onHide","onExit","onExited","onExiting","onEnter","onEntering","onEntered"]),W=uo(M),G=fo(S),$=pt(),Y=It(o),J=Object(s.useState)(!o),Z=J[0],Q=J[1],ee=Object(s.useRef)(null);Object(s.useImperativeHandle)(t,(function(){return G}),[G]),A&&!Y&&o&&(ee.current=Za()),y||o||Z?o&&Z&&Q(!1):Q(!0);var te=ve((function(){if(G.add(W,I),se.current=z(document,"keydown",oe),ie.current=z(document,"focus",(function(){return setTimeout(re)}),!0),D&&D(),w){var e=Za(document);G.dialog&&e&&!$n(G.dialog,e)&&(ee.current=e,G.dialog.focus())}})),ne=ve((function(){var e;(G.remove(),null==se.current||se.current(),null==ie.current||ie.current(),P)&&(null==(e=ee.current)||null==e.focus||e.focus(j),ee.current=null)}));Object(s.useEffect)((function(){o&&W&&te()}),[o,W,te]),Object(s.useEffect)((function(){Z&&ne()}),[Z,ne]),mt((function(){ne()}));var re=ve((function(){if(N&&$()&&G.isTopModal()){var e=Za();G.dialog&&e&&!$n(G.dialog,e)&&G.dialog.focus()}})),ae=ve((function(e){e.target===e.currentTarget&&(null==h||h(e),!0===m&&L())})),oe=ve((function(e){b&&27===e.keyCode&&G.isTopModal()&&(null==g||g(e),e.defaultPrevented||L())})),ie=Object(s.useRef)(),se=Object(s.useRef)(),le=y;if(!W||!(o||le&&!Z))return null;var ce=r({role:c,ref:G.setDialogRef,"aria-modal":"dialog"===c||void 0},U,{style:d,className:u,tabIndex:-1}),ue=k?k(ce):l.a.createElement("div",ce,l.a.cloneElement(f,{role:"document"}));le&&(ue=l.a.createElement(le,{appear:!0,unmountOnExit:!0,in:!!o,onExit:B,onExiting:_,onExited:function(){Q(!0);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];null==K||K.apply(void 0,t)},onEnter:H,onEntering:V,onEntered:q},ue));var de=null;if(m){var fe=x;de=T({ref:G.setBackdropRef,onClick:ae}),fe&&(de=l.a.createElement(fe,{appear:!0,in:!!o},de))}return l.a.createElement(l.a.Fragment,null,X.a.createPortal(l.a.createElement(l.a.Fragment,null,de,ue),W))})),mo={show:W.a.bool,container:W.a.any,onShow:W.a.func,onHide:W.a.func,backdrop:W.a.oneOfType([W.a.bool,W.a.oneOf(["static"])]),renderDialog:W.a.func,renderBackdrop:W.a.func,onEscapeKeyDown:W.a.func,onBackdropClick:W.a.func,containerClassName:W.a.string,keyboard:W.a.bool,transition:W.a.elementType,backdropTransition:W.a.elementType,autoFocus:W.a.bool,enforceFocus:W.a.bool,restoreFocus:W.a.bool,restoreFocusOptions:W.a.shape({preventScroll:W.a.bool}),onEnter:W.a.func,onEntering:W.a.func,onEntered:W.a.func,onExit:W.a.func,onExiting:W.a.func,onExited:W.a.func,manager:W.a.instanceOf(lo)};po.displayName="Modal",po.propTypes=mo;var vo=Object.assign(po,{Manager:lo}),bo=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",ho=".sticky-top",go=".navbar-toggler",yo=function(e){function t(){return e.apply(this,arguments)||this}v(t,e);var n=t.prototype;return n.adjustAndStore=function(e,t,n){var r,a=t.style[e];t.dataset[e]=a,F(t,((r={})[e]=parseFloat(F(t,e))+n+"px",r))},n.restore=function(e,t){var n,r=t.dataset[e];void 0!==r&&(delete t.dataset[e],F(t,((n={})[e]=r,n)))},n.setContainerStyle=function(t,n){var r=this;if(e.prototype.setContainerStyle.call(this,t,n),t.overflowing){var a=Ja();Mt(n,bo).forEach((function(e){return r.adjustAndStore("paddingRight",e,a)})),Mt(n,ho).forEach((function(e){return r.adjustAndStore("marginRight",e,-a)})),Mt(n,go).forEach((function(e){return r.adjustAndStore("marginRight",e,a)}))}},n.removeContainerStyle=function(t,n){var r=this;e.prototype.removeContainerStyle.call(this,t,n),Mt(n,bo).forEach((function(e){return r.restore("paddingRight",e)})),Mt(n,ho).forEach((function(e){return r.restore("marginRight",e)})),Mt(n,go).forEach((function(e){return r.restore("marginRight",e)}))},t}(lo),xo=Ce("modal-body"),Eo=l.a.createContext({onHide:function(){}}),wo=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.contentClassName,c=e.centered,u=e.size,d=e.children,f=e.scrollable,p=a(e,["bsPrefix","className","contentClassName","centered","size","children","scrollable"]),m=(n=E(n,"modal"))+"-dialog";return l.a.createElement("div",r({},p,{ref:t,className:i()(m,o,u&&n+"-"+u,c&&m+"-centered",f&&m+"-scrollable")}),l.a.createElement("div",{className:i()(n+"-content",s)},d))}));wo.displayName="ModalDialog";var Oo=wo,No=Ce("modal-footer"),Co=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.closeLabel,c=e.closeButton,u=e.onHide,d=e.className,f=e.children,p=a(e,["bsPrefix","closeLabel","closeButton","onHide","className","children"]);n=E(n,"modal-header");var m=Object(s.useContext)(Eo),v=ve((function(){m&&m.onHide(),u&&u()}));return l.a.createElement("div",r({ref:t},p,{className:i()(d,n)}),f,c&&l.a.createElement(Ee,{label:o,onClick:v}))}));Co.displayName="ModalHeader",Co.defaultProps={closeLabel:"Close",closeButton:!1};var Po,jo=Co,ko=Ce("modal-title",{Component:we("h4")}),Ro={show:!1,backdrop:!0,keyboard:!0,autoFocus:!0,enforceFocus:!0,restoreFocus:!0,animation:!0,dialogAs:Oo};function To(e){return l.a.createElement(ge,e)}function So(e){return l.a.createElement(ge,e)}var Mo=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.style,u=e.dialogClassName,d=e.contentClassName,f=e.children,p=e.dialogAs,m=e["aria-labelledby"],v=e.show,b=e.animation,h=e.backdrop,g=e.keyboard,y=e.onEscapeKeyDown,x=e.onShow,w=e.onHide,O=e.container,N=e.autoFocus,C=e.enforceFocus,P=e.restoreFocus,j=e.restoreFocusOptions,k=e.onEntered,T=e.onExit,S=e.onExiting,M=e.onEnter,I=e.onEntering,D=e.onExited,F=e.backdropClassName,L=e.manager,B=a(e,["bsPrefix","className","style","dialogClassName","contentClassName","children","dialogAs","aria-labelledby","show","animation","backdrop","keyboard","onEscapeKeyDown","onShow","onHide","container","autoFocus","enforceFocus","restoreFocus","restoreFocusOptions","onEntered","onExit","onExiting","onEnter","onEntering","onExited","backdropClassName","manager"]),K=Object(s.useState)({}),z=K[0],V=K[1],U=Object(s.useState)(!1),W=U[0],G=U[1],X=Object(s.useRef)(!1),$=Object(s.useRef)(!1),Y=Object(s.useRef)(null),J=Dt(),Z=J[0],Q=J[1],ee=ve(w);n=E(n,"modal"),Object(s.useImperativeHandle)(t,(function(){return{get _modal(){return Z}}}),[Z]);var te=Object(s.useMemo)((function(){return{onHide:ee}}),[ee]);function ne(){return L||(Po||(Po=new yo),Po)}function re(e){if(A){var t=ne().isContainerOverflowing(Z),n=e.scrollHeight>R(e).documentElement.clientHeight;V({paddingRight:t&&!n?Ja():void 0,paddingLeft:!t&&n?Ja():void 0})}}var ae=ve((function(){Z&&re(Z.dialog)}));mt((function(){H(window,"resize",ae),Y.current&&Y.current()}));var oe=function(){X.current=!0},ie=function(e){X.current&&Z&&e.target===Z.dialog&&($.current=!0),X.current=!1},se=function(){G(!0),Y.current=q(Z.dialog,(function(){G(!1)}))},le=function(e){"static"!==h?$.current||e.target!==e.currentTarget?$.current=!1:w():function(e){e.target===e.currentTarget&&se()}(e)},ce=Object(s.useCallback)((function(e){return l.a.createElement("div",r({},e,{className:i()(n+"-backdrop",F,!b&&"show")}))}),[b,F,n]),ue=r({},c,z);b||(ue.display="block");return l.a.createElement(Eo.Provider,{value:te},l.a.createElement(vo,{show:v,ref:Q,backdrop:h,container:O,keyboard:!0,autoFocus:N,enforceFocus:C,restoreFocus:P,restoreFocusOptions:j,onEscapeKeyDown:function(e){g||"static"!==h?g&&y&&y(e):(e.preventDefault(),se())},onShow:x,onHide:w,onEnter:function(e){e&&(e.style.display="block",re(e));for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];M&&M.apply(void 0,[e].concat(n))},onEntering:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];I&&I.apply(void 0,[e].concat(n)),_(window,"resize",ae)},onEntered:k,onExit:function(e){Y.current&&Y.current();for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];T&&T.apply(void 0,[e].concat(n))},onExiting:S,onExited:function(e){e&&(e.style.display="");for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];D&&D.apply(void 0,n),H(window,"resize",ae)},manager:ne(),containerClassName:n+"-open",transition:b?To:void 0,backdropTransition:b?So:void 0,renderBackdrop:ce,renderDialog:function(e){return l.a.createElement("div",r({role:"dialog"},e,{style:ue,className:i()(o,n,W&&n+"-static"),onClick:h?le:void 0,onMouseUp:ie,"aria-labelledby":m}),l.a.createElement(p,r({},B,{role:"document",onMouseDown:oe,className:u,contentClassName:d}),f))}}))}));Mo.displayName="Modal",Mo.defaultProps=Ro,Mo.Body=xo,Mo.Header=jo,Mo.Title=ko,Mo.Footer=No,Mo.Dialog=Oo,Mo.TRANSITION_DURATION=300,Mo.BACKDROP_TRANSITION_DURATION=150;var Io=Mo,Do=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.children,c=e.as,u=void 0===c?"div":c,d=a(e,["bsPrefix","className","children","as"]);return n=E(n,"nav-item"),l.a.createElement(u,r({},d,{ref:t,className:i()(o,n)}),s)}));Do.displayName="NavItem";var Fo=Do,Ao={disabled:!1,as:ke},Lo=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.disabled,s=e.className,c=e.href,u=e.eventKey,d=e.onSelect,f=e.as,p=a(e,["bsPrefix","disabled","className","href","eventKey","onSelect","as"]);return n=E(n,"nav-link"),l.a.createElement(_a,r({},p,{href:c,ref:t,eventKey:u,as:f,disabled:o,onSelect:d,className:i()(s,n,o&&"disabled")}))}));Lo.displayName="NavLink",Lo.defaultProps=Ao;var Bo=Lo,Ko=l.a.forwardRef((function(e,t){var n,o,c,u=m(e,{activeKey:"onSelect"}),d=u.as,f=void 0===d?"div":d,p=u.bsPrefix,v=u.variant,b=u.fill,h=u.justify,g=u.navbar,y=u.className,x=u.children,w=u.activeKey,O=a(u,["as","bsPrefix","variant","fill","justify","navbar","className","children","activeKey"]),N=E(p,"nav"),C=!1,P=Object(s.useContext)(Cr),j=Object(s.useContext)(Xe);return P?(o=P.bsPrefix,C=null==g||g):j&&(c=j.cardHeaderBsPrefix),l.a.createElement(Ba,r({as:f,ref:t,activeKey:w,className:i()(y,(n={},n[N]=!C,n[o+"-nav"]=C,n[c+"-"+v]=!!c,n[N+"-"+v]=!!v,n[N+"-fill"]=b,n[N+"-justified"]=h,n))},O),x)}));Ko.displayName="Nav",Ko.defaultProps={justify:!1,fill:!1},Ko.Item=Fo,Ko.Link=Bo;var _o=Ko,Ho=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.as,c=a(e,["bsPrefix","className","as"]);n=E(n,"navbar-brand");var u=s||(c.href?"a":"span");return l.a.createElement(u,r({},c,{ref:t,className:i()(o,n)}))}));Ho.displayName="NavbarBrand";var zo=Ho,Vo=l.a.forwardRef((function(e,t){var n=e.children,o=e.bsPrefix,i=a(e,["children","bsPrefix"]);return o=E(o,"navbar-collapse"),l.a.createElement(Cr.Consumer,null,(function(e){return l.a.createElement(le,r({in:!(!e||!e.expanded)},i),l.a.createElement("div",{ref:t,className:o},n))}))}));Vo.displayName="NavbarCollapse";var qo=Vo,Uo=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.children,u=e.label,d=e.as,f=void 0===d?"button":d,p=e.onClick,m=a(e,["bsPrefix","className","children","label","as","onClick"]);n=E(n,"navbar-toggler");var v=Object(s.useContext)(Cr)||{},b=v.onToggle,h=v.expanded,g=ve((function(e){p&&p(e),b&&b()}));return"button"===f&&(m.type="button"),l.a.createElement(f,r({},m,{ref:t,onClick:g,"aria-label":u,className:i()(o,n,!h&&"collapsed")}),c||l.a.createElement("span",{className:n+"-icon"}))}));Uo.displayName="NavbarToggle",Uo.defaultProps={label:"Toggle navigation"};var Wo=Uo,Go=Ce("navbar-text",{Component:"span"}),Xo=l.a.forwardRef((function(e,t){var n=m(e,{expanded:"onToggle"}),o=n.bsPrefix,c=n.expand,u=n.variant,d=n.bg,f=n.fixed,p=n.sticky,v=n.className,b=n.children,h=n.as,g=void 0===h?"nav":h,y=n.expanded,x=n.onToggle,w=n.onSelect,O=n.collapseOnSelect,C=a(n,["bsPrefix","expand","variant","bg","fixed","sticky","className","children","as","expanded","onToggle","onSelect","collapseOnSelect"]),P=E(o,"navbar"),j=Object(s.useCallback)((function(){w&&w.apply(void 0,arguments),O&&y&&x&&x(!1)}),[w,O,y,x]);void 0===C.role&&"nav"!==g&&(C.role="navigation");var k=P+"-expand";"string"==typeof c&&(k=k+"-"+c);var R=Object(s.useMemo)((function(){return{onToggle:function(){return x&&x(!y)},bsPrefix:P,expanded:!!y}}),[P,y,x]);return l.a.createElement(Cr.Provider,{value:R},l.a.createElement(N.Provider,{value:j},l.a.createElement(g,r({ref:t},C,{className:i()(v,P,c&&k,u&&P+"-"+u,d&&"bg-"+d,p&&"sticky-"+p,f&&"fixed-"+f)}),b)))}));Xo.defaultProps={expand:!0,variant:"light",collapseOnSelect:!1},Xo.displayName="Navbar",Xo.Brand=zo,Xo.Toggle=Wo,Xo.Collapse=qo,Xo.Text=Go;var $o=Xo,Yo={id:W.a.any,onClick:W.a.func,title:W.a.node.isRequired,disabled:W.a.bool,active:W.a.bool,menuRole:W.a.string,renderMenuOnMount:W.a.bool,rootCloseEvent:W.a.string,bsPrefix:W.a.string},Jo=l.a.forwardRef((function(e,t){var n=e.id,o=e.title,i=e.children,s=e.bsPrefix,c=e.rootCloseEvent,u=e.menuRole,d=e.disabled,f=e.active,p=e.renderMenuOnMount,m=a(e,["id","title","children","bsPrefix","rootCloseEvent","menuRole","disabled","active","renderMenuOnMount"]);return l.a.createElement(_r,r({ref:t},m,{as:Fo}),l.a.createElement(_r.Toggle,{id:n,eventKey:null,active:f,disabled:d,childBsPrefix:s,as:Bo},o),l.a.createElement(_r.Menu,{role:u,renderOnMount:p,rootCloseEvent:c},i))}));Jo.displayName="NavDropdown",Jo.propTypes=Yo,Jo.Item=_r.Item,Jo.ItemText=_r.ItemText,Jo.Divider=_r.Divider,Jo.Header=_r.Header;var Zo=Jo,Qo=l.a.forwardRef((function(e,t){var n=e.flip,o=e.offset,i=e.placement,c=e.containerPadding,u=void 0===c?5:c,d=e.popperConfig,f=void 0===d?{}:d,p=e.transition,m=Dt(),v=m[0],b=m[1],h=Dt(),g=h[0],y=h[1],x=Or(b,t),E=uo(e.container),w=uo(e.target),O=Object(s.useState)(!e.show),N=O[0],C=O[1],P=Xn(w,v,rr({placement:i,enableEvents:!!e.show,containerPadding:u||5,flip:n,offset:o,arrowElement:g,popperConfig:f})),j=P.styles,k=P.attributes,R=a(P,["styles","attributes"]);e.show?N&&C(!1):e.transition||N||C(!0);var T=e.show||p&&!N;if(tr(v,e.onHide,{disabled:!e.rootClose||e.rootCloseDisabled,clickTrigger:e.rootCloseEvent}),!T)return null;var S=e.children(r({},R,{show:!!e.show,props:r({},k.popper,{style:j.popper,ref:x}),arrowProps:r({},k.arrow,{style:j.arrow,ref:y})}));if(p){var M=e.onExit,I=e.onExiting,D=e.onEnter,F=e.onEntering,A=e.onEntered;S=l.a.createElement(p,{in:e.show,appear:!0,onExit:M,onExiting:I,onExited:function(){C(!0),e.onExited&&e.onExited.apply(e,arguments)},onEnter:D,onEntering:F,onEntered:A},S)}return E?X.a.createPortal(S,E):null}));Qo.displayName="Overlay",Qo.propTypes={show:W.a.bool,placement:W.a.oneOf(ln),target:W.a.any,container:W.a.any,flip:W.a.bool,children:W.a.func.isRequired,containerPadding:W.a.number,popperConfig:W.a.object,rootClose:W.a.bool,rootCloseEvent:W.a.oneOf(["click","mousedown"]),rootCloseDisabled:W.a.bool,onHide:function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];var a;return e.rootClose?(a=W.a.func).isRequired.apply(a,[e].concat(n)):W.a.func.apply(W.a,[e].concat(n))},transition:W.a.elementType,onEnter:W.a.func,onEntering:W.a.func,onEntered:W.a.func,onExit:W.a.func,onExiting:W.a.func,onExited:W.a.func};var ei=Qo,ti={transition:ge,rootClose:!1,show:!1,placement:"top"};function ni(e){var t=e.children,n=e.transition,o=e.popperConfig,c=void 0===o?{}:o,u=a(e,["children","transition","popperConfig"]),d=Object(s.useRef)({}),f=Rr(),p=f[0],m=f[1],v=!0===n?ge:n||null;return l.a.createElement(ei,r({},u,{ref:p,popperConfig:r({},c,{modifiers:m.concat(c.modifiers||[])}),transition:v}),(function(e){var o,s=e.props,c=e.arrowProps,u=e.show,f=e.update,p=(e.forceUpdate,e.placement),m=e.state,v=a(e,["props","arrowProps","show","update","forceUpdate","placement","state"]);!function(e,t){var n=e.ref,r=t.ref;e.ref=n.__wrapped||(n.__wrapped=function(e){return n(Zn(e))}),t.ref=r.__wrapped||(r.__wrapped=function(e){return r(Zn(e))})}(s,c);var b=Object.assign(d.current,{state:m,scheduleUpdate:f,placement:p,outOfBoundaries:(null==m||null==(o=m.modifiersData.hide)?void 0:o.isReferenceHidden)||!1});return"function"==typeof t?t(r({},v,s,{placement:p,show:u,popper:b,arrowProps:c})):l.a.cloneElement(t,r({},v,s,{placement:p,arrowProps:c,popper:b,className:i()(t.props.className,!n&&u&&"show"),style:r({},t.props.style,s.style)}))}))}ni.defaultProps=ti;var ri=ni,ai=function(e){function t(){return e.apply(this,arguments)||this}return v(t,e),t.prototype.render=function(){return this.props.children},t}(l.a.Component);function oi(e,t,n){var r=t[0],a=r.currentTarget,o=r.relatedTarget||r.nativeEvent[n];o&&o===a||$n(a,o)||e.apply(void 0,t)}function ii(e){var t=e.trigger,n=e.overlay,o=e.children,i=e.popperConfig,c=void 0===i?{}:i,u=e.show,d=e.defaultShow,f=void 0!==d&&d,m=e.onToggle,v=e.delay,b=e.placement,h=e.flip,g=void 0===h?b&&-1!==b.indexOf("auto"):h,y=a(e,["trigger","overlay","children","popperConfig","show","defaultShow","onToggle","delay","placement","flip"]),x=Object(s.useRef)(null),E=bt(),w=Object(s.useRef)(""),O=p(u,f,m),N=O[0],C=O[1],P=function(e){return e&&"object"==typeof e?e:{show:e,hide:e}}(v),j="function"!=typeof o?l.a.Children.only(o).props:{},k=j.onFocus,R=j.onBlur,T=j.onClick,S=Object(s.useCallback)((function(){return Zn(x.current)}),[]),M=Object(s.useCallback)((function(){E.clear(),w.current="show",P.show?E.set((function(){"show"===w.current&&C(!0)}),P.show):C(!0)}),[P.show,C,E]),I=Object(s.useCallback)((function(){E.clear(),w.current="hide",P.hide?E.set((function(){"hide"===w.current&&C(!1)}),P.hide):C(!1)}),[P.hide,C,E]),D=Object(s.useCallback)((function(){M();for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];null==k||k.apply(void 0,t)}),[M,k]),F=Object(s.useCallback)((function(){I();for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];null==R||R.apply(void 0,t)}),[I,R]),A=Object(s.useCallback)((function(){C(!N),T&&T.apply(void 0,arguments)}),[T,C,N]),L=Object(s.useCallback)((function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];oi(M,t,"fromElement")}),[M]),B=Object(s.useCallback)((function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];oi(I,t,"toElement")}),[I]),K=null==t?[]:[].concat(t),_={};return-1!==K.indexOf("click")&&(_.onClick=A),-1!==K.indexOf("focus")&&(_.onFocus=D,_.onBlur=F),-1!==K.indexOf("hover")&&(_.onMouseOver=L,_.onMouseOut=B),l.a.createElement(l.a.Fragment,null,"function"==typeof o?o(r({},_,{ref:x})):l.a.createElement(ai,{ref:x},Object(s.cloneElement)(o,_)),l.a.createElement(ri,r({},y,{show:N,onHide:I,flip:g,placement:b,popperConfig:c,target:S}),n))}ii.defaultProps={defaultShow:!1,trigger:["hover","focus"]};var si=ii,li=l.a.forwardRef((function(e,t){var n=e.active,o=e.disabled,s=e.className,c=e.style,u=e.activeLabel,d=e.children,f=a(e,["active","disabled","className","style","activeLabel","children"]),p=n||o?"span":ke;return l.a.createElement("li",{ref:t,style:c,className:i()(s,"page-item",{active:n,disabled:o})},l.a.createElement(p,r({className:"page-link",disabled:o},f),d,n&&u&&l.a.createElement("span",{className:"sr-only"},u)))}));li.defaultProps={active:!1,disabled:!1,activeLabel:"(current)"},li.displayName="PageItem";var ci=li;function ui(e,t,n){function r(e){var r=e.children,o=a(e,["children"]);return l.a.createElement(li,o,l.a.createElement("span",{"aria-hidden":"true"},r||t),l.a.createElement("span",{className:"sr-only"},n))}return void 0===n&&(n=e),r.displayName=e,r}var di=ui("First","«"),fi=ui("Prev","‹","Previous"),pi=ui("Ellipsis","…","More"),mi=ui("Next","›"),vi=ui("Last","»"),bi=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.children,c=e.size,u=a(e,["bsPrefix","className","children","size"]),d=E(n,"pagination");return l.a.createElement("ul",r({ref:t},u,{className:i()(o,d,c&&d+"-"+c)}),s)}));bi.First=di,bi.Prev=fi,bi.Ellipsis=pi,bi.Item=ci,bi.Next=mi,bi.Last=vi;var hi=bi,gi=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"div":n,s=e.bsPrefix,c=e.className,u=e.children,d=a(e,["as","bsPrefix","className","children"]);return s=E(s,"popover-header"),l.a.createElement(o,r({ref:t},d,{className:i()(s,c)}),u)})),yi=l.a.forwardRef((function(e,t){var n=e.as,o=void 0===n?"div":n,s=e.bsPrefix,c=e.className,u=e.children,d=a(e,["as","bsPrefix","className","children"]);return s=E(s,"popover-body"),l.a.createElement(o,r({ref:t},d,{className:i()(c,s)}),u)})),xi=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.placement,s=e.className,c=e.style,u=e.children,d=e.content,f=e.arrowProps,p=(e.popper,e.show,a(e,["bsPrefix","placement","className","style","children","content","arrowProps","popper","show"])),m=E(n,"popover"),v=((null==o?void 0:o.split("-"))||[])[0];return l.a.createElement("div",r({ref:t,role:"tooltip",style:c,"x-placement":v,className:i()(s,m,v&&"bs-popover-"+v)},p),l.a.createElement("div",r({className:"arrow"},f)),d?l.a.createElement(yi,null,u):u)}));xi.defaultProps={placement:"right"},xi.Title=gi,xi.Content=yi;var Ei=xi;function wi(e,t,n){var r=(e-t)/(n-t)*100;return Math.round(1e3*r)/1e3}function Oi(e,t){var n,o=e.min,s=e.now,c=e.max,u=e.label,d=e.srOnly,f=e.striped,p=e.animated,m=e.className,v=e.style,b=e.variant,h=e.bsPrefix,g=a(e,["min","now","max","label","srOnly","striped","animated","className","style","variant","bsPrefix"]);return l.a.createElement("div",r({ref:t},g,{role:"progressbar",className:i()(m,h+"-bar",(n={},n["bg-"+b]=b,n[h+"-bar-animated"]=p,n[h+"-bar-striped"]=p||f,n)),style:r({width:wi(s,o,c)+"%"},v),"aria-valuenow":s,"aria-valuemin":o,"aria-valuemax":c}),d?l.a.createElement("span",{className:"sr-only"},u):u)}var Ni=l.a.forwardRef((function(e,t){var n=e.isChild,o=a(e,["isChild"]);if(o.bsPrefix=E(o.bsPrefix,"progress"),n)return Oi(o,t);var c=o.min,u=o.now,d=o.max,f=o.label,p=o.srOnly,m=o.striped,v=o.animated,b=o.bsPrefix,h=o.variant,g=o.className,y=o.children,x=a(o,["min","now","max","label","srOnly","striped","animated","bsPrefix","variant","className","children"]);return l.a.createElement("div",r({ref:t},x,{className:i()(g,b)}),y?xt(y,(function(e){return Object(s.cloneElement)(e,{isChild:!0})})):Oi({min:c,now:u,max:d,label:f,srOnly:p,striped:m,animated:v,bsPrefix:b,variant:h},t))}));Ni.displayName="ProgressBar",Ni.defaultProps={min:0,max:100,animated:!1,isChild:!1,srOnly:!1,striped:!1};var Ci=Ni,Pi=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.children,c=e.aspectRatio,u=a(e,["bsPrefix","className","children","aspectRatio"]),d=E(n,"embed-responsive"),f=l.a.Children.only(s);return l.a.createElement("div",r({ref:t},u,{className:i()(d,o,c&&d+"-"+c)}),l.a.cloneElement(f,{className:i()(f.props.className,d+"-item")}))}));Pi.defaultProps={aspectRatio:"1by1"};var ji=Pi,ki=["xl","lg","md","sm","xs"],Ri=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.noGutters,c=e.as,u=void 0===c?"div":c,d=a(e,["bsPrefix","className","noGutters","as"]),f=E(n,"row"),p=f+"-cols",m=[];return ki.forEach((function(e){var t,n=d[e];delete d[e];var r="xs"!==e?"-"+e:"";null!=(t=null!=n&&"object"==typeof n?n.cols:n)&&m.push(""+p+r+"-"+t)})),l.a.createElement(u,r({ref:t},d,{className:i.a.apply(void 0,[o,f,s&&"no-gutters"].concat(m))}))}));Ri.displayName="Row",Ri.defaultProps={noGutters:!1};var Ti=Ri,Si=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.variant,s=e.animation,c=e.size,u=e.children,d=e.as,f=void 0===d?"div":d,p=e.className,m=a(e,["bsPrefix","variant","animation","size","children","as","className"]),v=(n=E(n,"spinner"))+"-"+s;return l.a.createElement(f,r({ref:t},m,{className:i()(p,v,c&&v+"-"+c,o&&"text-"+o)}),u)}));Si.displayName="Spinner";var Mi=Si,Ii={id:W.a.any,toggleLabel:W.a.string,href:W.a.string,target:W.a.string,onClick:W.a.func,title:W.a.node.isRequired,type:W.a.string,disabled:W.a.bool,menuAlign:Sr,menuRole:W.a.string,renderMenuOnMount:W.a.bool,rootCloseEvent:W.a.string,bsPrefix:W.a.string,variant:W.a.string,size:W.a.string},Di=l.a.forwardRef((function(e,t){var n=e.id,o=e.bsPrefix,i=e.size,s=e.variant,c=e.title,u=e.type,d=e.toggleLabel,f=e.children,p=e.onClick,m=e.href,v=e.target,b=e.menuAlign,h=e.menuRole,g=e.renderMenuOnMount,y=e.rootCloseEvent,x=a(e,["id","bsPrefix","size","variant","title","type","toggleLabel","children","onClick","href","target","menuAlign","menuRole","renderMenuOnMount","rootCloseEvent"]);return l.a.createElement(_r,r({ref:t},x,{as:qe}),l.a.createElement(ze,{size:i,variant:s,disabled:x.disabled,bsPrefix:o,href:m,target:v,onClick:p,type:u},c),l.a.createElement(_r.Toggle,{split:!0,id:n?n.toString():void 0,size:i,variant:s,disabled:x.disabled,childBsPrefix:o},l.a.createElement("span",{className:"sr-only"},d)),l.a.createElement(_r.Menu,{align:b,role:h,renderOnMount:g,rootCloseEvent:y},f))}));Di.propTypes=Ii,Di.defaultProps={toggleLabel:"Toggle dropdown",type:"button"},Di.displayName="SplitButton";var Fi=Di,Ai=function(e){var t=m(e,{activeKey:"onSelect"}),n=t.id,r=t.generateChildId,a=t.onSelect,o=t.activeKey,i=t.transition,c=t.mountOnEnter,u=t.unmountOnExit,d=t.children,f=Object(s.useMemo)((function(){return r||function(e,t){return n?n+"-"+t+"-"+e:null}}),[n,r]),p=Object(s.useMemo)((function(){return{onSelect:a,activeKey:o,transition:i,mountOnEnter:c||!1,unmountOnExit:u||!1,getControlledId:function(e){return f(e,"tabpane")},getControllerId:function(e){return f(e,"tab")}}}),[a,o,i,c,u,f]);return l.a.createElement(Aa.Provider,{value:p},l.a.createElement(N.Provider,{value:a||null},d))},Li=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.as,s=void 0===o?"div":o,c=e.className,u=a(e,["bsPrefix","as","className"]),d=E(n,"tab-content");return l.a.createElement(s,r({ref:t},u,{className:i()(c,d)}))}));var Bi=l.a.forwardRef((function(e,t){var n=function(e){var t=Object(s.useContext)(Aa);if(!t)return e;var n=t.activeKey,o=t.getControlledId,i=t.getControllerId,l=a(t,["activeKey","getControlledId","getControllerId"]),c=!1!==e.transition&&!1!==l.transition,u=O(e.eventKey);return r({},e,{active:null==e.active&&null!=u?O(n)===u:e.active,id:o(e.eventKey),"aria-labelledby":i(e.eventKey),transition:c&&(e.transition||l.transition||ge),mountOnEnter:null!=e.mountOnEnter?e.mountOnEnter:l.mountOnEnter,unmountOnExit:null!=e.unmountOnExit?e.unmountOnExit:l.unmountOnExit})}(e),o=n.bsPrefix,c=n.className,u=n.active,d=n.onEnter,f=n.onEntering,p=n.onEntered,m=n.onExit,v=n.onExiting,b=n.onExited,h=n.mountOnEnter,g=n.unmountOnExit,y=n.transition,x=n.as,w=void 0===x?"div":x,C=(n.eventKey,a(n,["bsPrefix","className","active","onEnter","onEntering","onEntered","onExit","onExiting","onExited","mountOnEnter","unmountOnExit","transition","as","eventKey"])),P=E(o,"tab-pane");if(!u&&!y&&g)return null;var j=l.a.createElement(w,r({},C,{ref:t,role:"tabpanel","aria-hidden":!u,className:i()(c,P,{active:u})}));return y&&(j=l.a.createElement(y,{in:u,onEnter:d,onEntering:f,onEntered:p,onExit:m,onExiting:v,onExited:b,mountOnEnter:h,unmountOnExit:g},j)),l.a.createElement(Aa.Provider,{value:null},l.a.createElement(N.Provider,{value:null},j))}));Bi.displayName="TabPane";var Ki=Bi,_i=function(e){function t(){return e.apply(this,arguments)||this}return v(t,e),t.prototype.render=function(){throw new Error("ReactBootstrap: The `Tab` component is not meant to be rendered! It's an abstract component that is only valid as a direct Child of the `Tabs` Component. For custom tabs components use TabPane and TabsContainer directly")},t}(l.a.Component);_i.Container=Ai,_i.Content=Li,_i.Pane=Ki;var Hi=_i,zi=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,s=e.striped,c=e.bordered,u=e.borderless,d=e.hover,f=e.size,p=e.variant,m=e.responsive,v=a(e,["bsPrefix","className","striped","bordered","borderless","hover","size","variant","responsive"]),b=E(n,"table"),h=i()(o,b,p&&b+"-"+p,f&&b+"-"+f,s&&b+"-striped",c&&b+"-bordered",u&&b+"-borderless",d&&b+"-hover"),g=l.a.createElement("table",r({},v,{className:h,ref:t}));if(m){var y=b+"-responsive";return"string"==typeof m&&(y=y+"-"+m),l.a.createElement("div",{className:y},g)}return g}));function Vi(e){var t=e.props,n=t.title,r=t.eventKey,a=t.disabled,o=t.tabClassName,i=t.id;return null==n?null:l.a.createElement(Fo,{as:Bo,eventKey:r,disabled:a,id:i,className:o},n)}var qi=function(e){var t=m(e,{activeKey:"onSelect"}),n=t.id,o=t.onSelect,i=t.transition,s=t.mountOnEnter,c=t.unmountOnExit,u=t.children,d=t.activeKey,f=void 0===d?function(e){var t;return Et(e,(function(e){null==t&&(t=e.props.eventKey)})),t}(u):d,p=a(t,["id","onSelect","transition","mountOnEnter","unmountOnExit","children","activeKey"]);return l.a.createElement(Ai,{id:n,activeKey:f,onSelect:o,transition:i,mountOnEnter:s,unmountOnExit:c},l.a.createElement(_o,r({},p,{role:"tablist",as:"nav"}),xt(u,Vi)),l.a.createElement(Li,null,xt(u,(function(e){var t=r({},e.props);return delete t.title,delete t.disabled,delete t.tabClassName,l.a.createElement(Ki,t)}))))};qi.defaultProps={variant:"tabs",mountOnEnter:!1,unmountOnExit:!1},qi.displayName="Tabs";var Ui=qi,Wi=l.a.createContext({onClose:function(){}}),Gi=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.closeLabel,c=e.closeButton,u=e.className,d=e.children,f=a(e,["bsPrefix","closeLabel","closeButton","className","children"]);n=E(n,"toast-header");var p=Object(s.useContext)(Wi),m=ve((function(e){p&&p.onClose&&p.onClose(e)}));return l.a.createElement("div",r({ref:t},f,{className:i()(n,u)}),d,c&&l.a.createElement(Ee,{label:o,onClick:m,className:"ml-2 mb-1","data-dismiss":"toast"}))}));Gi.displayName="ToastHeader",Gi.defaultProps={closeLabel:"Close",closeButton:!0};var Xi=Gi,$i=Ce("toast-body"),Yi=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.className,c=e.children,u=e.transition,d=void 0===u?ge:u,f=e.show,p=void 0===f||f,m=e.animation,v=void 0===m||m,b=e.delay,h=void 0===b?3e3:b,g=e.autohide,y=void 0!==g&&g,x=e.onClose,w=a(e,["bsPrefix","className","children","transition","show","animation","delay","autohide","onClose"]);n=E(n,"toast");var O=Object(s.useRef)(h),N=Object(s.useRef)(x);Object(s.useEffect)((function(){O.current=h,N.current=x}),[h,x]);var C=bt(),P=!(!y||!p),j=Object(s.useCallback)((function(){P&&(null==N.current||N.current())}),[P]);Object(s.useEffect)((function(){C.set(j,O.current)}),[C,j]);var k=Object(s.useMemo)((function(){return{onClose:x}}),[x]),R=!(!d||!v),T=l.a.createElement("div",r({},w,{ref:t,className:i()(n,o,!R&&(p?"show":"hide")),role:"alert","aria-live":"assertive","aria-atomic":"true"}),c);return l.a.createElement(Wi.Provider,{value:k},R&&d?l.a.createElement(d,{in:p,unmountOnExit:!0},T):T)}));Yi.displayName="Toast";var Ji=Object.assign(Yi,{Body:$i,Header:Xi}),Zi=function(){},Qi=l.a.forwardRef((function(e,t){var n=e.children,o=e.name,c=e.className,u=e.checked,d=e.type,f=e.onChange,p=e.value,m=e.disabled,v=e.inputRef,b=a(e,["children","name","className","checked","type","onChange","value","disabled","inputRef"]),h=Object(s.useState)(!1),g=h[0],y=h[1],x=Object(s.useCallback)((function(e){"INPUT"===e.target.tagName&&y(!0)}),[]),E=Object(s.useCallback)((function(e){"INPUT"===e.target.tagName&&y(!1)}),[]);return l.a.createElement(ze,r({},b,{ref:t,className:i()(c,g&&"focus",m&&"disabled"),type:void 0,active:!!u,as:"label"}),l.a.createElement("input",{name:o,type:d,value:p,ref:v,autoComplete:"off",checked:!!u,disabled:!!m,onFocus:x,onBlur:E,onChange:f||Zi}),n)}));Qi.displayName="ToggleButton";var es=Qi,ts=l.a.forwardRef((function(e,t){var n=m(e,{value:"onChange"}),o=n.children,i=n.type,s=n.name,c=n.value,d=n.onChange,f=a(n,["children","type","name","value","onChange"]),p=function(){return null==c?[]:[].concat(c)};return"radio"!==i||s||u()(!1),l.a.createElement(qe,r({},f,{ref:t,toggle:!0}),xt(o,(function(e){var t=p(),n=e.props,r=n.value,a=n.onChange;return l.a.cloneElement(e,{type:i,name:e.name||s,checked:-1!==t.indexOf(r),onChange:te(a,(function(e){return function(e,t){if(d){var n=p(),r=-1!==n.indexOf(e);"radio"!==i?d(r?n.filter((function(t){return t!==e})):[].concat(n,[e]),t):!r&&d&&d(e,t)}}(r,e)}))})})))}));ts.defaultProps={type:"radio",vertical:!1},ts.Button=es;var ns=ts,rs=l.a.forwardRef((function(e,t){var n=e.bsPrefix,o=e.placement,s=e.className,c=e.style,u=e.children,d=e.arrowProps,f=(e.popper,e.show,a(e,["bsPrefix","placement","className","style","children","arrowProps","popper","show"]));n=E(n,"tooltip");var p=((null==o?void 0:o.split("-"))||[])[0];return l.a.createElement("div",r({ref:t,style:c,role:"tooltip","x-placement":p,className:i()(s,n,"bs-tooltip-"+p)},f),l.a.createElement("div",r({className:"arrow"},d)),l.a.createElement("div",{className:n+"-inner"},u))}));rs.defaultProps={placement:"right"},rs.displayName="Tooltip";var as=rs}])}));
|
import ButtonDropdowns from './ButtonDropdowns';
import ButtonGroups from './ButtonGroups';
import Buttons from './Buttons';
import BrandButtons from './BrandButtons';
export {
ButtonDropdowns, ButtonGroups, Buttons, BrandButtons
}
|
load("201224b0d1c296b45befd2285e95dd42.js");
// |jit-test| error:recursion
x = /x/;
z = [];
y = Object.defineProperty(z, "valueOf", {
get: function() {
+y;
for (var i = 0; i < 1; i++) {
a = x.exec(0);
}
}
})
z + '';
|
'use strict';
const dummySubscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
var authorizationToken = null;
var subscriptions = null;
var mpnIdMap = {};
console.log('[Azure Partner Help Extention] start script.js');
var port = chrome.runtime.connect( { name: "my-background-port"} );
// This delay process is important to add elements on Azure portal for delay read.
function showMessageOnAzurePortalTopLoop() {
var elem = jQuery('div.fxs-startboard-layout.fxs-flowlayout');
if( elem.length > 0 ){
port.postMessage({name: "get-subscriptions-accesstoken"});
port.onMessage.addListener( response => {
// console.log('[Azure Partner Help Extention] returned values are below');
if(response.name == "get-access-function"){
// take authorizationToken from background
authorizationToken = response.authorizationToken;
subscriptions = response.subscriptions;
for(var i=0; i<response.subscriptions.length; i++)
{
port.postMessage({
name: "get-mpnids-function",
subscriptionId : subscriptions[i].subscriptionId
});
}
}else if(response.name == "get-mpnids-function"){
//console.log("################################# showMessageOnAzurePortalTopLoop()#get-mpnids-function start");
//console.log(response);
mpnIdMap[response.subscriptionId] = {
partnerId : response.partnerId,
partnerName : response.partnerName
};
console.log(mpnIdMap);
//console.log("################################# showMessageOnAzurePortalTopLoop()#get-mpnids-function end");
}
});
}else{
setTimeout( () => showMessageOnAzurePortalTopLoop(), 1000);
}
}
showMessageOnAzurePortalTopLoop();
function doURICheckLoop() {
if(window.location.href.indexOf('blade/Microsoft_Azure_Billing/SubscriptionsBlade') != -1
){
doUpdateSubscriptionlist();
}
setTimeout( () => doURICheckLoop(), 1000);
}
doURICheckLoop();
function doUpdateSubscriptionlist(){
// console.log('[Azure Partner Help Extention] doUpdateSubscriptionlist()')
// first element is header
const resourceArray = jQuery('div.azc-grid-tableContainer.azc-br-muted table tr:not(:first)');
resourceArray.each( (index, elem) => {
var subscirptionIdElem = jQuery(elem).find('td.azc-grid-cell.azc-br-muted:nth-child(3)');
const subscriptionIdText = jQuery(subscirptionIdElem).text();
const subscriptionId = subscriptionIdText.substring(0, dummySubscriptionId.length);
if(mpnIdMap[subscriptionId]){
var updateText = subscriptionId + " - " + mpnIdMap[subscriptionId].partnerName;
jQuery(subscirptionIdElem).text(updateText);
// console.log("[Azure Partner Help Extention] doUpdateSubscriptionlist(): " + updateText);
// There are no partners on this subscription or this extension hasn't still added a link into this DOM element
}
/*
else if( mpnIdMap[subscriptionId] == null && subscriptionIdText.length == subscriptionId.length){
var linkElem = jQuery("<a class='my-azure-partner-help-extension'></a>").text("Enable Partner Admin Link with your MPN ID");
linkElem.click( function (){
port.postMessage({
name: "set-mpnid-function",
subscriptionId : subscriptionId,
partnerId : "1316820" //mpnIdMap[subscriptionId].partnerId
});
});
jQuery(subscirptionIdElem).append(linkElem);
console.log("[Azure Partner Help Extention] doUpdateSubscriptionlist(): add a link on " + jQuery(subscirptionIdElem).text());
}
*/
//console.log("==================================================");
//console.log(subscriptionId);
//console.log(subscriptionIdText);
//console.log(mpnIdMap);
//console.log(mpnIdMap[subscriptionId]);
//if(mpnIdMap[subscriptionId]) console.log(mpnIdMap[subscriptionId].partnerName);
//if(mpnIdMap[subscriptionId]) console.log(subscriptionId.includes(mpnIdMap[subscriptionId].partnerName));
});
}
|
/* Flot plugin for selecting regions of a plot.
Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.
The plugin supports these options:
selection: {
mode: null or "x" or "y" or "xy",
color: color,
shape: "round" or "miter" or "bevel",
minSize: number of pixels
}
Selection support is enabled by setting the mode to one of "x", "y" or "xy".
In "x" mode, the user will only be able to specify the x range, similarly for
"y" mode. For "xy", the selection becomes a rectangle where both ranges can be
specified. "color" is color of the selection (if you need to change the color
later on, you can get to it with plot.getOptions().selection.color). "shape"
is the shape of the corners of the selection.
"minSize" is the minimum size a selection can be in pixels. This value can
be customized to determine the smallest size a selection can be and still
have the selection rectangle be displayed. When customizing this value, the
fact that it refers to pixels, not axis units must be taken into account.
Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
minute, setting "minSize" to 1 will not make the minimum selection size 1
minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
"plotunselected" events from being fired when the user clicks the mouse without
dragging.
When selection support is enabled, a "plotselected" event will be emitted on
the DOM element you passed into the plot function. The event handler gets a
parameter with the ranges selected on the axes, like this:
placeholder.bind( "plotselected", function( event, ranges ) {
alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
// similar for yaxis - with multiple axes, the extra ones are in
// x2axis, x3axis, ...
});
The "plotselected" event is only fired when the user has finished making the
selection. A "plotselecting" event is fired during the process with the same
parameters as the "plotselected" event, in case you want to know what's
happening while it's happening,
A "plotunselected" event with no arguments is emitted when the user clicks the
mouse to remove the selection. As stated above, setting "minSize" to 0 will
destroy this behavior.
The plugin allso adds the following methods to the plot object:
- setSelection( ranges, preventEvent )
Set the selection rectangle. The passed in ranges is on the same form as
returned in the "plotselected" event. If the selection mode is "x", you
should put in either an xaxis range, if the mode is "y" you need to put in
an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
this:
setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
setSelection will trigger the "plotselected" event when called. If you don't
want that to happen, e.g. if you're inside a "plotselected" handler, pass
true as the second parameter. If you are using multiple axes, you can
specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
xaxis, the plugin picks the first one it sees.
- clearSelection( preventEvent )
Clear the selection rectangle. Pass in true to avoid getting a
"plotunselected" event.
- getSelection()
Returns the current selection in the same format as the "plotselected"
event. If there's currently no selection, the function returns null.
*/
(function ($) {
function init(plot) {
var selection = {
first: { x: -1, y: -1}, second: { x: -1, y: -1},
show: false,
active: false
};
// FIXME: The drag handling implemented here should be
// abstracted out, there's some similar code from a library in
// the navigation plugin, this should be massaged a bit to fit
// the Flot cases here better and reused. Doing this would
// make this plugin much slimmer.
var savedhandlers = {};
var mouseUpHandler = null;
function onMouseMove(e) {
if (selection.active) {
updateSelection(e);
plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
}
}
function onMouseDown(e) {
if (e.which != 1) // only accept left-click
return;
// cancel out any text selections
document.body.focus();
// prevent text selection and drag in old-school browsers
if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
savedhandlers.onselectstart = document.onselectstart;
document.onselectstart = function () { return false; };
}
if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
savedhandlers.ondrag = document.ondrag;
document.ondrag = function () { return false; };
}
setSelectionPos(selection.first, e);
selection.active = true;
// this is a bit silly, but we have to use a closure to be
// able to whack the same handler again
mouseUpHandler = function (e) { onMouseUp(e); };
$(document).one("mouseup", mouseUpHandler);
}
function onMouseUp(e) {
mouseUpHandler = null;
// revert drag stuff for old-school browsers
if (document.onselectstart !== undefined)
document.onselectstart = savedhandlers.onselectstart;
if (document.ondrag !== undefined)
document.ondrag = savedhandlers.ondrag;
// no more dragging
selection.active = false;
updateSelection(e);
if (selectionIsSane())
triggerSelectedEvent();
else {
// this counts as a clear
plot.getPlaceholder().trigger("plotunselected", [ ]);
plot.getPlaceholder().trigger("plotselecting", [ null ]);
}
return false;
}
function getSelection() {
if (!selectionIsSane())
return null;
if (!selection.show) return null;
var r = {}, c1 = selection.first, c2 = selection.second;
$.each(plot.getAxes(), function (name, axis) {
if (axis.used) {
var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]);
r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
}
});
return r;
}
function triggerSelectedEvent() {
var r = getSelection();
plot.getPlaceholder().trigger("plotselected", [ r ]);
// backwards-compat stuff, to be removed in future
if (r.xaxis && r.yaxis)
plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
}
function clamp(min, value, max) {
return value < min ? min: (value > max ? max: value);
}
function setSelectionPos(pos, e) {
var o = plot.getOptions();
var offset = plot.getPlaceholder().offset();
var plotOffset = plot.getPlotOffset();
pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
if (o.selection.mode == "y")
pos.x = pos == selection.first ? 0 : plot.width();
if (o.selection.mode == "x")
pos.y = pos == selection.first ? 0 : plot.height();
}
function updateSelection(pos) {
if (pos.pageX == null)
return;
setSelectionPos(selection.second, pos);
if (selectionIsSane()) {
selection.show = true;
plot.triggerRedrawOverlay();
}
else
clearSelection(true);
}
function clearSelection(preventEvent) {
if (selection.show) {
selection.show = false;
plot.triggerRedrawOverlay();
if (!preventEvent)
plot.getPlaceholder().trigger("plotunselected", [ ]);
}
}
// function taken from markings support in Flot
function extractRange(ranges, coord) {
var axis, from, to, key, axes = plot.getAxes();
for (var k in axes) {
axis = axes[k];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function setSelection(ranges, preventEvent) {
var axis, range, o = plot.getOptions();
if (o.selection.mode == "y") {
selection.first.x = 0;
selection.second.x = plot.width();
}
else {
range = extractRange(ranges, "x");
selection.first.x = range.axis.p2c(range.from);
selection.second.x = range.axis.p2c(range.to);
}
if (o.selection.mode == "x") {
selection.first.y = 0;
selection.second.y = plot.height();
}
else {
range = extractRange(ranges, "y");
selection.first.y = range.axis.p2c(range.from);
selection.second.y = range.axis.p2c(range.to);
}
selection.show = true;
plot.triggerRedrawOverlay();
if (!preventEvent && selectionIsSane())
triggerSelectedEvent();
}
function selectionIsSane() {
var minSize = plot.getOptions().selection.minSize;
return Math.abs(selection.second.x - selection.first.x) >= minSize &&
Math.abs(selection.second.y - selection.first.y) >= minSize;
}
plot.clearSelection = clearSelection;
plot.setSelection = setSelection;
plot.getSelection = getSelection;
plot.hooks.bindEvents.push(function(plot, eventHolder) {
var o = plot.getOptions();
if (o.selection.mode != null) {
eventHolder.mousemove(onMouseMove);
eventHolder.mousedown(onMouseDown);
}
});
plot.hooks.drawOverlay.push(function (plot, ctx) {
// draw selection
if (selection.show && selectionIsSane()) {
var plotOffset = plot.getPlotOffset();
var o = plot.getOptions();
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var c = $.color.parse(o.selection.color);
ctx.strokeStyle = c.scale('a', 0.8).toString();
ctx.lineWidth = 1;
ctx.lineJoin = o.selection.shape;
ctx.fillStyle = c.scale('a', 0.4).toString();
var x = Math.min(selection.first.x, selection.second.x) + 0.5,
y = Math.min(selection.first.y, selection.second.y) + 0.5,
w = Math.abs(selection.second.x - selection.first.x) - 1,
h = Math.abs(selection.second.y - selection.first.y) - 1;
ctx.fillRect(x, y, w, h);
ctx.strokeRect(x, y, w, h);
ctx.restore();
}
});
plot.hooks.shutdown.push(function (plot, eventHolder) {
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mousedown", onMouseDown);
if (mouseUpHandler)
$(document).unbind("mouseup", mouseUpHandler);
});
}
$.plot.plugins.push({
init: init,
options: {
selection: {
mode: null, // one of null, "x", "y" or "xy"
color: "#e8cfac",
shape: "round", // one of "round", "miter", or "bevel"
minSize: 5 // minimum number of pixels
}
},
name: 'selection',
version: '1.1'
});
})(jQuery);
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[245],{309:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return a})),n.d(t,"metadata",(function(){return s})),n.d(t,"rightToc",(function(){return c})),n.d(t,"default",(function(){return l}));var i=n(3),r=n(7),o=(n(0),n(442)),a={id:"kratos-identities-delete",title:"kratos identities delete",description:"kratos identities delete Delete identities by ID"},s={unversionedId:"cli/kratos-identities-delete",id:"cli/kratos-identities-delete",isDocsHomePage:!1,title:"kratos identities delete",description:"kratos identities delete Delete identities by ID",source:"@site/docs/cli/kratos-identities-delete.md",slug:"/cli/kratos-identities-delete",permalink:"/kratos/docs/next/cli/kratos-identities-delete",editUrl:"https://github.com/ory/kratos/edit/master/docs/docs/cli/kratos-identities-delete.md",version:"current",lastUpdatedBy:"aeneasr",lastUpdatedAt:1610376221,sidebar:"docs",previous:{title:"kratos identities",permalink:"/kratos/docs/next/cli/kratos-identities"},next:{title:"kratos identities get",permalink:"/kratos/docs/next/cli/kratos-identities-get"}},c=[{value:"kratos identities delete",id:"kratos-identities-delete",children:[{value:"Synopsis",id:"synopsis",children:[]},{value:"Examples",id:"examples",children:[]},{value:"Options",id:"options",children:[]},{value:"Options inherited from parent commands",id:"options-inherited-from-parent-commands",children:[]},{value:"SEE ALSO",id:"see-also",children:[]}]}],d={rightToc:c};function l(e){var t=e.components,n=Object(r.a)(e,["components"]);return Object(o.b)("wrapper",Object(i.a)({},d,n,{components:t,mdxType:"MDXLayout"}),Object(o.b)("h2",{id:"kratos-identities-delete"},"kratos identities delete"),Object(o.b)("p",null,"Delete identities by ID"),Object(o.b)("h3",{id:"synopsis"},"Synopsis"),Object(o.b)("p",null,"This command deletes one or more identities by ID. To delete an identity by some\nselector, e.g. the recovery email address, use the list command in combination\nwith jq."),Object(o.b)("p",null,"We have to admit, this is not easy if you don't speak jq fluently. What about\nopening an issue and telling us what predefined selectors you want to have?\n",Object(o.b)("a",Object(i.a)({parentName:"p"},{href:"https://github.com/ory/kratos/issues/new/choose"}),"https://github.com/ory/kratos/issues/new/choose")),Object(o.b)("pre",null,Object(o.b)("code",Object(i.a)({parentName:"pre"},{}),"kratos identities delete <id-0 [id-1 ...]> [flags]\n")),Object(o.b)("h3",{id:"examples"},"Examples"),Object(o.b)("pre",null,Object(o.b)("code",Object(i.a)({parentName:"pre"},{}),'To delete the identity with the recovery email address "foo@bar.com", run:\n\n $ kratos identities delete $(kratos identities list --format json | jq -r \'map(select(.recovery_addresses[].value == "foo@bar.com")) | .[].id\')\n')),Object(o.b)("h3",{id:"options"},"Options"),Object(o.b)("pre",null,Object(o.b)("code",Object(i.a)({parentName:"pre"},{})," -h, --help help for delete\n")),Object(o.b)("h3",{id:"options-inherited-from-parent-commands"},"Options inherited from parent commands"),Object(o.b)("pre",null,Object(o.b)("code",Object(i.a)({parentName:"pre"},{})," -e, --endpoint string The URL of ORY Kratos' Admin API. Alternatively set using the KRATOS_ADMIN_URL environmental variable.\n -f, --format string Set the output format. One of table, json, and json-pretty.\n -q, --quiet Be quiet with output printing.\n")),Object(o.b)("h3",{id:"see-also"},"SEE ALSO"),Object(o.b)("ul",null,Object(o.b)("li",{parentName:"ul"},Object(o.b)("a",Object(i.a)({parentName:"li"},{href:"kratos-identities"}),"kratos identities")," - Tools to interact with remote\nidentities")))}l.isMDXComponent=!0},442:function(e,t,n){"use strict";n.d(t,"a",(function(){return p})),n.d(t,"b",(function(){return m}));var i=n(0),r=n.n(i);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function s(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function c(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n,i,r={},o=Object.keys(e);for(i=0;i<o.length;i++)n=o[i],t.indexOf(n)>=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(i=0;i<o.length;i++)n=o[i],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}var d=r.a.createContext({}),l=function(e){var t=r.a.useContext(d),n=t;return e&&(n="function"==typeof e?e(t):s(s({},t),e)),n},p=function(e){var t=l(e.components);return r.a.createElement(d.Provider,{value:t},e.children)},u={inlineCode:"code",wrapper:function(e){var t=e.children;return r.a.createElement(r.a.Fragment,{},t)}},b=r.a.forwardRef((function(e,t){var n=e.components,i=e.mdxType,o=e.originalType,a=e.parentName,d=c(e,["components","mdxType","originalType","parentName"]),p=l(n),b=i,m=p["".concat(a,".").concat(b)]||p[b]||u[b]||o;return n?r.a.createElement(m,s(s({ref:t},d),{},{components:n})):r.a.createElement(m,s({ref:t},d))}));function m(e,t){var n=arguments,i=t&&t.mdxType;if("string"==typeof e||i){var o=n.length,a=new Array(o);a[0]=b;var s={};for(var c in t)hasOwnProperty.call(t,c)&&(s[c]=t[c]);s.originalType=e,s.mdxType="string"==typeof e?e:i,a[1]=s;for(var d=2;d<o;d++)a[d]=n[d];return r.a.createElement.apply(null,a)}return r.a.createElement.apply(null,n)}b.displayName="MDXCreateElement"}}]);
|
import popover from './popover.vue';
export default popover;
|
function(doc) {
if (doc._id.substr(0,2) == "o." && !doc.finished) {
emit(doc.timeModified,null);
}
}
|
/**
* @fileoverview Rule to disallow assignments to native objects or read-only global variables
* @author Ilya Volodin
* @deprecated in ESLint v3.3.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow assignments to native objects or read-only global variables",
category: "Best Practices",
recommended: false,
replacedBy: ["no-global-assign"]
},
deprecated: true,
schema: [
{
type: "object",
properties: {
exceptions: {
type: "array",
items: { type: "string" },
uniqueItems: true
}
},
additionalProperties: false
}
]
},
create(context) {
const config = context.options[0];
const exceptions = (config && config.exceptions) || [];
/**
* Reports write references.
* @param {Reference} reference - A reference to check.
* @param {int} index - The index of the reference in the references.
* @param {Reference[]} references - The array that the reference belongs to.
* @returns {void}
*/
function checkReference(reference, index, references) {
const identifier = reference.identifier;
if (reference.init === false &&
reference.isWrite() &&
// Destructuring assignments can have multiple default value,
// so possibly there are multiple writeable references for the same identifier.
(index === 0 || references[index - 1].identifier !== identifier)
) {
context.report({
node: identifier,
message: "Read-only global '{{name}}' should not be modified.",
data: identifier
});
}
}
/**
* Reports write references if a given variable is read-only builtin.
* @param {Variable} variable - A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
variable.references.forEach(checkReference);
}
}
return {
Program() {
const globalScope = context.getScope();
globalScope.variables.forEach(checkVariable);
}
};
}
};
|
'use strict';
// Declare app level module which depends on views, and components
angular
.module('myApp', [
'ngMaterial',
'ui.router',
'LocalStorageModule',
'angular-loading-bar',
'md.data.table',
'toaster',
'ngAnimate',
'directives',
'services',
'providers',
'login',
'easymongo',
'database',
'collection'
])
.config(['$locationProvider', '$urlRouterProvider','$httpProvider', urlRouterProvider]);
function urlRouterProvider($locationProvider, $urlRouterProvider, $httpProvider) {
$httpProvider.interceptors.push('requestInterceptor');
$urlRouterProvider.otherwise('/login');
};
|
'use strict'
var Parser = require('jsonparse')
, through = require('through')
/*
the value of this.stack that creationix's jsonparse has is weird.
it makes this code ugly, but his problem is way harder that mine,
so i'll forgive him.
*/
exports.parse = function (path, map) {
var header, footer
var parser = new Parser()
var stream = through(function (chunk) {
if('string' === typeof chunk)
chunk = new Buffer(chunk)
parser.write(chunk)
},
function (data) {
if(data)
stream.write(data)
if (header)
stream.emit('header', header)
if (footer)
stream.emit('footer', footer)
stream.queue(null)
})
if('string' === typeof path)
path = path.split('.').map(function (e) {
if (e === '$*')
return {emitKey: true}
else if (e === '*')
return true
else if (e === '') // '..'.split('.') returns an empty string
return {recurse: true}
else
return e
})
var count = 0, _key
if(!path || !path.length)
path = null
parser.onValue = function (value) {
if (!this.root)
stream.root = value
if(! path) return
var i = 0 // iterates on path
var j = 0 // iterates on stack
var emitKey = false;
var emitPath = false;
while (i < path.length) {
var key = path[i]
var c
j++
if (key && !key.recurse) {
c = (j === this.stack.length) ? this : this.stack[j]
if (!c) return
if (! check(key, c.key)) {
setHeaderFooter(c.key, value)
return
}
emitKey = !!key.emitKey;
emitPath = !!key.emitPath;
i++
} else {
i++
var nextKey = path[i]
if (! nextKey) return
while (true) {
c = (j === this.stack.length) ? this : this.stack[j]
if (!c) return
if (check(nextKey, c.key)) {
i++;
if (!Object.isFrozen(this.stack[j]))
this.stack[j].value = null
break
} else {
setHeaderFooter(c.key, value)
}
j++
}
}
}
// emit header
if (header) {
stream.emit('header', header);
header = false;
}
if (j !== this.stack.length) return
count ++
var actualPath = this.stack.slice(1).map(function(element) { return element.key }).concat([this.key])
var data = this.value[this.key]
if(null != data)
if(null != (data = map ? map(data, actualPath) : data)) {
if (emitKey || emitPath) {
data = { value: data };
if (emitKey)
data["key"] = this.key;
if (emitPath)
data["path"] = actualPath;
}
stream.queue(data)
}
delete this.value[this.key]
for(var k in this.stack)
if (!Object.isFrozen(this.stack[k]))
this.stack[k].value = null
}
parser._onToken = parser.onToken;
parser.onToken = function (token, value) {
parser._onToken(token, value);
if (this.stack.length === 0) {
if (stream.root) {
if(!path)
stream.queue(stream.root)
count = 0;
stream.root = null;
}
}
}
parser.onError = function (err) {
if(err.message.indexOf("at position") > -1)
err.message = "Invalid JSON (" + err.message + ")";
stream.emit('error', err)
}
return stream
function setHeaderFooter(key, value) {
// header has not been emitted yet
if (header !== false) {
header = header || {}
header[key] = value
}
// footer has not been emitted yet but header has
if (footer !== false && header === false) {
footer = footer || {}
footer[key] = value
}
}
}
function check (x, y) {
if ('string' === typeof x)
return y == x
else if (x && 'function' === typeof x.exec)
return x.exec(y)
else if ('boolean' === typeof x || 'object' === typeof x)
return x
else if ('function' === typeof x)
return x(y)
return false
}
exports.stringify = function (op, sep, cl, indent) {
indent = indent || 0
if (op === false){
op = ''
sep = '\n'
cl = ''
} else if (op == null) {
op = '[\n'
sep = '\n,\n'
cl = '\n]\n'
}
//else, what ever you like
var stream
, first = true
, anyData = false
stream = through(function (data) {
anyData = true
try {
var json = JSON.stringify(data, null, indent)
} catch (err) {
return stream.emit('error', err)
}
if(first) { first = false ; stream.queue(op + json)}
else stream.queue(sep + json)
},
function (data) {
if(!anyData)
stream.queue(op)
stream.queue(cl)
stream.queue(null)
})
return stream
}
exports.stringifyObject = function (op, sep, cl, indent) {
indent = indent || 0
if (op === false){
op = ''
sep = '\n'
cl = ''
} else if (op == null) {
op = '{\n'
sep = '\n,\n'
cl = '\n}\n'
}
//else, what ever you like
var first = true
var anyData = false
var stream = through(function (data) {
anyData = true
var json = JSON.stringify(data[0]) + ':' + JSON.stringify(data[1], null, indent)
if(first) { first = false ; this.queue(op + json)}
else this.queue(sep + json)
},
function (data) {
if(!anyData) this.queue(op)
this.queue(cl)
this.queue(null)
})
return stream
}
|
var slugify = require('slugify')
// import slugify from 'slugify'
const text1 = slugify('This is a simple text...')
const text2 = slugify('This is a simple text...', '**')
console.log(text1)
console.log(text2)
|
var Statistics = require('./statistics');
var Tile = require('./tile').Tile;
var Metatile = require('./tile').Metatile;
module.exports = Scheme;
require('util').inherits(Scheme, process.EventEmitter);
function Scheme() {
throw new Error('not instantiable');
}
Scheme.types = {
file: require('./filescheme'),
pyramid: require('./pyramidscheme'),
scanline: require('./scanlinescheme')
};
Scheme.unserialize = function(state) {
return Scheme.types[state.type].unserialize(state);
};
Scheme.create = function(type, options) {
return new Scheme.types[type](options);
};
Scheme.prototype.started = false;
Scheme.prototype.finished = false;
Scheme.prototype.paused = true;
Scheme.prototype.initialize = function() {
this.pending = [];
Object.defineProperty(this, 'next', { value: this.next.bind(this) });
};
Scheme.prototype.start = function() {
if (this.finished) {
this.task.finished();
} else {
this.paused = false;
this.started = true;
this.next();
}
};
Scheme.prototype.pause = function() {
if (!this.paused) {
this.paused = true;
if (!this.pending.length) {
this.emit('paused');
}
} else if (!this.started) {
this.emit('paused');
}
};
Scheme.prototype.addPending = function(tile) {
this.pending.push(tile);
this.stats.pending++;
};
Scheme.prototype.removePending = function(tile) {
var index = this.pending.indexOf(tile);
if (index >= 0) {
this.pending.splice(index, 1);
this.stats.pending--;
}
if (this.paused && !this.pending.length) {
this.emit('paused');
}
};
Scheme.prototype.error = function(tile) {
this.removePending(tile);
this.stats.failed++;
process.nextTick(this.next);
};
Scheme.prototype.unique = function(tile) {
this.removePending(tile);
this.stats.unique++;
process.nextTick(this.next);
};
Scheme.prototype.skip = function(tile) {
this.removePending(tile);
this.stats.skipped++;
process.nextTick(this.next);
};
Scheme.prototype.duplicate = function(tile) {
this.removePending(tile);
this.stats.duplicate++;
process.nextTick(this.next);
};
|
'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 _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
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"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var dbLastTap = 0;
var ReactImageCrop = function (_Component) {
_inherits(ReactImageCrop, _Component);
function ReactImageCrop(props) {
_classCallCheck(this, ReactImageCrop);
var _this = _possibleConstructorReturn(this, (ReactImageCrop.__proto__ || Object.getPrototypeOf(ReactImageCrop)).call(this, props));
_this.state = {
activeCropBlock: false,
moveCropBlock: false,
resizeCropBlock: false,
status: false,
resizeDirection: 0,
blockX: 0,
blockY: 0,
start: {
x: 0,
y: 0
},
moveData: {
diffX: 0,
diffY: 0,
eWi: 0,
eHe: 0,
cWi: 0,
cHe: 0
},
cropSize: {
w: 0,
h: 0
},
resize: {
w: 0,
h: 0
}
};
_this.mouseDown = _this._mouseDown.bind(_this);
_this.resetCrop = _this._resetCrop.bind(_this);
_this.mouseMove = _this._mouseMove.bind(_this);
_this.mouseUp = _this._mouseUp.bind(_this);
_this.dbTab = _this._dbTab.bind(_this);
return _this;
}
_createClass(ReactImageCrop, [{
key: 'componentDidMount',
value: function componentDidMount() {
document.addEventListener("mousemove", this.mouseMove);
document.addEventListener("mouseup", this.mouseUp);
document.addEventListener("touchmove", this.mouseMove);
document.addEventListener("touchend", this.dbTab);
var image = new Image();
image.src = this.props.src;
var a = this;
image.onload = function () {
var block = a.refs.RICC_main_container,
crop = a.refs.RICC_crop_preview,
img = a.refs.RICC_image,
w = a.props.setWidth || img.offsetWidth,
h = a.props.setHeight || img.offsetHeight;
if (w > window.innerWidth) w = window.innerWidth;
if (h > window.innerHeight) h = window.innerHeight;
block.style.width = w + "px";
block.style.height = h + "px";
crop.style.width = w + "px";
crop.style.height = h + "px";
if (parseInt(block.style.width.replace('px', '')) > a.refs.RICC_image.width) w = a.refs.RICC_image.width;
if (parseInt(block.style.height.replace('px', '')) > a.refs.RICC_image.height) h = a.refs.RICC_image.height;
block.style.width = w + "px";
block.style.height = h + "px";
crop.style.width = w + "px";
crop.style.height = h + "px";
a.setState({
blockX: block.getBoundingClientRect().left,
blockY: block.getBoundingClientRect().top
});
};
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
document.removeEventListener("mousemove", this.mouseMove);
document.removeEventListener("mouseup", this.mouseUp);
document.removeEventListener("touchmove", this.mouseMove);
document.removeEventListener("touchend", this.dbTab);
}
}, {
key: 'render',
value: function render() {
return _react2.default.createElement(
'div',
{ id: 'mainContainer', className: 'RICC_main_container', ref: 'RICC_main_container', onTouchStart: this.mouseDown,
onMouseDown: this.mouseDown, onDoubleClick: this.resetCrop },
_react2.default.createElement(
'div',
{ className: 'cropBox' },
this.props.children
),
_react2.default.createElement(
'div',
{ className: 'RICC_crop_block', ref: 'RICC_crop_block' },
_react2.default.createElement('div', { style: this.props.borderStyle ? { borderLeft: this.props.borderStyle } : {},
className: "RICC_crop_block_left_resize" + (this.props.resize ? " RICC_crop_block_left_right_cursor" : ""), ref: 'RICC_crop_block_left_resize' }),
_react2.default.createElement('div', { style: this.props.borderStyle ? { borderRight: this.props.borderStyle } : {},
className: "RICC_crop_block_right_resize" + (this.props.resize ? " RICC_crop_block_left_right_cursor" : ""), ref: 'RICC_crop_block_right_resize' }),
_react2.default.createElement('div', { style: this.props.borderStyle ? { borderTop: this.props.borderStyle } : {},
className: "RICC_crop_block_top_resize" + (this.props.resize ? " RICC_crop_block_top_bottom_cursor" : ""), ref: 'RICC_crop_block_top_resize' }),
_react2.default.createElement('div', { style: this.props.borderStyle ? { borderBottom: this.props.borderStyle } : {},
className: "RICC_crop_block_bottom_resize" + (this.props.resize ? " RICC_crop_block_top_bottom_cursor" : ""), ref: 'RICC_crop_block_bottom_resize' }),
_react2.default.createElement(
'div',
{ className: 'RICC_crop_preview' },
_react2.default.createElement('img', { ref: 'RICC_crop_preview' })
)
),
_react2.default.createElement('div', { className: 'RICC_bg', ref: 'RICC_bg_block' }),
_react2.default.createElement('img', { className: 'RICC_image', ref: 'RICC_image', src: this.props.src })
);
}
}, {
key: '_mouseDown',
value: function _mouseDown(e) {
e.preventDefault();
var main_block = this.refs.RICC_main_container,
crop_block = this.refs.RICC_crop_block,
bg_block = this.refs.RICC_bg_block,
preview_block = this.refs.RICC_crop_preview,
resize_left_block = this.refs.RICC_crop_block_left_resize,
resize_right_block = this.refs.RICC_crop_block_right_resize,
resize_top_block = this.refs.RICC_crop_block_top_resize,
resize_bottom_block = this.refs.RICC_crop_block_bottom_resize,
mousePosX = e.clientX || Math.round(e.touches[0].clientX),
mousePosY = e.clientY + document.body.scrollTop || Math.round(e.touches[0].clientY + document.body.scrollTop);
if (!this.state.activeCropBlock) {
// CREATE CROP BLOCK FUNCTION
crop_block.style.top = mousePosY - this.state.blockY + "px";
crop_block.style.left = mousePosX - this.state.blockX + "px";
preview_block.style.marginTop = "-" + (mousePosY - this.state.blockY) + "px";
preview_block.style.marginLeft = "-" + (mousePosX - this.state.blockX) + "px";
crop_block.style.display = "block";
this.setState({
start: {
x: mousePosX,
y: mousePosY
}
});
} else if (this.state.activeCropBlock) {
if (e.target === bg_block) {
// NEW CROP BLOCK FUNCTION
crop_block.style.top = mousePosY - this.state.blockY + "px";
crop_block.style.left = mousePosX - this.state.blockX + "px";
preview_block.style.marginTop = "-" + (mousePosY - this.state.blockY) + "px";
preview_block.style.marginLeft = "-" + (mousePosX - this.state.blockX) + "px";
crop_block.style.width = "0px";
crop_block.style.height = "0px";
this.setState({
activeCropBlock: false,
start: {
x: mousePosX,
y: mousePosY
}
});
} else if (e.target === crop_block || e.target === preview_block || (e.target === resize_left_block || e.target === resize_right_block || e.target === resize_top_block || e.target === resize_bottom_block) && !this.props.resize) {
// MOVE FUNCTION
var divTop = crop_block.style.top.replace('px', ''),
divLeft = crop_block.style.left.replace('px', ''),
eWi = parseInt(this.state.cropSize.w),
eHe = parseInt(this.state.cropSize.h),
cWi = parseInt(main_block.style.width),
cHe = parseInt(main_block.style.height),
diffX = mousePosX - divLeft,
diffY = mousePosY - divTop;
this.setState({
moveCropBlock: true,
moveData: {
diffX: diffX,
diffY: diffY,
eWi: eWi,
eHe: eHe,
cWi: cWi,
cHe: cHe
}
});
} else if (e.target === resize_left_block || e.target === resize_right_block || e.target === resize_top_block || e.target === resize_bottom_block) {
if (this.props.resize) {
// RESIZE FUNCTION
var block = 0;
if (e.target === resize_left_block) block = 1;else if (e.target === resize_right_block) block = 2;else if (e.target === resize_top_block) block = 3;else if (e.target === resize_bottom_block) block = 4;
this.setState({
resizeCropBlock: true,
resizeDirection: block,
start: {
x: mousePosX,
y: mousePosY
},
resize: {
w: parseInt(crop_block.style.width.replace('px', '')),
h: parseInt(crop_block.style.height.replace('px', ''))
}
});
}
}
}
this.setState({ status: true });
}
}, {
key: '_mouseMove',
value: function _mouseMove(e) {
if (this.state.status) {
e.preventDefault();
var main_block = this.refs.RICC_main_container,
crop_block = this.refs.RICC_crop_block,
preview_block = this.refs.RICC_crop_preview,
mousePosX = e.pageX || Math.round(e.touches[0].clientX),
mousePosY = e.pageY + document.body.scrollTop || Math.round(e.touches[0].clientY + document.body.scrollTop);
if (!this.state.activeCropBlock) {
var startX = this.state.start.x,
startY = this.state.start.y,
bWi = document.getElementById('mainContainer').offsetWidth,
bLeft = this.state.blockX,
bHe = document.getElementById('mainContainer').offsetHeight,
bTop = this.state.blockY,
aX = mousePosX - startX,
aY = mousePosY - startY,
left_right = true,
top_bottom = true;
if (aX < 0) {
var l = parseInt(mousePosX - this.state.blockX);
aX = startX - mousePosX;
preview_block.style.marginLeft = "-" + (mousePosX - this.state.blockX) + "px";
crop_block.style.left = l + "px";
left_right = false;
}
if (aX > 0 && left_right) {
crop_block.style.top = startY - this.state.blockY + "px";
crop_block.style.left = startX - this.state.blockX + "px";
preview_block.style.marginTop = "-" + (startY - this.state.blockY) + "px";
preview_block.style.marginLeft = "-" + (startX - this.state.blockX) + "px";
}
if (aY < 0) {
var t = parseInt(mousePosY - this.state.blockY);
aY = startY - mousePosY;
preview_block.style.marginTop = "-" + (mousePosY - this.state.blockY) + "px";
crop_block.style.top = t + "px";
top_bottom = false;
}
if (this.props.square && top_bottom) aY = aX;else if (this.props.square && !top_bottom) aX = aY;
if (aX > bWi + bLeft - startX && left_right) {
aX = bWi + bLeft - startX;
if (this.props.square) aY = aX;
}
if (aX > bWi - (bWi + bLeft - startX) && !left_right) {
aX = bWi - (bWi + bLeft - startX);
preview_block.style.marginLeft = "-1px";
crop_block.style.left = "0px";
if (this.props.square) aY = aX;
}
if (aY > bHe + bTop - startY && top_bottom) {
aY = bHe + bTop - startY;
if (this.props.square) aX = aY;
}
if (aY > bHe - (bHe + bTop - startY) && !top_bottom) {
aY = bHe - (bHe + bTop - startY);
preview_block.style.marginTop = "-1px";
crop_block.style.top = "0px";
if (this.props.square) aX = aY;
}
crop_block.style.width = aX + "px";
crop_block.style.height = aY + "px";
this.setState({
cropSize: {
w: aX,
h: aY
}
});
} else {
if (this.state.moveCropBlock) {
var _aX = mousePosX - this.state.moveData.diffX,
_aY = mousePosY - this.state.moveData.diffY;
if (_aX < 0) _aX = 0;
if (_aY < 0) _aY = 0;
if (_aX + this.state.moveData.eWi > this.state.moveData.cWi) _aX = this.state.moveData.cWi - this.state.moveData.eWi;
if (_aY + this.state.moveData.eHe > this.state.moveData.cHe) _aY = this.state.moveData.cHe - this.state.moveData.eHe;
crop_block.style.left = _aX + 'px';
crop_block.style.top = _aY + 'px';
preview_block.style.marginTop = "-" + _aY + "px";
preview_block.style.marginLeft = "-" + _aX + "px";
}
if (this.state.resizeCropBlock) {
var _startX = this.state.start.x,
_startY = this.state.start.y,
_bWi = parseInt(main_block.style.width.replace('px', '')),
_bLeft = this.state.blockX,
_bHe = parseInt(main_block.style.height.replace('px', '')),
_bTop = this.state.blockY,
_aX2 = mousePosX - _startX,
_aY2 = mousePosY - _startY;
if (this.state.resizeDirection === 2) {
_aX2 = this.state.resize.w + _aX2;
if (_aX2 > _bWi + _bLeft - _startX + this.state.resize.w) _aX2 = _bWi + _bLeft - _startX + this.state.resize.w - 2;
crop_block.style.width = _aX2 + "px";
this.setState({ cropSize: { w: _aX2, h: this.state.cropSize.h } });
} else if (this.state.resizeDirection === 1) {
var _l = parseInt(mousePosX - this.state.blockX);
_aX2 = this.state.resize.w - _aX2;
if (_l < 0) {
preview_block.style.marginLeft = "-1px";
crop_block.style.left = "0px";
} else {
preview_block.style.marginLeft = "-" + (mousePosX - this.state.blockX) + "px";
crop_block.style.left = _l + "px";
crop_block.style.width = _aX2 + "px";
this.setState({ cropSize: { w: _aX2, h: this.state.cropSize.h } });
}
} else if (this.state.resizeDirection === 4) {
_aY2 = this.state.resize.h + _aY2;
if (_aY2 > _bHe + _bTop - _startY + this.state.resize.h) _aY2 = _bHe + _bTop - _startY + this.state.resize.h - 2;
crop_block.style.height = _aY2 + "px";
this.setState({ cropSize: { h: _aY2, w: this.state.cropSize.w } });
} else if (this.state.resizeDirection === 3) {
var _t = parseInt(mousePosY - this.state.blockY);
_aY2 = this.state.resize.h - _aY2;
if (_t < 0) {
preview_block.style.marginTop = "-1px";
crop_block.style.top = "0px";
} else {
preview_block.style.marginTop = "-" + (mousePosY - this.state.blockY) + "px";
crop_block.style.top = _t + "px";
crop_block.style.height = _aY2 + "px";
this.setState({ cropSize: { h: _aY2, w: this.state.cropSize.w } });
}
}
}
}
}
}
}, {
key: '_mouseUp',
value: function _mouseUp(e) {
if (this.state.status) {
e.preventDefault();
if (!this.state.activeCropBlock) this.setState({ activeCropBlock: true });
if (this.state.moveCropBlock) this.setState({ moveCropBlock: false });
if (this.state.resizeCropBlock) this.setState({ resizeCropBlock: false, resizeDirection: 0 });
if (this.props.onCrop) this.props.onCrop(this._onCrop());
this.setState({ status: false });
}
}
}, {
key: '_resetCrop',
value: function _resetCrop() {
var crop_block = this.refs.RICC_crop_block,
preview_block = this.refs.RICC_crop_preview;
crop_block.style.top = "0px";
crop_block.style.left = "0px";
crop_block.style.width = "0px";
crop_block.style.height = "0px";
preview_block.style.marginTop = "0px";
preview_block.style.marginLeft = "0px";
crop_block.style.display = "none";
this.setState({
activeCropBlock: false
});
}
}, {
key: '_onCrop',
value: function _onCrop() {
var w = this.refs.RICC_crop_block.offsetWidth,
h = this.refs.RICC_crop_block.offsetHeight,
l = this.refs.RICC_crop_block.offsetLeft,
t = this.refs.RICC_crop_block.offsetTop,
img = new Image(),
canvas = document.createElement('canvas');
img.src = this.refs.RICC_image.src;
var ratioW = img.width / this.refs.RICC_image.width,
ratioH = img.height / this.refs.RICC_image.height;
if (ratioW < 1) ratioW = 1;
if (ratioH < 1) ratioH = 1;
canvas.width = w * ratioW;
canvas.height = h * ratioH;
canvas.getContext('2d').drawImage(img, -l * ratioW, -t * ratioH, img.width, img.height);
var ratio = img.width / this.refs.RICC_main_container.offsetWidth;
ratioH = ratio;
if (img.height > img.width) ratioH = img.height / this.refs.RICC_main_container.offsetHeight;
if (ratio < 1) ratio = 1;
if (ratioH < 1) ratioH = 1;
this._resetCrop();
return [canvas.toDataURL(), { y: t * ratio, x: l * ratio, w: w * ratioH, h: h * ratioH }];
}
}, {
key: '_dbTab',
value: function _dbTab(e) {
var currentTime = new Date().getTime(),
tapLength = currentTime - dbLastTap;
if (tapLength < 250 && tapLength > 0) {
this._resetCrop();
e.preventDefault();
} else this._mouseUp(e);
dbLastTap = currentTime;
}
}]);
return ReactImageCrop;
}(_react.Component);
ReactImageCrop.defaultProps = {
resize: true
};
ReactImageCrop.propTypes = {
src: _propTypes2.default.string,
setWidth: _propTypes2.default.number,
setHeight: _propTypes2.default.number,
square: _propTypes2.default.bool,
resize: _propTypes2.default.bool,
border: _propTypes2.default.string,
onCrop: _propTypes2.default.func
};
exports.default = ReactImageCrop;
|
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define(['dojo/_base/declare',
'./_BasicServiceChooserContent',
'./GpServiceBrowser'
],
function(declare, _BasicServiceChooserContent, GpServiceBrowser) {
return declare([_BasicServiceChooserContent], {
baseClass: 'jimu-gp-service-chooser-content',
_examples:['http://myserver/arcgis/rest/services',
'http://myserver/arcgis/rest/services/myservice/GpServer',
'http://sampleserver6.arcgisonline.com/arcgis/' +
'rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed'],
//methods need to override:
//_createServiceBrowser, return a service browser
//to be override,return a service browser
_createServiceBrowser: function(args){
return new GpServiceBrowser(args);
}
});
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var HarmonyModulesHelpers = exports;
HarmonyModulesHelpers.getModuleVar = function(state, request) {
if(!state.harmonyModules) state.harmonyModules = [];
var idx = state.harmonyModules.indexOf(request);
if(idx < 0) {
idx = state.harmonyModules.length;
state.harmonyModules.push(request);
}
return "__WEBPACK_IMPORTED_MODULE_" + idx + "_" + request.replace(/[^A-Za-z0-9_]/g, "_").replace(/__+/g, "_") + "__";
};
HarmonyModulesHelpers.getNewModuleVar = function(state, request) {
if(state.harmonyModules && state.harmonyModules.indexOf(request) >= 0)
return null;
return HarmonyModulesHelpers.getModuleVar(state, request);
};
HarmonyModulesHelpers.checkModuleVar = function(state, request) {
if(!state.harmonyModules || state.harmonyModules.indexOf(request) < 0)
return null;
return HarmonyModulesHelpers.getModuleVar(state, request);
};
// checks if an harmony dependency is active in a module according to
// precedence rules.
HarmonyModulesHelpers.isActive = function(module, depInQuestion) {
var desc = depInQuestion.describeHarmonyExport();
if(!desc.exportedName) return true;
var before = true;
for(var i = 0; i < module.dependencies.length; i++) {
var dep = module.dependencies[i];
if(dep === depInQuestion) {
before = false;
continue;
}
if(!dep.describeHarmonyExport) continue;
var d = dep.describeHarmonyExport();
if(!d || !d.exportedName) continue;
if(d.exportedName === desc.exportedName) {
if(d.precedence < desc.precedence) {
return false;
}
if(d.precedence === desc.precedence && !before) {
return false;
}
}
}
return true;
};
// get a list of named exports defined in a module
// doesn't include * reexports.
HarmonyModulesHelpers.getActiveExports = function(module, currentDependency) {
var desc = currentDependency && currentDependency.describeHarmonyExport();
var currentIndex = currentDependency ? module.dependencies.indexOf(currentDependency) : -1;
return module.dependencies.map(function(dep, idx) {
return {
dep: dep,
idx: idx
}
}).reduce(function(arr, data) {
var dep = data.dep;
if(!dep.describeHarmonyExport) return arr;
var d = dep.describeHarmonyExport();
if(!d) return arr;
if(!desc || (d.precedence < desc.precedence) || (d.precedence === desc.precedence && data.idx < currentIndex)) {
var names = [].concat(d.exportedName);
names.forEach(function(name) {
if(name && arr.indexOf(name) < 0)
arr.push(name);
});
}
return arr;
}, []);
};
|
$(window).on("scroll", function () {
if ($(this).scrollTop() > 200) {
$(".navbar").addClass("transparent");
// $(".navbar").stop().animate({opacity: 0});
}
else {
$(".navbar").removeClass("transparent");
// $(".navbar").stop().animate({opacity: 1});
}
});
$(window).on("scroll", function () {
if ($(this).scrollTop() > 0) {
$(".navbar").addClass("navbar-scroll");
// $(".navbar").stop().animate({opacity: 0});
}
else {
$(".navbar").removeClass("navbar-scroll");
// $(".navbar").stop().animate({opacity: 1});
}
});
var scroll_to_target = function (target, complete) {
var target = $(target);
if (target.length) {
$('html, body').animate({scrollTop: target.offset().top - 120}, 1, complete);
}
}
// Because we have a fixed position nav bar, when a user clicks on a target with a #hash
// we have to scroll the page a bit so the target is visible.
$(window).on("load", function () {
// Handle the case where we are loading a page with a #id target in the URL
var hash = window.location.hash;
if (hash) {
scroll_to_target(hash);
}
// Handle the case when the user clicks on a #id target on the current page
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
var hash = this.hash;
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
scroll_to_target(target, function () {
location.hash = hash;
});
if (target.length) { return false; }
}
});
});
|
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
this.ctx.body = 'hi, ' + this.app.plugins.tsSequelize.name;
}
}
module.exports = HomeController;
|
// @flow weak
const { jsdom } = require('jsdom');
function createDOM() {
global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
if (typeof global[property] === 'undefined') {
global[property] = document.defaultView[property];
}
});
global.navigator = {
userAgent: 'node.js',
};
}
module.exports = createDOM;
|
'use strict';
const { users } = require('../models/index.js');
module.exports = async (req, res, next) => {
try {
if (!req.headers.authorization) { next('Invalid Login') }
const token = req.headers.authorization.split(' ').pop();
const validUser = await users.authenticateToken(token);
req.user = validUser;
req.token = validUser.token;
next();
} catch (e) {
res.status(403).send('Invalid Login');;
}
}
|
import { expect } from 'chai';
import { PrebidServer as Adapter, resetSyncedStatus } from 'modules/prebidServerBidAdapter/index.js';
import adapterManager from 'src/adapterManager';
import * as utils from 'src/utils';
import { ajax } from 'src/ajax';
import { config } from 'src/config';
import events from 'src/events';
import CONSTANTS from 'src/constants';
let CONFIG = {
accountId: '1',
enabled: true,
bidders: ['appnexus'],
timeout: 1000,
cacheMarkup: 2,
endpoint: 'https://prebid.adnxs.com/pbs/v1/auction'
};
const REQUEST = {
'account_id': '1',
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'max_bids': 1,
'timeout_millis': 1000,
'secure': 0,
'url': '',
'prebid_version': '0.30.0-pre',
'ad_units': [
{
'code': 'div-gpt-ad-1460505748561-0',
'sizes': [[300, 250], [300, 600]],
'mediaTypes': {
'banner': {
'sizes': [[300, 250], [300, 300]]
},
'native': {
'title': {
'required': true,
'len': 800
},
'image': {
'required': true,
'sizes': [989, 742],
},
'sponsoredBy': {
'required': true
}
}
},
'transactionId': '4ef956ad-fd83-406d-bd35-e4bb786ab86c',
'bids': [
{
'bid_id': '123',
'bidder': 'appnexus',
'params': {
'placementId': '10433394',
'member': 123
}
}
]
}
]
};
const VIDEO_REQUEST = {
'account_id': '1',
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'max_bids': 1,
'timeout_millis': 1000,
'secure': 0,
'url': '',
'prebid_version': '1.4.0-pre',
'ad_units': [
{
'code': 'div-gpt-ad-1460505748561-0',
'sizes': [640, 480],
'mediaTypes': {
'video': {
'playerSize': [[640, 480]],
'mimes': ['video/mp4']
}
},
'transactionId': '4ef956ad-fd83-406d-bd35-e4bb786ab86c',
'bids': [
{
'bid_id': '123',
'bidder': 'appnexus',
'params': { 'placementId': '12349520' }
}
]
}
]
};
const OUTSTREAM_VIDEO_REQUEST = {
'account_id': '1',
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'max_bids': 1,
'timeout_millis': 1000,
'secure': 0,
'url': '',
'prebid_version': '1.4.0-pre',
'ad_units': [
{
'code': 'div-gpt-ad-1460505748561-0',
'sizes': [640, 480],
'mediaTypes': {
'video': {
playerSize: [[640, 480]],
context: 'outstream',
mimes: ['video/mp4']
},
banner: { sizes: [[300, 250]] }
},
'transactionId': '4ef956ad-fd83-406d-bd35-e4bb786ab86c',
'bids': [
{
'bid_id': '123',
'bidder': 'appnexus',
'params': { 'placementId': '12349520' }
}
]
},
{
code: 'video1',
mediaTypes: {
video: {
playerSize: [640, 480],
context: 'outstream',
mimes: ['video/mp4']
}
},
bids: [
{
bidder: 'appnexus',
params: {
placementId: 13232385,
video: {
skippable: true,
playback_method: ['auto_play_sound_off']
}
}
}
],
renderer: {
url: 'http://acdn.adnxs.com/video/outstream/ANOutstreamVideo.js',
render: function (bid) {
ANOutstreamVideo.renderAd({
targetId: bid.adUnitCode,
adResponse: bid.adResponse,
});
}
}
}
]
};
let BID_REQUESTS;
const RESPONSE = {
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'status': 'OK',
'bidder_status': [
{
'bidder': 'appnexus',
'response_time_ms': 52,
'num_bids': 1
}
],
'bids': [
{
'bid_id': '123',
'code': 'div-gpt-ad-1460505748561-0',
'creative_id': '29681110',
'bidder': 'appnexus',
'price': 0.5,
'adm': '<script type="application/javascript" src="http://nym1-ib.adnxs.com/ab?e=wqT_3QL_Baj_AgAAAwDWAAUBCO-s38cFEJG-p6iRgOfvdhivtLWVpomhsWUgASotCQAAAQII4D8RAQc0AADgPxkAAACA61HgPyEREgApEQmgMPLm_AQ4vgdAvgdIAlDWy5MOWOGASGAAaJFAeP3PBIABAYoBA1VTRJIFBvBSmAGsAqAB-gGoAQGwAQC4AQLAAQPIAQLQAQnYAQDgAQHwAQCKAjp1ZignYScsIDQ5NDQ3MiwgMTQ5MjYzNzI5NSk7dWYoJ3InLCAyOTY4MTExMCwyHgDwnJIC7QEhcHpUNkZ3aTYwSWNFRU5iTGt3NFlBQ0RoZ0Vnd0FEZ0FRQVJJdmdkUTh1YjhCRmdBWVBfX19fOFBhQUJ3QVhnQmdBRUJpQUVCa0FFQm1BRUJvQUVCcUFFRHNBRUF1UUVwaTRpREFBRGdQOEVCS1l1SWd3QUE0RF9KQWQ0V2JVTnJmUEVfMlFFQUFBQUFBQUR3UC1BQkFQVUIFD0BKZ0Npb2FvcEFtZ0FnQzFBZwEWBEM5CQjoREFBZ0hJQWdIUUFnSFlBZ0hnQWdEb0FnRDRBZ0NBQXdHUUF3Q1lBd0dvQTdyUWh3US6aAjEhRXduSHU68AAcNFlCSUlBUW8JbARreAFmDQHwui7YAugH4ALH0wHqAg93d3cubnl0aW1lcy5jb23yAhEKBkNQR19JRBIHMTk3NzkzM_ICEAoFQ1BfSUQSBzg1MTM1OTSAAwGIAwGQAwCYAxSgAwGqAwDAA6wCyAMA2APjBuADAOgDAPgDA4AEAJIECS9vcGVucnRiMpgEAKIECzEwLjI0NC4wLjIyqAQAsgQKCAAQABgAIAAwALgEAMAEAMgEANIEDDEwLjMuMTM4LjE0ONoEAggB4AQA8ARBXyCIBQGYBQCgBf8RAZwBqgUkNDM3ZmJiZjUtMzNmNS00ODdhLThlMTYtYTcxMTI5MDNjZmU1&s=b52bf8a6265a78a5969444bc846cc6d0f9f3b489&test=1&referrer=www.nytimes.com&pp=${AUCTION_PRICE}&"></script>',
'width': 300,
'height': 250,
'deal_id': 'test-dealid',
'ad_server_targeting': {
'foo': 'bar'
},
'cache_id': '7654321',
'cache_url': 'http://www.test.com/cache?uuid=7654321',
}
]
};
const VIDEO_RESPONSE = {
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'status': 'OK',
'bidder_status': [
{
'bidder': 'appnexus',
'response_time_ms': 52,
'num_bids': 1
}
],
'bids': [
{
'bid_id': '123',
'code': 'div-gpt-ad-1460505748561-0',
'creative_id': '29681110',
'bidder': 'appnexus',
'price': 0.5,
'adm': '<script type="application/javascript" src="http://nym1-ib.adnxs.com/ab?e=wqT_3QL_Baj_AgAAAwDWAAUBCO-s38cFEJG-p6iRgOfvdhivtLWVpomhsWUgASotCQAAAQII4D8RAQc0AADgPxkAAACA61HgPyEREgApEQmgMPLm_AQ4vgdAvgdIAlDWy5MOWOGASGAAaJFAeP3PBIABAYoBA1VTRJIFBvBSmAGsAqAB-gGoAQGwAQC4AQLAAQPIAQLQAQnYAQDgAQHwAQCKAjp1ZignYScsIDQ5NDQ3MiwgMTQ5MjYzNzI5NSk7dWYoJ3InLCAyOTY4MTExMCwyHgDwnJIC7QEhcHpUNkZ3aTYwSWNFRU5iTGt3NFlBQ0RoZ0Vnd0FEZ0FRQVJJdmdkUTh1YjhCRmdBWVBfX19fOFBhQUJ3QVhnQmdBRUJpQUVCa0FFQm1BRUJvQUVCcUFFRHNBRUF1UUVwaTRpREFBRGdQOEVCS1l1SWd3QUE0RF9KQWQ0V2JVTnJmUEVfMlFFQUFBQUFBQUR3UC1BQkFQVUIFD0BKZ0Npb2FvcEFtZ0FnQzFBZwEWBEM5CQjoREFBZ0hJQWdIUUFnSFlBZ0hnQWdEb0FnRDRBZ0NBQXdHUUF3Q1lBd0dvQTdyUWh3US6aAjEhRXduSHU68AAcNFlCSUlBUW8JbARreAFmDQHwui7YAugH4ALH0wHqAg93d3cubnl0aW1lcy5jb23yAhEKBkNQR19JRBIHMTk3NzkzM_ICEAoFQ1BfSUQSBzg1MTM1OTSAAwGIAwGQAwCYAxSgAwGqAwDAA6wCyAMA2APjBuADAOgDAPgDA4AEAJIECS9vcGVucnRiMpgEAKIECzEwLjI0NC4wLjIyqAQAsgQKCAAQABgAIAAwALgEAMAEAMgEANIEDDEwLjMuMTM4LjE0ONoEAggB4AQA8ARBXyCIBQGYBQCgBf8RAZwBqgUkNDM3ZmJiZjUtMzNmNS00ODdhLThlMTYtYTcxMTI5MDNjZmU1&s=b52bf8a6265a78a5969444bc846cc6d0f9f3b489&test=1&referrer=www.nytimes.com&pp=${AUCTION_PRICE}&"></script>',
'width': 300,
'height': 250,
'deal_id': 'test-dealid',
'ad_server_targeting': {
'foo': 'bar'
},
'media_type': 'video',
'cache_id': 'video_cache_id',
'cache_url': 'video_cache_url',
}
]
};
const RESPONSE_NO_BID_NO_UNIT = {
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'status': 'OK',
'bidder_status': [{
'bidder': 'appnexus',
'response_time_ms': 132,
'no_bid': true
}]
};
const RESPONSE_NO_BID_UNIT_SET = {
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'status': 'OK',
'bidder_status': [{
'bidder': 'appnexus',
'ad_unit': 'div-gpt-ad-1460505748561-0',
'response_time_ms': 91,
'no_bid': true
}]
};
const RESPONSE_NO_COOKIE = {
'tid': 'd6eca075-4a59-4346-bdb3-86531830ef2c',
'status': 'OK',
'bidder_status': [{
'bidder': 'pubmatic',
'no_cookie': true,
'usersync': {
'url': '//ads.pubmatic.com/AdServer/js/user_sync.html?predirect=http://localhost:8000/setuid?bidder=pubmatic&uid=',
'type': 'iframe'
}
}]
};
const RESPONSE_NO_PBS_COOKIE = {
'tid': '882fe33e-2981-4257-bd44-bd3b03945f48',
'status': 'no_cookie',
'bidder_status': [{
'bidder': 'rubicon',
'no_cookie': true,
'usersync': {
'url': 'https://pixel.rubiconproject.com/exchange/sync.php?p=prebid',
'type': 'redirect'
}
}, {
'bidder': 'pubmatic',
'no_cookie': true,
'usersync': {
'url': '//ads.pubmatic.com/AdServer/js/user_sync.html?predirect=https%3A%2F%2Fprebid.adnxs.com%2Fpbs%2Fv1%2Fsetuid%3Fbidder%3Dpubmatic%26uid%3D',
'type': 'iframe'
}
}, {
'bidder': 'appnexus',
'response_time_ms': 162,
'num_bids': 1,
'debug': [{
'request_uri': 'http://ib.adnxs.com/openrtb2',
'request_body': '{"id":"882fe33e-2981-4257-bd44-bd3b03945f48","imp":[{"id":"/19968336/header-bid-tag-0","banner":{"w":300,"h":250,"format":[{"w":300,"h":250}]},"secure":1,"ext":{"appnexus":{"placement_id":5914989}}}],"site":{"domain":"nytimes.com","page":"http://www.nytimes.com"},"device":{"ua":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36","ip":"75.97.0.47"},"user":{"id":"3519479852893340159","buyeruid":"3519479852893340159"},"at":1,"tmax":1000,"source":{"fd":1,"tid":"882fe33e-2981-4257-bd44-bd3b03945f48"}}',
'response_body': '{"id":"882fe33e-2981-4257-bd44-bd3b03945f48"}',
'status_code': 200
}]
}],
'bids': [{
'bid_id': '123',
'code': 'div-gpt-ad-1460505748561-0',
'creative_id': '70928274',
'bidder': 'appnexus',
'price': 0.07425,
'adm': '<script type="application/javascript" src="https://secure-nym.adnxs.com/ab?e=wqT_3QLeCPBOXgQAAAMA1gAFAQi5krDKBRCwho2ft8LKoCMY_4PozveI7eswIAEqLQnbgoxDEVi5PxElYqnyDAKzPxkAAAAgXA8zQCHOzMzMzMy8PykzMwECsMM_MO2C6QI47RtA_AxIAlCSj-khWL-tNGAAaNfUTniivwSAAQGKAQNVU0SSAQEG8FSYAawCoAH6AagBAbABALgBAsABBcgBAtABCdgBAOABAPABAIoCkgF1ZignYScsIDE2OTc2MjksIDE0OTgxNTUzMjEpO3VmKCdyJywgNzA5MjgyNzQsQh4ABGMnATsQODY2NTVKPAAgZycsIDM5OTgzTh0AKGknLCA0OTM1MTUsMlcA8IeSAs0CIWhWRE5jZ2pfdVlVSUVKS1A2U0VZQUNDX3JUUXdBRGdBUUFCSV9BeFE3WUxwQWxnQVlKOEJhQUJ3QUhnQWdBRUFpQUVBa0FFQm1BRUJvQUVCcUFFRHNBRUF1UUhPRGRmZE16UERQOEVCemczWDNUTXp3el9KQVFBQUFBQUFBUEFfMlFFCQw0QUR3UC1BQnk0OGU5UUUFFChnQUlCaUFLMzdjRQEIQEIzNWNCaUFMZzZJNEVpQUxoDQgAag0IAG4NCABvAQhIa0FJSG1BSUFvQUlBcUFJR3RRSQVUAHYNCPBed0FJQXlBSUEwQUlBMkFJQTRBTDYtd2ZvQXBqaXI4b0Y4Z0lGZG1semFUSDRBZ0NBQXdHUUF3Q1lBd0dvQV8tNWhRaTZBd2xPV1UweU9qTTJNamcumgItIV93ajdud2oyUAHwTHY2MDBJQUFvQURvSlRsbE5Nam96TmpJNNgCAOACvtUr6gIWaHR0cDovL3d3dy5ueXRpbWVzLmNvbfICEQoGQURWX0lEEgcxNjk3NjI5BRQIQ1BHBRQt9AEUCAVDUAETBAgxTSXA8gINCghBRFZfRlJFURIBMPICGQoPQ1VTVE9NX01PREVMX0lEEgYxMzA1NTTyAh8KFjIcAFBMRUFGX05BTUUSBXZpc2kx8gIoCho2IgAIQVNUAUkcSUZJRUQSCjFBzvB4NDkxNDSAAwCIAwGQAwCYAxSgAwGqAwDAA6wCyAMA2APjBuADAOgDAPgDA4AEAJIECS9vcGVucnRiMpgEAKIECjc1Ljk3LjAuNDeoBACyBAoIABAAGAAgADAAuAQAwAQAyAQA0gQJTllNMjozNjI42gQCCAHgBADwBGGlIIgFAZgFAKAF_xEBuAGqBSQ4ODJmZTMzZS0yOTgxLTQyNTctYmQ0NC1iZDNiMDM5NDVmNDjABQDJBQAAAQI08D_SBQkJAAAAAAAAAAA.&s=d4bc7cd2e5d7e1910a591bc97df6ae9e63333e52&referrer=http%3A%2F%2Fwww.nytimes.com&pp=${AUCTION_PRICE}&"></script>',
'width': 300,
'height': 250,
'response_time_ms': 162
}]
};
const RESPONSE_NO_PBS_COOKIE_ERROR = {
'tid': '882fe33e-2981-4257-bd44-bd3b0394545f',
'status': 'no_cookie',
'bidder_status': [{
'bidder': 'rubicon',
'no_cookie': true,
'usersync': {
'url': 'https://pixel.rubiconproject.com/exchange/sync.php?p=prebid',
'type': 'jsonp'
}
}, {
'bidder': 'pubmatic',
'no_cookie': true,
'usersync': {
'url': '',
'type': 'iframe'
}
}]
};
const RESPONSE_OPENRTB = {
'id': 'c7dcf14f',
'seatbid': [
{
'bid': [
{
'id': '8750901685062148',
'impid': 'div-gpt-ad-1460505748561-0',
'price': 0.5,
'adm': '<script src="http://lax1-ib.adnxs.com/ab?e=wqT_3QKgB6CgAwAAAwDWAAUBCJ7kvtMFEPft7JnIuImSdBj87IDv8q21rXcqNgkAAAECCOA_EQEHNAAA4D8ZAAAAgOtR4D8hERIAKREJADERG6Aw8ub8BDi-B0C-B0gCUNbLkw5Y4YBIYABokUB48NIEgAEBigEDVVNEkgUG8FKYAawCoAH6AagBAbABALgBAsABA8gBAtABCdgBAOABAPABAIoCOnVmKCdhJywgNDk0NDcyLCAxNTE3MjY5NTM0KTt1ZigncicsIDI5NjgxMTEwLDIeAPCckgKBAiFqRHF3RUFpNjBJY0VFTmJMa3c0WUFDRGhnRWd3QURnQVFBUkl2Z2RROHViOEJGZ0FZUF9fX184UGFBQndBWGdCZ0FFQmlBRUJrQUVCbUFFQm9BRUJxQUVEc0FFQXVRRXBpNGlEQUFEZ1A4RUJLWXVJZ3dBQTREX0pBVkx3MU5mdl9lMF8yUUVBQUFBQUFBRHdQLUFCQVBVQgUPKEpnQ0FLQUNBTFVDBRAETDAJCPBUTUFDQWNnQ0FkQUNBZGdDQWVBQ0FPZ0NBUGdDQUlBREFaQURBSmdEQWFnRHV0Q0hCTG9ERVdSbFptRjFiSFFqVEVGWU1Ub3pPRFk1mgI5IS1ndndfUTYEAfCENFlCSUlBUW9BRG9SWkdWbVlYVnNkQ05NUVZneE9qTTROamsu2ALoB-ACx9MB6gJHaHR0cDovL3ByZWJpZC5sb2NhbGhvc3Q6OTk5OS9pbnRlZ3JhdGlvbkV4YW1wbGVzL2dwdC9hcHBuZXh1cy10ZXN0Lmh0bWzyAhAKBkFEVl9JRBIGNCXTHPICEQoGQ1BHARM4BzE5Nzc5MzPyAhAKBUNQBRPwljg1MTM1OTSAAwGIAwGQAwCYAxSgAwGqAwDAA6wCyAMA2AMA4AMA6AMA-AMDgAQAkgQJL29wZW5ydGIymAQAogQMMjE2LjU1LjQ3Ljk0qAQAsgQMCAAQABgAIAAwADgAuAQAwAQAyAQA0gQRZGVmYXVsdCNMQVgxOjM4NjnaBAIIAeAEAPAE1suTDogFAZgFAKAF______8BA7ABqgUkYzdkY2YxNGYtZjliYS00Yzc3LWEzYjQtMjdmNmRmMzkwNjdmwAUAyQVpLhTwP9IFCQkJDFAAANgFAeAFAfAFAfoFBAgAEACQBgA.&s=f4dc8b6fa65845d08f0a87c145e12cb7d6288c2a&referrer=http%3A%2F%2Fprebid.localhost%3A9999%2FintegrationExamples%2Fgpt%2Fappnexus-test.html&pp=${AUCTION_PRICE}"></script>',
'adid': '29681110',
'adomain': ['appnexus.com'],
'iurl': 'http://lax1-ib.adnxs.com/cr?id=2968111',
'cid': '958',
'crid': '2968111',
'w': 300,
'h': 250,
'ext': {
'prebid': { 'type': 'banner' },
'bidder': {
'appnexus': {
'brand_id': 1,
'auction_id': 3,
'bidder_id': 2
}
}
}
}
],
'seat': 'appnexus'
},
],
'ext': {
'responsetimemillis': {
'appnexus': 8,
}
}
};
const RESPONSE_OPENRTB_VIDEO = {
id: 'c7dcf14f',
seatbid: [
{
bid: [
{
id: '1987250005171537465',
impid: 'div-gpt-ad-1460505748561-0',
price: 10,
adm: '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><VAST version="3.0"><Ad id="81877115" sequence="0"><Wrapper><AdSystem version="3.0">adnxs</AdSystem><VASTAdTagURI><![CDATA[http://lax1-ib.adnxs.com/ab?e=wqT_3QLZBq]]></VASTAdTagURI><Impression><![CDATA[http://ib.adnxs.com/nop]]></Impression><Creatives><Creative adID="81877115"><Linear></Linear></Creative></Creatives></Wrapper></Ad></VAST>',
adid: '81877115',
adomain: ['appnexus.com'],
iurl: 'http://lax1-ib.adnxs.com/cr?id=81877115',
cid: '3535',
crid: '81877115',
w: 1,
h: 1,
ext: {
prebid: {
type: 'video',
},
bidder: {
appnexus: {
brand_id: 1,
auction_id: 6673622101799484743,
bidder_id: 2,
bid_ad_type: 1,
},
},
},
},
],
seat: 'appnexus',
},
],
ext: {
responsetimemillis: {
appnexus: 81,
},
},
};
const RESPONSE_OPENRTB_NATIVE = {
'id': 'c7dcf14f',
'seatbid': [
{
'bid': [
{
'id': '6451317310275562039',
'impid': 'div-gpt-ad-1460505748561-0',
'price': 10,
'adm': {
'ver': '1.2',
'assets': [
{
'id': 1,
'img': {
'url': 'https://vcdn.adnxs.com/p/creative-image/f8/7f/0f/13/f87f0f13-230c-4f05-8087-db9216e393de.jpg',
'w': 989,
'h': 742,
'ext': {
'appnexus': {
'prevent_crop': 0
}
}
}
},
{
'id': 0,
'title': {
'text': 'This is a Prebid Native Creative'
}
},
{
'id': 2,
'data': {
'value': 'Prebid.org'
}
}
],
'link': {
'url': 'https://lax1-ib.adnxs.com/click?AAAAAAAAJEAAAAAAAAAkQAAAAAAAACRAAAAAAAAAJEAAAAAAAAAkQGdce2vBWudAJZpFu1er1zA7ZzddAAAAAOLoyQBtJAAAbSQAAAIAAAC8pM8FnPgWAAAAAABVU0QAVVNEAAEAAQBNXQAAAAABAgMCAAAAALsAuhVqdgAAAAA./cpcpm=AAAAAAAAAAA=/bcr=AAAAAAAA8D8=/pp=${AUCTION_PRICE}/cnd=%213Q5HCQj8-LwKELzJvi4YnPFbIAQoADEAAAAAAAAkQDoJTEFYMTo0MDc3QKcPSQAAAAAAAPA_UQAAAAAAAAAAWQAAAAAAAAAAYQAAAAAAAAAAaQAAAAAAAAAAcQAAAAAAAAAA/cca=OTMyNSNMQVgxOjQwNzc=/bn=84305/test=1/clickenc=http%3A%2F%2Fprebid.org%2Fdev-docs%2Fshow-native-ads.html'
},
'eventtrackers': [
{
'event': 1,
'method': 1,
'url': 'https://lax1-ib.adnxs.com/it?an_audit=0&test=1&referrer=http%3A%2F%2Flocalhost%3A9999%2FintegrationExamples%2Fgpt%2Fdemo_native.html&e=wqT_3QKCCKACBAAAAwDWAAUBCLvO3ekFEOe47duW2NbzQBiltJba--rq6zAqNgkAAAECCCRAEQEHEAAAJEAZEQkAIREJACkRCQAxEQmoMOLRpwY47UhA7UhIAlC8yb4uWJzxW2AAaM26dXjRkgWAAQGKAQNVU0SSAQEG8FKYAQGgAQGoAQGwAQC4AQLAAQPIAQLQAQnYAQDgAQHwAQCKAjt1ZignYScsIDI1Mjk4ODUsIDE1NjM5MTE5OTUpO3VmKCdyJywgOTc0OTQyMDQsIC4eAPQ0AZICnQIhb2pkaWlnajgtTHdLRUx6SnZpNFlBQ0NjOFZzd0FEZ0FRQVJJN1VoUTR0R25CbGdBWVAwQmFBQndBSGdBZ0FFQWlBRUFrQUVCbUFFQm9BRUJxQUVEc0FFQXVRSHpyV3FrQUFBa1FNRUI4NjFxcEFBQUpFREpBVVZpYmxDaFpRQkEyUUVBQUFBQUFBRHdQLUFCQVBVQkFBQUFBUGdCQUpnQ0FLQUNBTFVDQUFBQUFMMENBQUFBQU1BQ0FNZ0NBT0FDQU9nQ0FQZ0NBSUFEQVpBREFKZ0RBYWdEX1BpOENyb0RDVXhCV0RFNk5EQTNOLUFEcHctUUJBQ1lCQUhCQkFBQUFBQUFBQUFBeVFRQUFBQUFBQUFBQU5nRUFBLi6aAoUBITNRNUhDUWo4LUx3S0VMeiUhJG5QRmJJQVFvQUQRvVhBa1FEb0pURUZZTVRvME1EYzNRS2NQUxFUDFBBX1URDAxBQUFXHQwAWR0MAGEdDABjHQz0FwHYAgDgAq2YSOoCPmh0dHA6Ly9sb2NhbGhvc3Q6OTk5OS9pbnRlZ3JhdGlvbkV4YW1wbGVzL2dwdC9kZW1vX25hdGl2ZS5odG1sgAMAiAMBkAMAmAMUoAMBqgMAwAPgqAHIAwDYAwDgAwDoAwD4AwOABACSBAkvb3BlbnJ0YjKYBACiBA0xNzMuMjQ0LjM2LjQwqATtoySyBAwIABAAGAAgADAAOAC4BADABADIBADSBA45MzI1I0xBWDE6NDA3N9oEAggB4AQA8AS8yb4uiAUBmAUAoAX___________8BqgUkZTU5YzNlYjYtNmRkNi00MmQ5LWExMWEtM2FhMTFjOTc5MGUwwAUAyQUAAAAAAADwP9IFCQkAaVh0ANgFAeAFAfAFmfQh-gUECAAQAJAGAZgGALgGAMEGCSQk8D_IBgDaBhYKEAkQGQEBwTTgBgzyBgIIAIAHAYgHAA..&s=11ababa390e9f7983de260493fc5b91ec5b1b3d4&pp=${AUCTION_PRICE}'
}
]
},
'adid': '97494204',
'adomain': [
'http://prebid.org'
],
'iurl': 'https://lax1-ib.adnxs.com/cr?id=97494204',
'cid': '9325',
'crid': '97494204',
'cat': [
'IAB3-1'
],
'ext': {
'prebid': {
'targeting': {
'hb_bidder': 'appnexus',
'hb_pb': '10.00'
},
'type': 'native',
'video': {
'duration': 0,
'primary_category': ''
}
},
'bidder': {
'appnexus': {
'brand_id': 555545,
'auction_id': 4676806524825984103,
'bidder_id': 2,
'bid_ad_type': 3
}
}
}
}
],
'seat': 'appnexus'
}
]
};
const RESPONSE_UNSUPPORTED_BIDDER = {
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'status': 'OK',
'bidder_status': [{
'bidder': '33Across',
'error': 'Unsupported bidder'
}]
};
describe('S2S Adapter', function () {
let adapter,
addBidResponse = sinon.spy(),
done = sinon.spy();
beforeEach(function () {
adapter = new Adapter();
BID_REQUESTS = [
{
'bidderCode': 'appnexus',
'auctionId': '173afb6d132ba3',
'bidderRequestId': '3d1063078dfcc8',
'tid': '437fbbf5-33f5-487a-8e16-a7112903cfe5',
'bids': [
{
'bidder': 'appnexus',
'params': {
'placementId': '10433394',
'member': 123,
'keywords': {
'foo': ['bar', 'baz'],
'fizz': ['buzz']
}
},
'bid_id': '123',
'adUnitCode': 'div-gpt-ad-1460505748561-0',
'mediaTypes': {
'banner': {
'sizes': [[300, 250]]
}
},
'transactionId': '4ef956ad-fd83-406d-bd35-e4bb786ab86c',
'sizes': [300, 250],
'bidId': '123',
'bidderRequestId': '3d1063078dfcc8',
'auctionId': '173afb6d132ba3'
}
],
'auctionStart': 1510852447530,
'timeout': 5000,
'src': 's2s',
'doneCbCallCount': 0
}
];
});
afterEach(function () {
addBidResponse.resetHistory();
done.resetHistory();
});
describe('request function', function () {
let xhr;
let requests;
beforeEach(function () {
xhr = sinon.useFakeXMLHttpRequest();
requests = [];
xhr.onCreate = request => requests.push(request);
config.resetConfig();
resetSyncedStatus();
});
afterEach(function () {
xhr.restore();
});
it('should not add outstrean without renderer', function () {
let ortb2Config = utils.deepClone(CONFIG);
ortb2Config.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
config.setConfig({ s2sConfig: ortb2Config });
adapter.callBids(OUTSTREAM_VIDEO_REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.imp[0].banner).to.exist;
expect(requestBid.imp[0].video).to.not.exist;
});
it('exists and is a function', function () {
expect(adapter.callBids).to.exist.and.to.be.a('function');
});
it('exists converts types', function () {
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid).to.have.property('cache_markup', 2);
expect(requestBid.ad_units[0].bids[0].params.placementId).to.exist.and.to.be.a('number');
expect(requestBid.ad_units[0].bids[0].params.member).to.exist.and.to.be.a('string');
});
describe('gdpr tests', function () {
afterEach(function () {
config.resetConfig();
$$PREBID_GLOBAL$$.requestBids.removeAll();
});
it('adds gdpr consent information to ortb2 request depending on presence of module', function () {
let ortb2Config = utils.deepClone(CONFIG);
ortb2Config.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
let consentConfig = { consentManagement: { cmpApi: 'iab' }, s2sConfig: ortb2Config };
config.setConfig(consentConfig);
let gdprBidRequest = utils.deepClone(BID_REQUESTS);
gdprBidRequest[0].gdprConsent = {
consentString: 'abc123',
gdprApplies: true
};
adapter.callBids(REQUEST, gdprBidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.regs.ext.gdpr).is.equal(1);
expect(requestBid.user.ext.consent).is.equal('abc123');
config.resetConfig();
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
requestBid = JSON.parse(requests[1].requestBody);
expect(requestBid.regs).to.not.exist;
expect(requestBid.user).to.not.exist;
});
it('check gdpr info gets added into cookie_sync request: have consent data', function () {
let cookieSyncConfig = utils.deepClone(CONFIG);
cookieSyncConfig.syncEndpoint = 'https://prebid.adnxs.com/pbs/v1/cookie_sync';
let consentConfig = { consentManagement: { cmpApi: 'iab' }, s2sConfig: cookieSyncConfig };
config.setConfig(consentConfig);
let gdprBidRequest = utils.deepClone(BID_REQUESTS);
gdprBidRequest[0].gdprConsent = {
consentString: 'abc123def',
gdprApplies: true
};
adapter.callBids(REQUEST, gdprBidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.gdpr).is.equal(1);
expect(requestBid.gdpr_consent).is.equal('abc123def');
expect(requestBid.bidders).to.contain('appnexus').and.to.have.lengthOf(1);
expect(requestBid.account).is.equal('1');
});
it('check gdpr info gets added into cookie_sync request: have consent data but gdprApplies is false', function () {
let cookieSyncConfig = utils.deepClone(CONFIG);
cookieSyncConfig.syncEndpoint = 'https://prebid.adnxs.com/pbs/v1/cookie_sync';
let consentConfig = { consentManagement: { cmpApi: 'iab' }, s2sConfig: cookieSyncConfig };
config.setConfig(consentConfig);
let gdprBidRequest = utils.deepClone(BID_REQUESTS);
gdprBidRequest[0].gdprConsent = {
consentString: 'xyz789abcc',
gdprApplies: false
};
adapter.callBids(REQUEST, gdprBidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.gdpr).is.equal(0);
expect(requestBid.gdpr_consent).is.undefined;
});
it('checks gdpr info gets added to cookie_sync request: consent data unknown', function () {
let cookieSyncConfig = utils.deepClone(CONFIG);
cookieSyncConfig.syncEndpoint = 'https://prebid.adnxs.com/pbs/v1/cookie_sync';
let consentConfig = { consentManagement: { cmpApi: 'iab' }, s2sConfig: cookieSyncConfig };
config.setConfig(consentConfig);
let gdprBidRequest = utils.deepClone(BID_REQUESTS);
gdprBidRequest[0].gdprConsent = {
consentString: undefined,
gdprApplies: undefined
};
adapter.callBids(REQUEST, gdprBidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.gdpr).is.undefined;
expect(requestBid.gdpr_consent).is.undefined;
});
});
it('sets invalid cacheMarkup value to 0', function () {
const s2sConfig = Object.assign({}, CONFIG, {
cacheMarkup: 999
});
config.setConfig({ s2sConfig: s2sConfig });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid).to.have.property('cache_markup', 0);
});
it('adds digitrust id is present and user is not optout', function () {
let ortb2Config = utils.deepClone(CONFIG);
ortb2Config.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction';
let consentConfig = { s2sConfig: ortb2Config };
config.setConfig(consentConfig);
let digiTrustObj = {
privacy: {
optout: false
},
id: 'testId',
keyv: 'testKeyV'
};
let digiTrustBidRequest = utils.deepClone(BID_REQUESTS);
digiTrustBidRequest[0].bids[0].userId = { digitrustid: { data: digiTrustObj } };
adapter.callBids(REQUEST, digiTrustBidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.user.ext.digitrust).to.deep.equal({
id: digiTrustObj.id,
keyv: digiTrustObj.keyv
});
digiTrustObj.privacy.optout = true;
adapter.callBids(REQUEST, digiTrustBidRequest, addBidResponse, done, ajax);
requestBid = JSON.parse(requests[1].requestBody);
expect(requestBid.user && request.user.ext && requestBid.user.ext.digitrust).to.not.exist;
});
it('adds device and app objects to request', function () {
const _config = {
s2sConfig: CONFIG,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.device).to.deep.equal({
ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC',
w: window.innerWidth,
h: window.innerHeight
});
expect(requestBid.app).to.deep.equal({
bundle: 'com.test.app',
publisher: { 'id': '1' }
});
});
it('adds device and app objects to request for OpenRTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.device).to.deep.equal({
ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC',
w: window.innerWidth,
h: window.innerHeight
});
expect(requestBid.app).to.deep.equal({
bundle: 'com.test.app',
publisher: { 'id': '1' }
});
});
it('adds device.w and device.h even if the config lacks a device object', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
const _config = {
s2sConfig: s2sConfig,
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.device).to.deep.equal({
w: window.innerWidth,
h: window.innerHeight
});
expect(requestBid.app).to.deep.equal({
bundle: 'com.test.app',
publisher: { 'id': '1' }
});
});
it('adds native request for OpenRTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
const _config = {
s2sConfig: s2sConfig
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.imp[0].native).to.deep.equal({
request: JSON.stringify({
'context': 1,
'plcmttype': 1,
'eventtrackers': [{
event: 1,
methods: [1]
}],
'assets': [
{
'required': 1,
'title': {
'len': 800
}
},
{
'required': 1,
'img': {
'type': 3,
'w': 989,
'h': 742
}
},
{
'required': 1,
'data': {
'type': 1
}
}
]
}),
ver: '1.2'
});
});
it('adds site if app is not present', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
const _config = {
s2sConfig: s2sConfig,
}
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.site).to.exist.and.to.be.a('object');
expect(requestBid.site.publisher).to.exist.and.to.be.a('object');
expect(requestBid.site.page).to.exist.and.to.be.a('string');
});
it('adds appnexus aliases to request', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
config.setConfig({ s2sConfig: s2sConfig });
const aliasBidder = {
bidder: 'brealtime',
params: { placementId: '123456' }
};
const request = utils.deepClone(REQUEST);
request.ad_units[0].bids = [aliasBidder];
adapter.callBids(request, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.ext).to.deep.equal({
prebid: {
aliases: {
brealtime: 'appnexus'
},
targeting: {
includebidderkeys: false,
includewinners: true
}
}
});
});
it('adds dynamic aliases to request', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
config.setConfig({ s2sConfig: s2sConfig });
const alias = 'foobar';
const aliasBidder = {
bidder: alias,
params: { placementId: '123456' }
};
const request = utils.deepClone(REQUEST);
request.ad_units[0].bids = [aliasBidder];
// TODO: stub this
$$PREBID_GLOBAL$$.aliasBidder('appnexus', alias);
adapter.callBids(request, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.ext).to.deep.equal({
prebid: {
aliases: {
[alias]: 'appnexus'
},
targeting: {
includebidderkeys: false,
includewinners: true
}
}
});
});
it('converts appnexus params to expected format for PBS', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
config.setConfig({ s2sConfig: s2sConfig });
const myRequest = utils.deepClone(REQUEST);
myRequest.ad_units[0].bids[0].params.usePaymentRule = true;
myRequest.ad_units[0].bids[0].params.keywords = {
foo: ['bar', 'baz'],
fizz: ['buzz']
};
adapter.callBids(myRequest, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.imp[0].ext.appnexus).to.exist;
expect(requestBid.imp[0].ext.appnexus.placement_id).to.exist.and.to.equal(10433394);
expect(requestBid.imp[0].ext.appnexus.use_pmt_rule).to.exist.and.to.be.true;
expect(requestBid.imp[0].ext.appnexus.member).to.exist;
expect(requestBid.imp[0].ext.appnexus.keywords).to.exist.and.to.deep.equal([{
key: 'foo',
value: ['bar', 'baz']
}, {
key: 'fizz',
value: ['buzz']
}]);
config.resetConfig();
const oldS2sConfig = Object.assign({}, CONFIG);
config.setConfig({ s2sConfig: oldS2sConfig });
const myRequest2 = utils.deepClone(REQUEST);
myRequest2.ad_units[0].bids[0].params.keywords = {
foo: ['bar', 'baz'],
fizz: ['buzz']
};
adapter.callBids(myRequest2, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid2 = JSON.parse(requests[1].requestBody);
expect(requestBid2.ad_units[0].bids[0].params.keywords).to.exist.and.to.deep.equal([{
key: 'foo',
value: ['bar', 'baz']
}, {
key: 'fizz',
value: ['buzz']
}]);
});
it('adds limit to the cookie_sync request if userSyncLimit is greater than 0', function () {
let cookieSyncConfig = utils.deepClone(CONFIG);
cookieSyncConfig.syncEndpoint = 'https://prebid.adnxs.com/pbs/v1/cookie_sync';
cookieSyncConfig.userSyncLimit = 1;
config.setConfig({ s2sConfig: cookieSyncConfig });
let bidRequest = utils.deepClone(BID_REQUESTS);
adapter.callBids(REQUEST, bidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.bidders).to.contain('appnexus').and.to.have.lengthOf(1);
expect(requestBid.account).is.equal('1');
expect(requestBid.limit).is.equal(1);
});
it('does not add limit to cooke_sync request if userSyncLimit is missing or 0', function () {
let cookieSyncConfig = utils.deepClone(CONFIG);
cookieSyncConfig.syncEndpoint = 'https://prebid.adnxs.com/pbs/v1/cookie_sync';
config.setConfig({ s2sConfig: cookieSyncConfig });
let bidRequest = utils.deepClone(BID_REQUESTS);
adapter.callBids(REQUEST, bidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.bidders).to.contain('appnexus').and.to.have.lengthOf(1);
expect(requestBid.account).is.equal('1');
expect(requestBid.limit).is.undefined;
cookieSyncConfig.userSyncLimit = 0;
config.resetConfig();
config.setConfig({ s2sConfig: cookieSyncConfig });
bidRequest = utils.deepClone(BID_REQUESTS);
adapter.callBids(REQUEST, bidRequest, addBidResponse, done, ajax);
requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.bidders).to.contain('appnexus').and.to.have.lengthOf(1);
expect(requestBid.account).is.equal('1');
expect(requestBid.limit).is.undefined;
});
it('adds s2sConfig adapterOptions to request for ORTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction',
adapterOptions: {
appnexus: {
key: 'value'
}
}
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.imp[0].ext.appnexus).to.haveOwnProperty('key');
expect(requestBid.imp[0].ext.appnexus.key).to.be.equal('value')
});
it('when userId is defined on bids, it\'s properties should be copied to user.ext.tpid properties', function () {
let ortb2Config = utils.deepClone(CONFIG);
ortb2Config.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction';
let consentConfig = { s2sConfig: ortb2Config };
config.setConfig(consentConfig);
let userIdBidRequest = utils.deepClone(BID_REQUESTS);
userIdBidRequest[0].bids[0].userId = {
tdid: 'abc123',
pubcid: '1234',
parrableid: '01.1563917337.test-eid',
lipb: {
lipbid: 'li-xyz'
}
};
adapter.callBids(REQUEST, userIdBidRequest, addBidResponse, done, ajax);
let requestBid = JSON.parse(requests[0].requestBody);
expect(typeof requestBid.user.ext.eids).is.equal('object');
expect(Array.isArray(requestBid.user.ext.eids)).to.be.true;
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'adserver.org')).is.not.empty;
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'adserver.org')[0].uids[0].id).is.equal('abc123');
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'pubcommon')).is.not.empty;
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'pubcommon')[0].uids[0].id).is.equal('1234');
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'parrable.com')).is.not.empty;
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'parrable.com')[0].uids[0].id).is.equal('01.1563917337.test-eid');
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'liveintent.com')).is.not.empty;
expect(requestBid.user.ext.eids.filter(eid => eid.source === 'liveintent.com')[0].uids[0].id).is.equal('li-xyz');
});
it('when config \'currency.adServerCurrency\' value is an array: ORTB has property \'cur\' value set to a single item array', function () {
let s2sConfig = utils.deepClone(CONFIG);
s2sConfig.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction';
config.setConfig({
currency: { adServerCurrency: ['USD', 'GB', 'UK', 'AU'] },
s2sConfig: s2sConfig
});
const bidRequests = utils.deepClone(BID_REQUESTS);
adapter.callBids(REQUEST, bidRequests, addBidResponse, done, ajax);
const parsedRequestBody = JSON.parse(requests[0].requestBody);
expect(parsedRequestBody.cur).to.deep.equal(['USD']);
});
it('when config \'currency.adServerCurrency\' value is a string: ORTB has property \'cur\' value set to a single item array', function () {
let s2sConfig = utils.deepClone(CONFIG);
s2sConfig.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction';
config.setConfig({
currency: { adServerCurrency: 'NZ' },
s2sConfig: s2sConfig
});
const bidRequests = utils.deepClone(BID_REQUESTS);
adapter.callBids(REQUEST, bidRequests, addBidResponse, done, ajax);
const parsedRequestBody = JSON.parse(requests[1].requestBody);
expect(parsedRequestBody.cur).to.deep.equal(['NZ']);
});
it('when config \'currency.adServerCurrency\' is unset: ORTB should not define a \'cur\' property', function () {
let s2sConfig = utils.deepClone(CONFIG);
s2sConfig.endpoint = 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction';
config.setConfig({ s2sConfig: s2sConfig });
const bidRequests = utils.deepClone(BID_REQUESTS);
adapter.callBids(REQUEST, bidRequests, addBidResponse, done, ajax);
const parsedRequestBody = JSON.parse(requests[0].requestBody);
expect(typeof parsedRequestBody.cur).to.equal('undefined');
});
it('always add ext.prebid.targeting.includebidderkeys: false for ORTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction',
adapterOptions: {
appnexus: {
key: 'value'
}
}
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.ext.prebid.targeting).to.haveOwnProperty('includebidderkeys');
expect(requestBid.ext.prebid.targeting.includebidderkeys).to.equal(false);
});
it('always add ext.prebid.targeting.includewinners: true for ORTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction',
adapterOptions: {
appnexus: {
key: 'value'
}
}
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.ext.prebid.targeting).to.haveOwnProperty('includewinners');
expect(requestBid.ext.prebid.targeting.includewinners).to.equal(true);
});
it('adds s2sConfig video.ext.prebid to request for ORTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction',
extPrebid: {
foo: 'bar'
}
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid).to.haveOwnProperty('ext');
expect(requestBid.ext).to.haveOwnProperty('prebid');
expect(requestBid.ext.prebid).to.deep.equal({
foo: 'bar',
targeting: {
includewinners: true,
includebidderkeys: false
}
});
});
it('overrides request.ext.prebid properties using s2sConfig video.ext.prebid values for ORTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction',
extPrebid: {
targeting: {
includewinners: false,
includebidderkeys: true
}
}
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid).to.haveOwnProperty('ext');
expect(requestBid.ext).to.haveOwnProperty('prebid');
expect(requestBid.ext.prebid).to.deep.equal({
targeting: {
includewinners: false,
includebidderkeys: true
}
});
});
it('overrides request.ext.prebid properties using s2sConfig video.ext.prebid values for ORTB', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction',
extPrebid: {
cache: {
vastxml: 'vastxml-set-though-extPrebid.cache.vastXml'
},
targeting: {
includewinners: false,
includebidderkeys: false
}
}
});
const _config = {
s2sConfig: s2sConfig,
device: { ifa: '6D92078A-8246-4BA4-AE5B-76104861E7DC' },
app: { bundle: 'com.test.app' },
};
config.setConfig(_config);
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid).to.haveOwnProperty('ext');
expect(requestBid.ext).to.haveOwnProperty('prebid');
expect(requestBid.ext.prebid).to.deep.equal({
cache: {
vastxml: 'vastxml-set-though-extPrebid.cache.vastXml'
},
targeting: {
includewinners: false,
includebidderkeys: false
}
});
});
it('passes schain object in request', function () {
const bidRequests = utils.deepClone(BID_REQUESTS);
const schainObject = {
'ver': '1.0',
'complete': 1,
'nodes': [
{
'asi': 'indirectseller.com',
'sid': '00001',
'hp': 1
},
{
'asi': 'indirectseller-2.com',
'sid': '00002',
'hp': 2
}
]
};
bidRequests[0].bids[0].schain = schainObject;
adapter.callBids(REQUEST, bidRequests, addBidResponse, done, ajax);
const parsedRequestBody = JSON.parse(requests[0].requestBody);
expect(parsedRequestBody.source.ext.schain).to.deep.equal(schainObject);
})
});
describe('response handler', function () {
let server;
let logWarnSpy;
beforeEach(function () {
server = sinon.fakeServer.create();
sinon.stub(utils, 'triggerPixel');
sinon.stub(utils, 'insertUserSyncIframe');
sinon.stub(utils, 'logError');
sinon.stub(events, 'emit');
logWarnSpy = sinon.spy(utils, 'logWarn');
});
afterEach(function () {
server.restore();
utils.triggerPixel.restore();
utils.insertUserSyncIframe.restore();
utils.logError.restore();
events.emit.restore();
logWarnSpy.restore();
});
// TODO: test dependent on pbjs_api_spec. Needs to be isolated
it('registers bids and calls BIDDER_DONE', function () {
server.respondWith(JSON.stringify(RESPONSE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
sinon.assert.calledOnce(events.emit);
const event = events.emit.firstCall.args;
expect(event[0]).to.equal(CONSTANTS.EVENTS.BIDDER_DONE);
expect(event[1].bids[0]).to.have.property('serverResponseTimeMs', 52);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('cpm', 0.5);
expect(response).to.have.property('requestId', '123');
expect(response).to.not.have.property('videoCacheKey');
expect(response).to.have.property('cache_id', '7654321');
expect(response).to.have.property('cache_url', 'http://www.test.com/cache?uuid=7654321');
expect(response).to.not.have.property('vastUrl');
});
it('registers video bids', function () {
server.respondWith(JSON.stringify(VIDEO_RESPONSE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(VIDEO_REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('cpm', 0.5);
expect(response).to.have.property('requestId', '123');
expect(response).to.have.property('videoCacheKey', 'video_cache_id');
expect(response).to.have.property('cache_id', 'video_cache_id');
expect(response).to.have.property('cache_url', 'video_cache_url');
expect(response).to.have.property('vastUrl', 'video_cache_url');
});
it('does not call addBidResponse and calls done when ad unit not set', function () {
server.respondWith(JSON.stringify(RESPONSE_NO_BID_NO_UNIT));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.notCalled(addBidResponse);
sinon.assert.calledOnce(done);
});
it('does not call addBidResponse and calls done when server requests cookie sync', function () {
server.respondWith(JSON.stringify(RESPONSE_NO_COOKIE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.notCalled(addBidResponse);
sinon.assert.calledOnce(done);
});
it('does not call addBidResponse and calls done when ad unit is set', function () {
server.respondWith(JSON.stringify(RESPONSE_NO_BID_UNIT_SET));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.notCalled(addBidResponse);
sinon.assert.calledOnce(done);
});
it('registers successful bids and calls done when there are less bids than requests', function () {
server.respondWith(JSON.stringify(RESPONSE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
sinon.assert.calledOnce(done);
expect(addBidResponse.firstCall.args[0]).to.equal('div-gpt-ad-1460505748561-0');
expect(addBidResponse.firstCall.args[1]).to.have.property('requestId', '123');
expect(addBidResponse.firstCall.args[1])
.to.have.property('statusMessage', 'Bid available');
});
it('should have dealId in bidObject', function () {
server.respondWith(JSON.stringify(RESPONSE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('dealId', 'test-dealid');
});
it('should pass through default adserverTargeting if present in bidObject', function () {
server.respondWith(JSON.stringify(RESPONSE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('adserverTargeting').that.deep.equals({ 'foo': 'bar' });
});
it('registers client user syncs when client bid adapter is present', function () {
let rubiconAdapter = {
registerSyncs: sinon.spy()
};
sinon.stub(adapterManager, 'getBidAdapter').callsFake(() => rubiconAdapter);
server.respondWith(JSON.stringify(RESPONSE_NO_PBS_COOKIE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(rubiconAdapter.registerSyncs);
adapterManager.getBidAdapter.restore();
});
it('registers client user syncs when using OpenRTB endpoint', function () {
let rubiconAdapter = {
registerSyncs: sinon.spy()
};
sinon.stub(adapterManager, 'getBidAdapter').returns(rubiconAdapter);
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
config.setConfig({ s2sConfig });
server.respondWith(JSON.stringify(RESPONSE_OPENRTB));
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(rubiconAdapter.registerSyncs);
adapterManager.getBidAdapter.restore();
});
it('registers bid responses when server requests cookie sync', function () {
server.respondWith(JSON.stringify(RESPONSE_NO_PBS_COOKIE));
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const ad_unit_code = addBidResponse.firstCall.args[0];
expect(ad_unit_code).to.equal('div-gpt-ad-1460505748561-0');
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('source', 's2s');
const bid_request_passed = addBidResponse.firstCall.args[1];
expect(bid_request_passed).to.have.property('requestId', '123');
});
it('handles OpenRTB responses and call BIDDER_DONE', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebid.adnxs.com/pbs/v1/openrtb2/auction'
});
config.setConfig({ s2sConfig });
server.respondWith(JSON.stringify(RESPONSE_OPENRTB));
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(events.emit);
const event = events.emit.firstCall.args;
expect(event[0]).to.equal(CONSTANTS.EVENTS.BIDDER_DONE);
expect(event[1].bids[0]).to.have.property('serverResponseTimeMs', 8);
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('bidderCode', 'appnexus');
expect(response).to.have.property('requestId', '123');
expect(response).to.have.property('cpm', 0.5);
});
it('handles OpenRTB video responses', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebidserverurl/openrtb2/auction?querystring=param'
});
config.setConfig({ s2sConfig });
server.respondWith(JSON.stringify(RESPONSE_OPENRTB_VIDEO));
adapter.callBids(VIDEO_REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('vastXml', RESPONSE_OPENRTB_VIDEO.seatbid[0].bid[0].adm);
expect(response).to.have.property('mediaType', 'video');
expect(response).to.have.property('bidderCode', 'appnexus');
expect(response).to.have.property('requestId', '123');
expect(response).to.have.property('cpm', 10);
});
it('handles response cache from ext.prebid.cache.vastXml', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebidserverurl/openrtb2/auction?querystring=param'
});
config.setConfig({ s2sConfig });
const cacheResponse = utils.deepClone(RESPONSE_OPENRTB_VIDEO);
cacheResponse.seatbid.forEach(item => {
item.bid[0].ext.prebid.cache = {
vastXml: {
cacheId: 'abcd1234',
url: 'https://prebid-cache.net/cache?uuid=abcd1234'
}
}
});
server.respondWith(JSON.stringify(cacheResponse));
adapter.callBids(VIDEO_REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('videoCacheKey', 'abcd1234');
expect(response).to.have.property('vastUrl', 'https://prebid-cache.net/cache?uuid=abcd1234');
});
it('add adserverTargeting object to bids when ext.prebid.targeting is defined', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebidserverurl/openrtb2/auction?querystring=param'
});
config.setConfig({ s2sConfig });
const cacheResponse = utils.deepClone(RESPONSE_OPENRTB_VIDEO);
const targetingTestData = {
hb_cache_path: '/cache',
hb_cache_host: 'prebid-cache.testurl.com'
};
cacheResponse.seatbid.forEach(item => {
item.bid[0].ext.prebid.targeting = targetingTestData
});
server.respondWith(JSON.stringify(cacheResponse));
adapter.callBids(VIDEO_REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('adserverTargeting');
expect(response.adserverTargeting).to.deep.equal({
'hb_cache_path': '/cache',
'hb_cache_host': 'prebid-cache.testurl.com'
});
});
it('handles response cache from ext.prebid.targeting', function () {
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebidserverurl/openrtb2/auction?querystring=param'
});
config.setConfig({ s2sConfig });
const cacheResponse = utils.deepClone(RESPONSE_OPENRTB_VIDEO);
cacheResponse.seatbid.forEach(item => {
item.bid[0].ext.prebid.targeting = {
hb_uuid: 'a5ad3993',
hb_cache_host: 'prebid-cache.net',
hb_cache_path: '/cache'
}
});
server.respondWith(JSON.stringify(cacheResponse));
adapter.callBids(VIDEO_REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('videoCacheKey', 'a5ad3993');
expect(response).to.have.property('vastUrl', 'https://prebid-cache.net/cache?uuid=a5ad3993');
});
it('handles OpenRTB native responses', function () {
sinon.stub(utils, 'getBidRequest').returns({
adUnitCode: 'div-gpt-ad-1460505748561-0',
bidder: 'appnexus',
bidId: '123'
});
const s2sConfig = Object.assign({}, CONFIG, {
endpoint: 'https://prebidserverurl/openrtb2/auction?querystring=param'
});
config.setConfig({ s2sConfig });
server.respondWith(JSON.stringify(RESPONSE_OPENRTB_NATIVE));
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(addBidResponse);
const response = addBidResponse.firstCall.args[1];
expect(response).to.have.property('statusMessage', 'Bid available');
expect(response).to.have.property('adm').deep.equal(RESPONSE_OPENRTB_NATIVE.seatbid[0].bid[0].adm);
expect(response).to.have.property('mediaType', 'native');
expect(response).to.have.property('bidderCode', 'appnexus');
expect(response).to.have.property('requestId', '123');
expect(response).to.have.property('cpm', 10);
utils.getBidRequest.restore();
});
it('should log warning for unsupported bidder', function () {
server.respondWith(JSON.stringify(RESPONSE_UNSUPPORTED_BIDDER));
const s2sConfig = Object.assign({}, CONFIG, {
bidders: ['33Across']
});
const _config = {
s2sConfig: s2sConfig,
}
config.setConfig(_config);
config.setConfig({ s2sConfig: CONFIG });
adapter.callBids(REQUEST, BID_REQUESTS, addBidResponse, done, ajax);
server.respond();
sinon.assert.calledOnce(logWarnSpy);
});
});
describe('s2sConfig', function () {
let xhr;
let requests;
let logErrorSpy;
beforeEach(function () {
xhr = sinon.useFakeXMLHttpRequest();
requests = [];
xhr.onCreate = request => requests.push(request);
logErrorSpy = sinon.spy(utils, 'logError');
resetSyncedStatus();
});
afterEach(function () {
xhr.restore();
utils.logError.restore();
});
it('should log an error when accountId is missing', function () {
const options = {
enabled: true,
bidders: ['appnexus'],
timeout: 1000,
adapter: 'prebidServer',
endpoint: 'https://prebid.adnxs.com/pbs/v1/auction'
};
config.setConfig({ s2sConfig: options });
sinon.assert.calledOnce(logErrorSpy);
});
it('should log an error when bidders is missing', function () {
const options = {
accountId: '1',
enabled: true,
timeout: 1000,
adapter: 's2s',
endpoint: 'https://prebid.adnxs.com/pbs/v1/auction'
};
config.setConfig({ s2sConfig: options });
sinon.assert.calledOnce(logErrorSpy);
});
it('should log an error when endpoint is missing', function () {
const options = {
accountId: '1',
bidders: ['appnexus'],
timeout: 1000,
enabled: true,
adapter: 'prebidServer'
};
config.setConfig({ s2sConfig: options });
sinon.assert.calledOnce(logErrorSpy);
});
it('should log an error when using an unknown vendor', function () {
const options = {
accountId: '1',
bidders: ['appnexus'],
defaultVendor: 'mytest'
};
config.setConfig({ s2sConfig: options });
sinon.assert.calledOnce(logErrorSpy);
});
it('should configure the s2sConfig object with appnexus vendor defaults unless specified by user', function () {
const options = {
accountId: '123',
bidders: ['appnexus'],
defaultVendor: 'appnexus',
timeout: 750
};
config.setConfig({ s2sConfig: options });
sinon.assert.notCalled(logErrorSpy);
let vendorConfig = config.getConfig('s2sConfig');
expect(vendorConfig).to.have.property('accountId', '123');
expect(vendorConfig).to.have.property('adapter', 'prebidServer');
expect(vendorConfig.bidders).to.deep.equal(['appnexus']);
expect(vendorConfig.enabled).to.be.true;
expect(vendorConfig).to.have.property('endpoint', '//prebid.adnxs.com/pbs/v1/openrtb2/auction');
expect(vendorConfig).to.have.property('syncEndpoint', '//prebid.adnxs.com/pbs/v1/cookie_sync');
expect(vendorConfig).to.have.property('timeout', 750);
});
it('should configure the s2sConfig object with rubicon vendor defaults unless specified by user', function () {
const options = {
accountId: 'abc',
bidders: ['rubicon'],
defaultVendor: 'rubicon',
timeout: 750
};
config.setConfig({ s2sConfig: options });
sinon.assert.notCalled(logErrorSpy);
let vendorConfig = config.getConfig('s2sConfig');
expect(vendorConfig).to.have.property('accountId', 'abc');
expect(vendorConfig).to.have.property('adapter', 'prebidServer');
expect(vendorConfig.bidders).to.deep.equal(['rubicon']);
expect(vendorConfig.enabled).to.be.true;
expect(vendorConfig).to.have.property('endpoint', '//prebid-server.rubiconproject.com/openrtb2/auction');
expect(vendorConfig).to.have.property('syncEndpoint', '//prebid-server.rubiconproject.com/cookie_sync');
expect(vendorConfig).to.have.property('timeout', 750);
});
it('should return proper defaults', function () {
expect(config.getConfig('s2sConfig')).to.deep.equal({
'accountId': 'abc',
'adapter': 'prebidServer',
'bidders': ['rubicon'],
'defaultVendor': 'rubicon',
'enabled': true,
'endpoint': '//prebid-server.rubiconproject.com/openrtb2/auction',
'syncEndpoint': '//prebid-server.rubiconproject.com/cookie_sync',
'timeout': 750
})
});
it('should return default adapterOptions if not set', function () {
config.setConfig({
s2sConfig: {
accountId: 'abc',
bidders: ['rubicon'],
defaultVendor: 'rubicon',
timeout: 750
}
});
expect(config.getConfig('s2sConfig')).to.deep.equal({
enabled: true,
timeout: 750,
adapter: 'prebidServer',
accountId: 'abc',
bidders: ['rubicon'],
defaultVendor: 'rubicon',
endpoint: '//prebid-server.rubiconproject.com/openrtb2/auction',
syncEndpoint: '//prebid-server.rubiconproject.com/cookie_sync'
})
});
it('should set adapterOptions', function () {
config.setConfig({
s2sConfig: {
adapterOptions: {
rubicon: {
singleRequest: true,
foo: 'bar'
}
}
}
});
expect(config.getConfig('s2sConfig').adapterOptions).to.deep.equal({
rubicon: {
singleRequest: true,
foo: 'bar'
}
})
});
it('should set syncUrlModifier', function () {
config.setConfig({
s2sConfig: {
syncUrlModifier: {
appnexus: () => { }
}
}
});
expect(typeof config.getConfig('s2sConfig').syncUrlModifier.appnexus).to.equal('function')
});
it('should set correct bidder names to bidders property when using an alias for that bidder', function () {
const s2sConfig = utils.deepClone(CONFIG);
// Add syncEndpoint so that the request goes to the User Sync endpoint
// Modify the bidders property to include an alias for Rubicon adapter
s2sConfig.syncEndpoint = 'https://prebid.adnxs.com/pbs/v1/cookie_sync';
s2sConfig.bidders = ['appnexus', 'rubicon-alias'];
const request = utils.deepClone(REQUEST);
// Add another bidder, `rubicon-alias`
request.ad_units[0].bids.push({
bidder: 'rubicon-alias',
params: {
accoundId: 14062,
siteId: 70608,
zoneId: 498816
}
});
// create an alias for the Rubicon Bid Adapter
adapterManager.aliasBidAdapter('rubicon', 'rubicon-alias');
config.setConfig({ s2sConfig });
const bidRequest = utils.deepClone(BID_REQUESTS);
bidRequest.push({
'bidderCode': 'rubicon-alias',
'auctionId': '4146ab2b-9422-4040-9b1c-966fffbfe2d4',
'bidderRequestId': '4b1a4f9c3e4546',
'tid': 'd7fa8342-ae22-4ca1-b237-331169350f84',
'bids': [
{
'bidder': 'rubicon-alias',
'params': {
'accountId': 14062,
'siteId': 70608,
'zoneId': 498816
},
'bid_id': '2a9523915411c3',
'mediaTypes': {
'banner': {
'sizes': [
[
300,
250
]
]
}
},
'adUnitCode': 'div-gpt-ad-1460505748561-0',
'transactionId': '78ddc106-b7d8-45d1-bd29-86993098e53d',
'sizes': [
[
300,
250
]
],
'bidId': '2a9523915411c3',
'bidderRequestId': '4b1a4f9c3e4546',
'auctionId': '4146ab2b-9422-4040-9b1c-966fffbfe2d4'
}
],
'auctionStart': 1569234122602,
'timeout': 1000,
'src': 's2s'
});
adapter.callBids(request, bidRequest, addBidResponse, done, ajax);
const requestBid = JSON.parse(requests[0].requestBody);
expect(requestBid.bidders).to.deep.equal(['appnexus', 'rubicon']);
});
});
});
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export default {
getErrorTypeByErrorCode: function(code) {
var errorType = '';
if (code) {
switch (code) {
case "500":
errorType = "Internal Server Error";
break;
case "502":
errorType = "Bad Gateway";
break;
case "503":
errorType = "Service Unavailable";
break;
case "400":
errorType = "Bad Request";
break;
case "403":
errorType = "Forbidden";
break;
case "404":
errorType = "Not Found";
break;
case "401":
errorType = "Authorization required";
break;
default:
errorType = "";
break;
}
}
return errorType;
},
stripErrorCodeAndMessageFromError: function(err) {
var obj = {};
if (err && err.errors && err.errors[0]) {
obj.errorCode = err.errors[0].status || "";
obj.title = err.errors[0].title || "";
obj.errorType = this.getErrorTypeByErrorCode(err.errors[0].status);
}
return obj;
}
};
|
import React, { Component } from 'react';
import client from '../../data/contentful';
import FontAwesome from 'react-fontawesome';
import styles from './styles.scss';
import NavBar from '../navbar/';
class Hero extends Component {
constructor() {
super()
this.state = {
tangoBanner: ''
}
}
componentDidMount() {
this.getImage('6FCIxd7wyskIOQ6iCKWCw2')
}
getImage(bannerId) {
client.getAsset(bannerId)
.then(asset => {
const bannerURL = asset.fields.file.url
this.setState({tangoBanner: bannerURL})
})
.catch(console.error)
}
render() {
const bannerBG = {
backgroundImage:
`linear-gradient(135deg, rgba(26, 26, 26, 0.5) 0%,rgba(26, 26, 26, 0.8) 100%), url(${this.state.tangoBanner}) `
}
return (
<div className="heroImageContainer">
<NavBar />
<div className="heroBackgroundImage" style={bannerBG}>
<div className="heroTitleContain" >
<p className="heroTitle">Tango</p>
<p className="heroSubTitle"> Tropical Grill Vietnamese & Thai Cuisine </p>
<a className="heroButton" data-scroll href="#contact">Contact</a>
</div>
</div>
<div className="heroJump">
<a style={{color:'inherit'}} href="#specials">
<FontAwesome name="angle-down" size="3x"/>
</a>
</div>
</div>
);
}
}
export default Hero;
|
/**
* Created by Administrator on 2017/9/12 0012.
*/
var _ =require('underscore');
var Player = require('./Player');
var zhuoguiMgr = function () {
this.guiNum = 0;
this.di = 0;
this.gui = [];
this.players = [];
this.seatIndex = 0;
this.trun = 0;
this.countBySeat = {};
this.playersBySeat = {};
this.thisTrunDrank ={};
}
var pro = zhuoguiMgr.prototype;
pro.getGui = function () {
return this.gui;
}
pro.init = function (app,guinum,di) {
this.app = app;
this.guiNum = guinum;
this.di = di;
}
// 定鬼
pro.dingGui2 =function () {
for(var i=0;i<this.guiNum;i++){
var gui = _.random(1,6);
this.gui.push(gui);
}
};
pro.zhangui = function (seatIndex,craps) {
if(!this.gui){
return;
}
this.countBySeat[seatIndex] = craps;
this.pushAll('zhangui',{seat:seatIndex,craps:craps});
if(this.countBySeat.length == this.players){
this.pushAll('gameBegin',{trun:this.trun});
}
};
//
function shangjiahei(seatIndex) {
if(seatIndex-1<0){
}else {
}
}
pro.shoot = function (seatIndex,crap1,crap2) {
var totalValue = crap1 + crap2;
switch (totalValue){
case 7:
shangjiahei(seatIndex);
break;
case 8:
}
}
pro.addPlayer = function (uid) {
var self = this;
if(this.players.valueOf(uid)==-1){
var player = new Player({uid:uid,seat:self.seatIndex});
this.players.push(player);
this.seatIndex++;
}
}
pro.pushAll = function (route,msg) {
var channelService = this.app.get('channelService');
var channel = channelService.getChannel(1, false);
channel.pushMessage(route, msg);
}
pro.begin = function () {
this.dingGui2();
this.pushAll('dinggui',{gui:this.gui});
};
var _gInstance = null;
module.exports.getInstance = function () {
if(!_gInstance){
_gInstance = new zhuoguiMgr();
}
return _gInstance;
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7 3v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2H9c-1.1 0-2 .9-2 2zm2.5 12.5c.29-.12.55-.29.8-.48l-.02.03 1.01.39c.23.09.49 0 .61-.22l.84-1.46c.12-.21.07-.49-.12-.64l-.85-.68-.02.03c.02-.16.05-.32.05-.48s-.03-.32-.05-.48l.02.03.85-.68c.19-.15.24-.43.12-.64l-.84-1.46c-.12-.21-.38-.31-.61-.22l-1.01.39.02.03c-.25-.17-.51-.34-.8-.46l-.17-1.08C9.3 7.18 9.09 7 8.84 7H7.16c-.25 0-.46.18-.49.42L6.5 8.5c-.29.12-.55.29-.8.48l.02-.03-1.02-.39c-.23-.09-.49 0-.61.22l-.84 1.46c-.12.21-.07.49.12.64l.85.68.02-.03c-.02.15-.05.31-.05.47s.03.32.05.48l-.02-.03-.85.68c-.19.15-.24.43-.12.64l.84 1.46c.12.21.38.31.61.22l1.01-.39-.01-.04c.25.19.51.36.8.48l.17 1.07c.03.25.24.43.49.43h1.68c.25 0 .46-.18.49-.42l.17-1.08zM6 12c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2z" />
, 'PhonelinkSetupTwoTone');
|
var capitalAlphabet = ['Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'];
var alphabet = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'];
var special = ['`','~','!','@','#','$','%','^','&','*','(',')','_','=',';',':',',','<','.','>','/','?',' '];
var numberDelimeters = ['_'].concat(alphabet).concat(capitalAlphabet).concat(special);
var letterDelimeters = ['0','1','2','3','4','5','6','7','8','9','-'];
function encode(input)
{
var ret = "";
for (var i = 0; i < input.length; i++) {
var character = input.charAt(i);
//console.log(character,special.indexOf(character));
if (special.indexOf(character)!=-1) {
var source = Math.floor(Math.random()*special.length);
var destination = special.indexOf(character);
if(destination==-1) {
//Uh oh error!!! Just skip it!
ret+="0?";
}
//Get delta
var delta = destination-source;
ret += delta;
ret += special[source];
//console.log(delta,special[destination],special[source],destination,source);
} else if (character == character.toUpperCase()) {
//Select source character
var source = Math.floor(Math.random()*capitalAlphabet.length);
var destination = capitalAlphabet.indexOf(character);
if(destination==-1) {
//Uh oh error!!! Just skip it!
ret+="0?";
}
//Get delta
var delta = destination-source;
ret += delta;
ret += capitalAlphabet[source];
//console.log(delta,capitalAlphabet[destination],capitalAlphabet[source],destination,source);
} else if (character == character.toLowerCase()){
//Select source character
var source = Math.floor(Math.random()*alphabet.length);
var destination = alphabet.indexOf(character);
if(destination==-1) {
//Uh oh error!!! Just skip it!
ret+="0?";
}
//Get delta
var delta = destination-source;
ret += delta;
ret += alphabet[source];
//console.log(delta,capitalAlphabet[destination],capitalAlphabet[source],destination,source);
}
}
return ret;
}
function decode(input)
{
var ret = "";
var numbers = splitMultiple(input,numberDelimeters);
var letters = splitMultiple(input,letterDelimeters);
//console.log(numbers);
if(numbers.length!=letters.length) return "Error";
for (var i = 0; i < letters.length; i++) {
var character = letters[i];
var source = -1;
var isCapital = false;
//console.log(special.indexOf(character));
if (special.indexOf(character)!=-1) {
source = special.indexOf(character);
var delta = Number(numbers[i]);
var destination = source+delta; //Using communitive property
//console.log(delta,special[source],special[destination]);
ret += special[destination];
continue;
} else if (character == character.toUpperCase()) {
isCapital = true;
source = capitalAlphabet.indexOf(character);
} else if (character == character.toLowerCase()){
source = alphabet.indexOf(character);
}
if(source==-1)
{
ret += "?";
continue;
}
var delta = Number(numbers[i]);
var destination = source+delta; //Using communitive property
//console.log(destination);
if(isCapital) ret += capitalAlphabet[destination]; else ret += alphabet[destination];
}
return ret;
}
function splitMultiple(source,delimeters)
{
var pieces = [];
pieces.push(source);
var newPieces = [];
for (var i = 0; i < delimeters.length; i++) {
var currentdelimeter = delimeters[i];
for (var j = 0; j < pieces.length; j++) {
var piecesPieces = pieces[j].split(currentdelimeter);
for (var k = 0; k < piecesPieces.length; k++)
newPieces.push(piecesPieces[k]);
}
pieces = newPieces;
newPieces = [];
}
return pieces.filter(function(e){ return e === 0 || e });
}
//UI
function encodeUI()
{
document.getElementById("encodeOut").innerText = encode(document.getElementById("encode").value);
}
function decodeUI()
{
document.getElementById("decodeOut").innerText = decode(document.getElementById("decode").value);
}
|
"use strict";
/**
* Created by ngtmuzi on 2018/2/10.
*/
Object.defineProperty(exports, "__esModule", { value: true });
const lodash = require("lodash");
exports.default = pave;
/**
* 展平对象
* {a:1, b:{c:1,d:{e:[2]}}} -> {a:1,'b.c':1,'b.d.e':[2]}
* @param obj
* @param pre
* @param split
* @returns {*}
*/
function pave(obj, pre = '', split = '.') {
if (!lodash.isPlainObject(obj))
throw new TypeError(`pave() need a Object but got a ` + typeof obj);
return Object.assign({}, ...lodash.flatMap(obj, (value, key) => {
if (lodash.isPlainObject(value))
return pave(value, `${pre && (pre + split)}${key}`, split);
else
return { [`${pre && (pre + split)}${key}`]: value };
}));
}
|
/*
* Copyright 2022 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { __ } from '@googleforcreators/i18n';
import PropTypes from 'prop-types';
import styled from 'styled-components';
export const SubMenuContainer = styled.div`
position: absolute;
top: ${({ position }) => position?.y ?? 0}px;
left: ${({ position }) => position?.x ?? 0}px;
z-index: 9999;
`;
SubMenuContainer.propTypes = {
position: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }),
};
export const DEFAULT_DISPLACEMENT = 210;
export const SUB_MENU_ARIA_LABEL = __('Select a layer', 'web-stories');
export const MenuPropType = {
parentMenuRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.shape({ current: PropTypes.instanceOf(Element) }),
]).isRequired,
};
|
var fs = require('fs')
var path = require('path')
var test = require('tape')
var tempDir = require('temporary-directory')
var spawn = require('./helpers/spawn.js')
var help = require('./helpers')
var dwebx = path.resolve(path.join(__dirname, '..', 'bin', 'cli.js'))
test('clone - default opts', function (t) {
help.shareFixtures(function (_, shareDat) {
var key = shareDat.key.toString('hex')
tempDir(function (_, dir, cleanup) {
var cmd = dwebx + ' clone ' + key
var st = spawn(t, cmd, { cwd: dir })
var datDir = path.join(dir, key)
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
var stats = shareDat.stats.get()
var fileRe = new RegExp(stats.files + ' files')
var bytesRe = new RegExp(/1\.\d KB/)
t.ok(output.match(fileRe), 'total size: files okay')
t.ok(output.match(bytesRe), 'total size: bytes okay')
t.ok(help.isDir(datDir), 'creates download directory')
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
// Right now we aren't forcing this
// test('clone - errors on existing dir', function (t) {
// tempDir(function (_, dir, cleanup) {
// // make empty dwebx in directory
// DWebX(dir, function (err, shareDat) {
// t.error(err, 'no error')
// // Try to clone to same dir
// shareDat.close(function () {
// var cmd = dwebx + ' clone ' + shareDat.key.toString('hex') + ' ' + dir
// var st = spawn(t, cmd)
// st.stdout.empty()
// st.stderr.match(function (output) {
// t.same(output.trim(), 'Existing archive in this directory. Use pull or sync to update.', 'Existing archive.')
// st.kill()
// return true
// })
// st.end(cleanup)
// })
// })
// })
// })
test('clone - specify dir', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
var key = shareDat.key.toString('hex')
var customDir = 'my_dir'
var cmd = dwebx + ' clone ' + key + ' ' + customDir
var st = spawn(t, cmd, { cwd: dir })
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
t.ok(help.isDir(path.join(dir, customDir)), 'creates download directory')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
test('clone - dwebx:// link', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
var key = 'dwebx://' + shareDat.key.toString('hex') + '/'
var cmd = dwebx + ' clone ' + key + ' '
var downloadDir = path.join(dir, shareDat.key.toString('hex'))
var st = spawn(t, cmd, { cwd: dir })
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
t.ok(help.isDir(path.join(downloadDir)), 'creates download directory')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
test('clone - dwebx.org/key link', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
var key = 'dwebx.org/' + shareDat.key.toString('hex') + '/'
var cmd = dwebx + ' clone ' + key + ' '
var downloadDir = path.join(dir, shareDat.key.toString('hex'))
var st = spawn(t, cmd, { cwd: dir })
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
t.ok(help.isDir(path.join(downloadDir)), 'creates download directory')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
// TODO: fix --temp for clones
// test('clone - with --temp', function (t) {
// // cmd: dwebx clone <link>
// help.shareFixtures(function (_, fixturesDat) {
// shareDat = fixturesDat
// var key = shareDat.key.toString('hex')
// var cmd = dwebx + ' clone ' + key + ' --temp'
// var st = spawn(t, cmd, {cwd: baseTestDir})
// var datDir = path.join(baseTestDir, key)
// st.stdout.match(function (output) {
// var downloadFinished = output.indexOf('Download Finished') > -1
// if (!downloadFinished) return false
// var stats = shareDat.stats.get()
// var fileRe = new RegExp(stats.filesTotal + ' files')
// var bytesRe = new RegExp(/1\.\d{1,2} kB/)
// t.ok(help.matchLink(output), 'prints link')
// t.ok(output.indexOf('dwebx-download-folder/' + key) > -1, 'prints dir')
// t.ok(output.match(fileRe), 'total size: files okay')
// t.ok(output.match(bytesRe), 'total size: bytes okay')
// t.ok(help.isDir(datDir), 'creates download directory')
// var fileList = help.fileList(datDir).join(' ')
// var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
// t.ok(hasCsvFile, 'csv file downloaded')
// var hasDatFolder = fileList.indexOf('.dwebx') > -1
// t.ok(!hasDatFolder, '.dwebx folder not created')
// var hasSubDir = fileList.indexOf('folder') > -1
// t.ok(hasSubDir, 'folder created')
// var hasNestedDir = fileList.indexOf('nested') > -1
// t.ok(hasNestedDir, 'nested folder created')
// var hasHelloFile = fileList.indexOf('hello.txt') > -1
// t.ok(hasHelloFile, 'hello.txt file downloaded')
// st.kill()
// return true
// })
// st.succeeds('exits after finishing download')
// st.stderr.empty()
// st.end()
// })
// })
test('clone - invalid link', function (t) {
var key = 'best-key-ever'
var cmd = dwebx + ' clone ' + key
tempDir(function (_, dir, cleanup) {
var st = spawn(t, cmd, { cwd: dir })
var datDir = path.join(dir, key)
st.stderr.match(function (output) {
var error = output.indexOf('Could not resolve link') > -1
if (!error) return false
t.ok(error, 'has error')
t.ok(!help.isDir(datDir), 'download dir removed')
st.kill()
return true
})
st.end(cleanup)
})
})
test('clone - shortcut/stateless clone', function (t) {
help.shareFixtures(function (_, shareDat) {
var key = shareDat.key.toString('hex')
tempDir(function (_, dir, cleanup) {
var datDir = path.join(dir, key)
var cmd = dwebx + ' ' + key + ' ' + datDir + ' --exit'
var st = spawn(t, cmd)
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
t.ok(help.isDir(datDir), 'creates download directory')
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
// TODO: fix this
// test('clone - ddatabase link', function (t) {
// help.shareFeed(function (_, key, close) {
// tempDir(function (_, dir, cleanup) {
// var cmd = dwebx + ' clone ' + key
// var st = spawn(t, cmd, {cwd: dir})
// var datDir = path.join(dir, key)
// st.stderr.match(function (output) {
// var error = output.indexOf('not a DWebX Archive') > -1
// if (!error) return false
// t.ok(error, 'has error')
// t.ok(!help.isDir(datDir), 'download dir removed')
// st.kill()
// return true
// })
// st.end(function () {
// cleanup()
// close()
// })
// })
// })
// })
test('clone - specify directory containing dwebx.json', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
fs.writeFileSync(path.join(dir, 'dwebx.json'), JSON.stringify({ url: shareDat.key.toString('hex') }), 'utf8')
// dwebx clone /dir
var cmd = dwebx + ' clone ' + dir
var st = spawn(t, cmd)
var datDir = dir
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
test('clone - specify directory containing dwebx.json with cwd', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
fs.writeFileSync(path.join(dir, 'dwebx.json'), JSON.stringify({ url: shareDat.key.toString('hex') }), 'utf8')
// cd dir && dwebx clone /dir/dwebx.json
var cmd = dwebx + ' clone ' + dir
var st = spawn(t, cmd, { cwd: dir })
var datDir = dir
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
test('clone - specify dwebx.json path', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
var datJsonPath = path.join(dir, 'dwebx.json')
fs.writeFileSync(datJsonPath, JSON.stringify({ url: shareDat.key.toString('hex') }), 'utf8')
// dwebx clone /dir/dwebx.json
var cmd = dwebx + ' clone ' + datJsonPath
var st = spawn(t, cmd)
var datDir = dir
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
test('clone - specify dwebx.json path with cwd', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
var datJsonPath = path.join(dir, 'dwebx.json')
fs.writeFileSync(datJsonPath, JSON.stringify({ url: shareDat.key.toString('hex') }), 'utf8')
// cd /dir && dwebx clone /dir/dwebx.json
var cmd = dwebx + ' clone ' + datJsonPath
var st = spawn(t, cmd, { cwd: dir })
var datDir = dir
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
test('clone - specify dwebx.json + directory', function (t) {
help.shareFixtures(function (_, shareDat) {
tempDir(function (_, dir, cleanup) {
var datDir = path.join(dir, 'clone-dest')
var datJsonPath = path.join(dir, 'dwebx.json') // make dwebx.json in different dir
fs.mkdirSync(datDir)
fs.writeFileSync(datJsonPath, JSON.stringify({ url: shareDat.key.toString('hex') }), 'utf8')
// dwebx clone /dir/dwebx.json /dir/clone-dest
var cmd = dwebx + ' clone ' + datJsonPath + ' ' + datDir
var st = spawn(t, cmd)
st.stdout.match(function (output) {
var downloadFinished = output.indexOf('Exiting') > -1
if (!downloadFinished) return false
var fileList = help.fileList(datDir).join(' ')
var hasCsvFile = fileList.indexOf('all_hour.csv') > -1
t.ok(hasCsvFile, 'csv file downloaded')
var hasDatFolder = fileList.indexOf('.dwebx') > -1
t.ok(hasDatFolder, '.dwebx folder created')
var hasSubDir = fileList.indexOf('folder') > -1
t.ok(hasSubDir, 'folder created')
var hasNestedDir = fileList.indexOf('nested') > -1
t.ok(hasNestedDir, 'nested folder created')
var hasHelloFile = fileList.indexOf('hello.txt') > -1
t.ok(hasHelloFile, 'hello.txt file downloaded')
st.kill()
return true
})
st.succeeds('exits after finishing download')
st.stderr.empty()
st.end(function () {
cleanup()
shareDat.close()
})
})
})
})
|
import { DecimalChanta } from "../../lib/b2c6/mathematics/DecimalChanta";
test('Testing Instantiating of DecimalChanta', () => {
let a = new DecimalChanta(11.5);
expect(a.toString()).toBe("11.5");
DecimalChanta.precision = 97;
a = new DecimalChanta("11.5346141710991074111232578901231234387777733339904343464574908070735623435479797897857434567625943");
expect(a.toString()).toBe("11.5346141710991074111232578901231234387777733339904343464574908070735623435479797897857434567625943");
DecimalChanta.precision = 32;
return;
});
test('Testing adding of DecimalChanta', () => {
DecimalChanta.precision = 32;
const a = new DecimalChanta(11.5);
const b = new DecimalChanta(1.18);
const c = a.add(b);
expect(c.toString()).toBe("12.68");
});
test('Testing substracting of DecimalChanta', () => {
DecimalChanta.precision = 32;
const a = new DecimalChanta(11.5);
const b = new DecimalChanta(1.18);
const c = a.substract(b);
expect(c.toString()).toBe("10.32");
});
test('Testing multiplying of DecimalChanta', () => {
DecimalChanta.precision = 32;
const a = new DecimalChanta(11.5);
const b = new DecimalChanta(1.18);
const c = a.multiply(b);
expect(c.toString()).toBe("13.57");
});
test('Testing division of DecimalChanta', () => {
DecimalChanta.precision = 32;
const a = new DecimalChanta(11.5);
const b = new DecimalChanta(1.18);
const c = a.divide(b);
expect(c.toString()).toBe("9.74576271186440677966101694915254");
});
test('Testing result of arithmetic operations in DecimalChanta', () => {
DecimalChanta.precision = 32;
const a = new DecimalChanta(11.5);
const b = new DecimalChanta(1.18);
const c = a.divide(b);
const aAgain = c.multiply(b);
expect(a.toString()).toBe(aAgain.toString());
const expected = "9.74576271186440677966101694915254";
expect(c.toString()).toBe(expected);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.