code stringlengths 2 1.05M |
|---|
import * as i0 from '@angular/core';
import { Component, ChangeDetectionStrategy, ViewEncapsulation, Input, ContentChild, ContentChildren, NgModule } from '@angular/core';
import * as i1 from '@angular/common';
import { CommonModule } from '@angular/common';
import { Header, Footer, PrimeTemplate, SharedModule } from 'primeng/api';
class Card {
constructor(el) {
this.el = el;
}
ngAfterContentInit() {
this.templates.forEach((item) => {
switch (item.getType()) {
case 'header':
this.headerTemplate = item.template;
break;
case 'title':
this.titleTemplate = item.template;
break;
case 'subtitle':
this.subtitleTemplate = item.template;
break;
case 'content':
this.contentTemplate = item.template;
break;
case 'footer':
this.footerTemplate = item.template;
break;
default:
this.contentTemplate = item.template;
break;
}
});
}
getBlockableElement() {
return this.el.nativeElement.children[0];
}
}
Card.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: Card, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Component });
Card.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.0.4", type: Card, selector: "p-card", inputs: { header: "header", subheader: "subheader", style: "style", styleClass: "styleClass" }, queries: [{ propertyName: "headerFacet", first: true, predicate: Header, descendants: true }, { propertyName: "footerFacet", first: true, predicate: Footer, descendants: true }, { propertyName: "templates", predicate: PrimeTemplate }], ngImport: i0, template: `
<div [ngClass]="'p-card p-component'" [ngStyle]="style" [class]="styleClass">
<div class="p-card-header" *ngIf="headerFacet || headerTemplate">
<ng-content select="p-header"></ng-content>
<ng-container *ngTemplateOutlet="headerTemplate"></ng-container>
</div>
<div class="p-card-body">
<div class="p-card-title" *ngIf="header || titleTemplate">
{{header}}
<ng-container *ngTemplateOutlet="titleTemplate"></ng-container>
</div>
<div class="p-card-subtitle" *ngIf="subheader || subtitleTemplate">
{{subheader}}
<ng-container *ngTemplateOutlet="subtitleTemplate"></ng-container>
</div>
<div class="p-card-content">
<ng-content></ng-content>
<ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</div>
<div class="p-card-footer" *ngIf="footerFacet || footerTemplate">
<ng-content select="p-footer"></ng-content>
<ng-container *ngTemplateOutlet="footerTemplate"></ng-container>
</div>
</div>
</div>
`, isInline: true, styles: [".p-card-header img{width:100%}"], directives: [{ type: i1.NgClass, selector: "[ngClass]", inputs: ["class", "ngClass"] }, { type: i1.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }, { type: i1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { type: i1.NgTemplateOutlet, selector: "[ngTemplateOutlet]", inputs: ["ngTemplateOutletContext", "ngTemplateOutlet"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: Card, decorators: [{
type: Component,
args: [{
selector: 'p-card',
template: `
<div [ngClass]="'p-card p-component'" [ngStyle]="style" [class]="styleClass">
<div class="p-card-header" *ngIf="headerFacet || headerTemplate">
<ng-content select="p-header"></ng-content>
<ng-container *ngTemplateOutlet="headerTemplate"></ng-container>
</div>
<div class="p-card-body">
<div class="p-card-title" *ngIf="header || titleTemplate">
{{header}}
<ng-container *ngTemplateOutlet="titleTemplate"></ng-container>
</div>
<div class="p-card-subtitle" *ngIf="subheader || subtitleTemplate">
{{subheader}}
<ng-container *ngTemplateOutlet="subtitleTemplate"></ng-container>
</div>
<div class="p-card-content">
<ng-content></ng-content>
<ng-container *ngTemplateOutlet="contentTemplate"></ng-container>
</div>
<div class="p-card-footer" *ngIf="footerFacet || footerTemplate">
<ng-content select="p-footer"></ng-content>
<ng-container *ngTemplateOutlet="footerTemplate"></ng-container>
</div>
</div>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
styleUrls: ['./card.css']
}]
}], ctorParameters: function () { return [{ type: i0.ElementRef }]; }, propDecorators: { header: [{
type: Input
}], subheader: [{
type: Input
}], style: [{
type: Input
}], styleClass: [{
type: Input
}], headerFacet: [{
type: ContentChild,
args: [Header]
}], footerFacet: [{
type: ContentChild,
args: [Footer]
}], templates: [{
type: ContentChildren,
args: [PrimeTemplate]
}] } });
class CardModule {
}
CardModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: CardModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
CardModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: CardModule, declarations: [Card], imports: [CommonModule], exports: [Card, SharedModule] });
CardModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: CardModule, imports: [[CommonModule], SharedModule] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.4", ngImport: i0, type: CardModule, decorators: [{
type: NgModule,
args: [{
imports: [CommonModule],
exports: [Card, SharedModule],
declarations: [Card]
}]
}] });
/**
* Generated bundle index. Do not edit.
*/
export { Card, CardModule };
//# sourceMappingURL=primeng-card.js.map
|
var gulp = require('gulp')
, jscs = require('gulp-jscs')
, jshint = require('gulp-jshint')
, stylish = require('gulp-jscs-stylish');
gulp.task('lint', function() {
gulp.src(['./*.js', './**/*.js', '!./node_modules/**'])
.pipe(jshint())
.pipe(jscs())
.pipe(stylish.combineWithHintResults())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('test', ['lint']);
gulp.task('default', ['test']);
|
var unfunk;
(function (unfunk) {
var jsesc = require('jsesc');
var escapableExp = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
var meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"': '\\"',
'\\': '\\\\'
};
var jsonNW = {
json: true,
wrap: false,
quotes: 'double'
};
function escape(str) {
escapableExp.lastIndex = 0;
if (escapableExp.test(str)) {
return str.replace(escapableExp, function (a) {
var c = meta[a];
if (typeof c === 'string') {
return c;
}
return jsesc(a, jsonNW);
});
}
return str;
}
unfunk.escape = escape;
})(unfunk || (unfunk = {}));
var unfunk;
(function (unfunk) {
var util = require('util');
var lineExtractExp = /(.*?)(\n|(\r\n)|\r|$)/g;
var lineBreaks = /\n|(\r\n)|\r/g;
var stringDiff = require('diff');
function repeatStr(str, amount) {
var ret = '';
for (var i = 0; i < amount; i++) {
ret += str;
}
return ret;
}
var StringDiffer = (function () {
function StringDiffer(diff) {
this.diff = diff;
}
StringDiffer.prototype.getWrappingLines = function (actual, expected, maxWidth, rowPadLength, padFirst, leadSymbols) {
if (typeof leadSymbols === "undefined") { leadSymbols = false; }
var changes = stringDiff.diffChars(expected, actual);
var escape = unfunk.escape;
var style = this.diff.style;
var sep = '\n';
if (changes.length === 0) {
return [
padFirst[0],
padFirst[1] + style.warning('<no diff data>'),
padFirst[1]
].join(sep);
}
var isSimple = (unfunk.identAnyExp.test(actual) && unfunk.identAnyExp.test(expected));
var delim = (isSimple ? '' : '"');
var delimEmpty = repeatStr(' ', delim.length);
var top = padFirst[0];
var middle = padFirst[1];
var bottom = padFirst[2];
var buffer = '';
if (leadSymbols) {
top += style.error(this.diff.markRemov);
middle += style.plain(this.diff.markEmpty);
bottom += style.success(this.diff.markAdded);
rowPadLength += this.diff.markAdded.length;
}
var dataLength = maxWidth - rowPadLength;
if (rowPadLength + delim.length * 2 >= maxWidth) {
return '<no space for padded diff: "' + (rowPadLength + ' >= ' + maxWidth) + '">';
}
var rowPad = repeatStr(' ', rowPadLength);
var blocks = [];
var charSame = '|';
var charAdded = '+';
var charMissing = '-';
var charCounter = 0;
function delimLine() {
top += delimEmpty;
middle += delim;
bottom += delimEmpty;
}
delimLine();
function flushLine() {
flushStyle();
delimLine();
blocks.push(top + sep + middle + sep + bottom);
top = rowPad;
middle = rowPad;
bottom = rowPad;
charCounter = 0;
delimLine();
}
function appendAdd(value) {
for (var i = 0; i < value.length; i++) {
top += ' ';
buffer += charAdded;
}
bottom += value;
}
function flushAdd() {
if (buffer.length > 0) {
middle += style.success(buffer);
buffer = '';
}
}
function appendRem(value) {
top += value;
for (var i = 0; i < value.length; i++) {
buffer += charMissing;
bottom += ' ';
}
}
function flushRem() {
if (buffer.length > 0) {
middle += style.error(buffer);
buffer = '';
}
}
function appendSame(value) {
top += value;
for (var i = 0; i < value.length; i++) {
buffer += charSame;
}
bottom += value;
}
function flushSame() {
if (buffer.length > 0) {
middle += style.warning(buffer);
buffer = '';
}
}
function appendPlain(value) {
top += value;
for (var i = 0; i < value.length; i++) {
buffer += ' ';
}
bottom += value;
}
function flushPlainStyle() {
middle += buffer;
buffer = '';
}
var appendStyle = appendPlain;
var flushStyle = flushPlainStyle;
var printLine = (isSimple ? function (line, end) {
appendStyle(line);
charCounter += line.length;
if (end) {
flushLine();
}
} : function (line, end) {
for (var j = 0, jj = line.length; j < jj; j++) {
var value = escape(line[j]);
if (charCounter + value.length > dataLength) {
flushLine();
}
appendStyle(value);
charCounter += value.length;
}
if (end) {
flushLine();
}
});
for (var i = 0, ii = changes.length; i < ii; i++) {
var change = changes[i];
flushStyle();
if (change.added) {
appendStyle = appendAdd;
flushStyle = flushAdd;
} else if (change.removed) {
appendStyle = appendRem;
flushStyle = flushRem;
} else {
appendStyle = appendSame;
flushStyle = flushSame;
}
if (change.value.length === 0) {
printLine('', true);
continue;
}
var start = 0;
var match;
lineBreaks.lastIndex = 0;
while ((match = lineBreaks.exec(change.value))) {
var line = change.value.substring(start, match.index);
start = match.index + match[0].length;
lineBreaks.lastIndex = start;
printLine(line + match[0], true);
}
if (start < change.value.length) {
printLine(change.value.substr(start), false);
}
}
if (charCounter > 0) {
flushLine();
}
if (blocks.length === 0) {
return [
padFirst[0],
padFirst[1] + style.warning('<no diff content rendered>'),
padFirst[1]
].join(sep);
}
return blocks.join(sep + sep);
};
return StringDiffer;
})();
unfunk.StringDiffer = StringDiffer;
})(unfunk || (unfunk = {}));
var object;
(function (object) {
var isDate = function (obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
};
var padZero = function (str, len) {
str = '' + str;
while (str.length < len) {
str = '0' + str;
}
return str;
};
var padZero2 = function (str) {
str = '' + str;
if (str.length === 1) {
return '0' + str;
}
return str;
};
var getDateObj = function (date) {
return {
__date: padZero(date.getFullYear(), 4) + '/' + padZero2(date.getMonth()) + '/' + padZero2(date.getDate()),
__time: padZero2(date.getHours()) + ':' + padZero2(date.getMinutes()) + ' ' + padZero2(date.getSeconds()) + ':' + padZero(date.getMilliseconds(), 3)
};
};
function diff(a, b) {
if (a === b) {
return {
changed: 'equal',
value: a
};
}
if (!a) {
return {
changed: 'removed',
value: b
};
}
if (!b) {
return {
changed: 'added',
value: a
};
}
var value = {};
var equal = true;
for (var key in a) {
var valueA = a[key];
var typeA = typeof valueA;
if (typeA === 'object' && isDate(valueA)) {
valueA = getDateObj(valueA);
}
if (key in b) {
var valueB = b[key];
var typeB = typeof valueB;
if (typeB === 'object' && isDate(valueB)) {
valueB = getDateObj(valueB);
}
if (valueA === valueB) {
value[key] = {
changed: 'equal',
value: valueA
};
} else {
if (valueA && valueB && (typeA === 'object' || typeA === 'function') && (typeB === 'object' || typeB === 'function')) {
var valueDiff = diff(valueA, valueB);
if (valueDiff.changed === 'equal') {
value[key] = {
changed: 'equal',
value: valueA
};
} else {
equal = false;
value[key] = valueDiff;
}
} else {
equal = false;
value[key] = {
changed: 'primitive change',
removed: valueA,
added: valueB
};
}
}
} else {
equal = false;
value[key] = {
changed: 'added',
value: valueA
};
}
}
for (key in b) {
if (!(key in a)) {
equal = false;
value[key] = {
changed: 'removed',
value: b[key]
};
}
}
if (equal) {
return {
changed: 'equal',
value: a
};
} else {
return {
changed: 'object change',
value: value
};
}
}
object.diff = diff;
;
})(object || (object = {}));
var unfunk;
(function (unfunk) {
function repeatStr(str, amount) {
var ret = '';
for (var i = 0; i < amount; i++) {
ret += str;
}
return ret;
}
var ObjectDiffer = (function () {
function ObjectDiffer(diff) {
this.diff = diff;
this.prefix = '';
this.indents = 0;
}
ObjectDiffer.prototype.addIndent = function (amount) {
this.indents += amount;
return '';
};
ObjectDiffer.prototype.getWrapping = function (actual, expected, prefix) {
if (typeof prefix === "undefined") { prefix = ''; }
this.indents = 0;
this.prefix = prefix;
var changes = object.diff(actual, expected);
return this.getWrappingDiff(changes);
};
ObjectDiffer.prototype.getWrappingDiff = function (changes) {
var properties = [];
var diff = changes.value;
var res;
var indent = this.getIndent();
var prop;
if (changes.changed === 'equal') {
for (prop in diff) {
res = diff[prop];
properties.push(indent + this.getNameEqual(prop) + this.inspect('', res, 'equal'));
}
} else {
for (prop in diff) {
res = diff[prop];
var changed = res.changed;
switch (changed) {
case 'object change':
properties.push(indent + this.getNameChanged(prop) + '\n' + this.addIndent(1) + this.getWrappingDiff(res));
break;
case 'primitive change':
if (typeof res.added === 'string' && typeof res.removed === 'string') {
if (this.diff.inDiffLengthLimit(res.removed) && this.diff.inDiffLengthLimit(res.added)) {
var plain = this.getNameEmpty(prop);
var preLen = plain.length;
var prepend = [
indent + this.getNameRemoved(prop),
indent + plain,
indent + this.getNameAdded(prop)
];
properties.push(this.diff.getStringDiff(res.removed, res.added, indent.length + preLen, prepend));
} else {
properties.push(this.diff.printDiffLengthLimit(res.removed, res.added, indent));
}
} else {
properties.push(indent + this.getNameRemoved(prop) + this.inspect('', res.added, 'removed') + '\n' + indent + this.getNameAdded(prop) + this.inspect('', res.removed, 'added') + '');
}
break;
case 'removed':
properties.push(indent + this.getNameRemoved(prop) + this.inspect('', res.value, 'removed'));
break;
case 'added':
properties.push(indent + this.getNameAdded(prop) + this.inspect('', res.value, 'added'));
break;
case 'equal':
default:
properties.push(indent + this.getNameEqual(prop) + this.inspect('', res.value, 'equal'));
break;
}
}
}
return properties.join('\n') + this.addIndent(-1) + this.getIndent() + this.diff.markSpace;
};
ObjectDiffer.prototype.getIndent = function (id) {
if (typeof id === "undefined") { id = ''; }
var ret = [];
for (var i = 0; i < this.indents; i++) {
ret.push(this.diff.indentert);
}
return id + this.prefix + ret.join('');
};
ObjectDiffer.prototype.encodeName = function (prop) {
if (!unfunk.identAnyExp.test(prop)) {
return '"' + unfunk.escape(prop) + '"';
}
return prop;
};
ObjectDiffer.prototype.encodeString = function (prop) {
return '"' + unfunk.escape(prop) + '"';
};
ObjectDiffer.prototype.getNameAdded = function (prop) {
return this.diff.style.success(this.diff.markAdded + this.encodeName(prop)) + ': ';
};
ObjectDiffer.prototype.getNameRemoved = function (prop) {
return this.diff.style.error(this.diff.markRemov + this.encodeName(prop)) + ': ';
};
ObjectDiffer.prototype.getNameChanged = function (prop) {
return this.diff.style.warning(this.diff.markChang + this.encodeName(prop)) + ': ';
};
ObjectDiffer.prototype.getNameEmpty = function (prop) {
return this.diff.markColum + repeatStr(' ', this.encodeName(prop).length) + ': ';
};
ObjectDiffer.prototype.getNameEqual = function (prop) {
return this.diff.markEqual + this.encodeName(prop) + ': ';
};
ObjectDiffer.prototype.getName = function (prop, change) {
switch (change) {
case 'added':
return this.getNameAdded(prop);
case 'removed':
return this.getNameRemoved(prop);
case 'object change':
return this.getNameChanged(prop);
case 'empty':
return this.getNameEmpty(prop);
case 'plain':
default:
return this.diff.markEqual + this.encodeName(prop) + ': ';
}
};
ObjectDiffer.prototype.inspect = function (accumulator, obj, change) {
var i;
switch (typeof obj) {
case 'object':
if (!obj) {
accumulator += 'null';
break;
}
var length;
if (Array.isArray(obj)) {
length = obj.length;
if (length === 0) {
accumulator += '[]';
} else {
accumulator += '\n';
for (i = 0; i < length; i++) {
this.addIndent(1);
accumulator = this.inspect(accumulator + this.getIndent() + this.getName(String(i), change), obj[i], change);
if (i < length - 1) {
accumulator += '\n';
}
this.addIndent(-1);
}
}
} else {
var props = Object.keys(obj).sort();
length = props.length;
if (length === 0) {
accumulator += '{}';
} else {
accumulator += '\n';
for (i = 0; i < length; i++) {
var prop = props[i];
this.addIndent(1);
accumulator = this.inspect(accumulator + this.getIndent() + this.getName(prop, change), obj[prop], change);
if (i < length - 1) {
accumulator += '\n';
}
this.addIndent(-1);
}
}
}
break;
case 'function':
accumulator += 'function()';
break;
case 'undefined':
accumulator += 'undefined';
break;
case 'string':
accumulator += this.encodeName(obj);
break;
case 'number':
accumulator += String(obj);
break;
default:
accumulator += this.encodeString(String(obj));
break;
}
return accumulator;
};
return ObjectDiffer;
})();
unfunk.ObjectDiffer = ObjectDiffer;
})(unfunk || (unfunk = {}));
var unfunk;
(function (unfunk) {
unfunk.objectNameExp = /(^\[object )|(\]$)/gi;
unfunk.identExp = /^[a-z](?:[a-z0-9_\-]*?[a-z0-9])?$/i;
unfunk.identAnyExp = /^[a-z0-9](?:[a-z0-9_\-]*?[a-z0-9])?$/i;
var DiffFormatter = (function () {
function DiffFormatter(style, maxWidth) {
if (typeof maxWidth === "undefined") { maxWidth = 80; }
this.style = style;
this.maxWidth = maxWidth;
this.indentert = ' ';
this.markAdded = '+ ';
this.markRemov = '- ';
this.markChang = '? ';
this.markEqual = '. ';
this.markEmpty = ' ';
this.markColum = '| ';
this.markSpace = '';
this.stringMaxLength = 5000;
this.bufferMaxLength = 100;
this.arrayMaxLength = 100;
if (maxWidth === 0) {
this.maxWidth = 100;
}
}
DiffFormatter.prototype.forcedDiff = function (actual, expected) {
if (typeof actual === 'string' && typeof expected === 'string') {
return true;
} else if (typeof actual === 'object' && typeof expected === 'object') {
return true;
}
return false;
};
DiffFormatter.prototype.inDiffLengthLimit = function (obj, limit) {
if (typeof limit === "undefined") { limit = 0; }
switch (typeof obj) {
case 'string':
return (obj.length < (limit ? limit : this.stringMaxLength));
case 'object':
switch (this.getObjectType(obj)) {
case 'array':
case 'arguments':
return (obj.length < (limit ? limit : this.arrayMaxLength));
case 'buffer':
return (obj.length < (limit ? limit : this.bufferMaxLength));
case 'object':
return (obj && (Object.keys(obj).length < (limit ? limit : this.arrayMaxLength)));
}
default:
return false;
}
};
DiffFormatter.prototype.printDiffLengthLimit = function (actual, expected, prepend, limit) {
if (typeof prepend === "undefined") { prepend = ''; }
if (typeof limit === "undefined") { limit = 0; }
var len = [];
if (actual && !this.inDiffLengthLimit(actual, limit)) {
len.push(prepend + this.style.warning('<actual too lengthy for diff: ' + actual.length + '>'));
}
if (expected && !this.inDiffLengthLimit(expected, limit)) {
len.push(prepend + this.style.warning('<expected too lengthy for diff: ' + expected.length + '>'));
}
if (len.length > 0) {
return len.join('\n');
}
return '';
};
DiffFormatter.prototype.getObjectType = function (obj) {
return Object.prototype.toString.call(obj).replace(unfunk.objectNameExp, '').toLowerCase();
};
DiffFormatter.prototype.validType = function (value) {
var type = typeof value;
if (type === 'string') {
return true;
}
if (type === 'object') {
return !!value;
}
return false;
};
DiffFormatter.prototype.getStyledDiff = function (actual, expected, prepend) {
if (typeof prepend === "undefined") { prepend = ''; }
if ((this.getObjectType(actual) !== this.getObjectType(expected) || !this.validType(actual) || !this.validType(expected))) {
return '';
}
if (!this.inDiffLengthLimit(actual) || !this.inDiffLengthLimit(expected)) {
return this.printDiffLengthLimit(actual, expected, prepend);
}
if (typeof actual === 'object' && typeof expected === 'object') {
return this.getObjectDiff(actual, expected, prepend);
} else if (typeof actual === 'string' && typeof expected === 'string') {
return this.getStringDiff(actual, expected, prepend.length, [prepend, prepend, prepend], true);
}
return '';
};
DiffFormatter.prototype.getObjectDiff = function (actual, expected, prepend, diffLimit) {
if (typeof diffLimit === "undefined") { diffLimit = 0; }
return new unfunk.ObjectDiffer(this).getWrapping(actual, expected, prepend);
};
DiffFormatter.prototype.getStringDiff = function (actual, expected, padLength, padFirst, leadSymbols) {
if (typeof leadSymbols === "undefined") { leadSymbols = false; }
return new unfunk.StringDiffer(this).getWrappingLines(actual, expected, this.maxWidth, padLength, padFirst, leadSymbols);
};
return DiffFormatter;
})();
unfunk.DiffFormatter = DiffFormatter;
})(unfunk || (unfunk = {}));
var unfunk;
(function (unfunk) {
var ministyle = require('ministyle');
function ansi(valueA, valueB, maxWidth) {
if (typeof maxWidth === "undefined") { maxWidth = 80; }
var formatter = new unfunk.DiffFormatter(ministyle.ansi(), maxWidth);
return formatter.getStyledDiff(valueA, valueB);
}
unfunk.ansi = ansi;
function plain(valueA, valueB, maxWidth) {
if (typeof maxWidth === "undefined") { maxWidth = 80; }
var formatter = new unfunk.DiffFormatter(ministyle.plain(), maxWidth);
return formatter.getStyledDiff(valueA, valueB);
}
unfunk.plain = plain;
})(unfunk || (unfunk = {}));
(module).exports = unfunk;
//# sourceMappingURL=index.js.map
|
var Package = require('dgeni').Package;
var jsdocPackage = require('dgeni-packages/jsdoc');
var nunjucksPackage = require('dgeni-packages/nunjucks');
var typescriptPackage = require('dgeni-packages/typescript');
var linksPackage = require('../links-package');
var gitPackage = require('dgeni-packages/git');
var path = require('canonical-path');
// Define the dgeni package for generating the docs
module.exports = new Package('angular-v2-docs', [jsdocPackage, nunjucksPackage, typescriptPackage, linksPackage, gitPackage])
// Register the processors
.processor(require('./processors/convertPrivateClassesToInterfaces'))
.processor(require('./processors/generateNavigationDoc'))
.processor(require('./processors/extractTitleFromGuides'))
.processor(require('./processors/createOverviewDump'))
.processor(require('./processors/checkUnbalancedBackTicks'))
.processor(require('./processors/convertBackticksToCodeBlocks'))
.processor(require('./processors/addNotYetDocumentedProperty'))
.processor(require('./processors/mergeDecoratorDocs'))
.processor(require('./processors/extractDecoratedClasses'))
.config(function(parseTagsProcessor) {
parseTagsProcessor.tagDefinitions.push({ name: 'internal', transforms: function() { return true; } });
parseTagsProcessor.tagDefinitions.push({ name: 'syntax' });
parseTagsProcessor.tagDefinitions.push({ name: 'noDescription', transforms: function() { return true; } });
})
.config(function(renderDocsProcessor, versionInfo) {
renderDocsProcessor.extraData.versionInfo = versionInfo;
})
.config(function(parseTagsProcessor, getInjectables) {
// We actually don't want to parse param docs in this package as we are getting the data out using TS
// TODO: rewire the param docs to the params extracted from TS
parseTagsProcessor.tagDefinitions.forEach(function(tagDef) {
if (tagDef.name === 'param') {
tagDef.docProperty = 'paramData';
tagDef.transforms = [];
}
});
})
// Configure links
.config(function(getLinkInfo) {
getLinkInfo.useFirstAmbiguousLink = true;
})
// Configure file writing
.config(function(writeFilesProcessor) {
writeFilesProcessor.outputFolder = 'dist/docs';
})
// Configure rendering
.config(function(templateFinder, templateEngine) {
// Nunjucks and Angular conflict in their template bindings so change Nunjucks
templateEngine.config.tags = {
variableStart: '{$',
variableEnd: '$}'
};
templateFinder.templatePatterns = [
'${ doc.template }',
'${ doc.id }.${ doc.docType }.template.html',
'${ doc.id }.template.html',
'${ doc.docType }.template.html',
'common.template.html'
];
}); |
module.exports = require('./build/webpack/graphql');
|
<div id="wrapper">
<div data-tabname="one">Tab one</div>
<div data-tabname="two">Tab two</div>
<div data-tabname="three">Tab three</div>
</div>
<script>
function asTabs(node) {
//1.Gathering all decent children (no whitespaces etc) and not displaying them
function decentChildren(node) {
var arr = [];
for (var i = 0; i < node.childNodes.length; i++) {
if (node.childNodes[i].nodeType === 1) {
arr = arr.concat(node.childNodes[i]);
}
}
return arr;
}
var children = decentChildren(node);
function hideEm(nodes) {
nodes.forEach(function(node) {
node.style.display = "none";
});
}
hideEm(children);
//2.Act (what to do, after button is clicked)
function act(event) {
children.forEach(function(child) {
if (event.target.getAttribute("data-num") == children.indexOf(child)) {
child.style.display = "block";
} else {
child.style.display = "none";
}
});
}
//3. Creating buttons
function buttons(tags){
var arr = [];
for (var i = 0; i < tags.length; i++) {
arr[i] = document.createElement("BUTTON");
arr[i].textContent = tags[i].getAttribute("data-tabname");
arr[i].setAttribute("data-num", i);
arr[i].addEventListener("click", act);
}
return arr;
}
function appendFirstChildren(arr, node) {
var firstChild = node.firstChild;
arr.forEach(function(child) {
node.insertBefore(child, firstChild);
});
}
appendFirstChildren(buttons(children), node);
}
asTabs(document.querySelector("#wrapper"));
</script> |
// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from 'utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// Create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars
return [
{
path: '/',
name: 'home',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/HomePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([component]) => {
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/createpost',
name: 'post',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/Post/reducer'),
System.import('containers/Post/sagas'),
System.import('containers/Post'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('post', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/singlepost',
name: 'singlePost',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/SinglePost/reducer'),
System.import('containers/SinglePost/sagas'),
System.import('containers/SinglePost'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('singlePost', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/dashboard',
name: 'dashboard',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/Dashboard/reducer'),
System.import('containers/Dashboard/sagas'),
System.import('containers/Dashboard'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('dashboard', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/learningtocode',
name: 'learningToCode',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/LearningToCode/reducer'),
System.import('containers/LearningToCode/sagas'),
System.import('containers/LearningToCode'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('learningToCode', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/wanttolearn',
name: 'wantToLearn',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/WantToLearn/reducer'),
System.import('containers/WantToLearn/sagas'),
System.import('containers/WantToLearn'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('wantToLearn', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/onthejob',
name: 'onTheJob',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/OnTheJob/reducer'),
System.import('containers/OnTheJob/sagas'),
System.import('containers/OnTheJob'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('onTheJob', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/jobhunt',
name: 'jobHunt',
getComponent(nextState, cb) {
const importModules = Promise.all([
System.import('containers/JobHunt/reducer'),
System.import('containers/JobHunt/sagas'),
System.import('containers/JobHunt'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('jobHunt', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
System.import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
|
/**
* @file
* This file is used by "npm test" to selftest the succss package.
* Selftests are made from http://succss.ifzenelse.net documentation website.
*
* @see selftests/run.sh, selftests/test.sh
*
*/
var baseUrl = 'succss.ifzenelse.net';
Succss.pages = {
'home': {
url:'succss.ifzenelse.net',
directory:'screenshots/dir',
captures: {
'header':'',
// Key:name Value:CSS selector.
'dynamic-text':'body #header-text > #static-line + span',
},
},
'special': {
url:'http://succss.ifzenelse.net/commandline?bgColor=A7A',
captures: {
'body': {
// Selectors can have a hook callback "before" capture.
before: function() {
this.click('#logo-image');
console.log('... Waiting for color squares randomization');
this.wait(1000, function() {
console.log('Done!');
});
}
},
},
},
// Will output: './screenshots/home--body--default-viewport.png'
'concise': { url:'succss.ifzenelse.net/home?bgColor=088&variation=0', 'good':true },
'installation': {
'url': baseUrl + '/installation&variation=0',
'directory':'./screenshots/installation',
captures: {
'header':''
},
},
'configuration': {
'url': baseUrl + '/configuration?bgColor=A7A&variation=0',
'directory':'./screenshots/configuration/',
'source': 'installation',
},
'capture-prop': {
'url':baseUrl + '/fork&variation=0',
'captures': { 'header-text':'#static-line' },
'good':true
},
'custom-resemble': {
'url':baseUrl + '?variation=100&speed=70',
'captures': { 'aside-colors':'aside#colors' },
}
};
Succss.callback = function(capture) {
// The other available action is 'add'
if (capture.action == 'check') {
if (!capture.options.good && !capture.page.good) {
casper.test.assertTruthy(fs.exists(capture.filePath), 'The updated capture was taken (' + capture.filePath + ').');
casper.test.assertNotEquals(fs.size(capture.filePath), fs.size(capture.basePath), 'Base and update are different in size.');
}
}
}
Succss.viewports = {
'classic-wide': {
width: 1366,
height: 768
},
}
Succss.options = {
imagediff:false,
resemble:false,
diff:true,
exitOnError:false
}
Succss.diff = function(imgBase, imgCheck, capture) {
if (capture.page.name == 'custom-resemble') {
try {
this.injectJs(capture.options.libpath + '/resemble.js');
resemble.outputSettings({
errorColor: {
red: 0,
green: 0,
blue: 255
},
errorType: 'movement',
transparency: 0.8,
largeImageThreshold: 1000
});
this.resemble(imgBase, imgCheck, capture);
}
catch(e) {
console.log(e);
}
}
}; |
module.exports = {
mysql: require('./mysql'),
sqlite3: require('./sqlite3'),
}
|
define({url:"/ajax_change_info"}); |
import GLBoost from '../../globals';
import GLBoostObject from '../../low_level/core/GLBoostObject';
export default class Expression extends GLBoostObject {
constructor(glBoostContext) {
super(glBoostContext);
this._renderPasses = [];
}
addRenderPasses(renderPasses) {
renderPasses.forEach((renderPass)=>{
renderPass._expression = this;
});
this._renderPasses = this._renderPasses.concat(renderPasses);
}
addRenderPass(renderPass) {
renderPath._expression = this;
this._renderPasses.push(renderPass);
}
clearRenderPasses() {
this._renderPasses.forEach((renderPass)=>{
renderPass._expression = null;
});
this._renderPasses.length = 0;
}
get renderPasses() {
return this._renderPasses;
}
setCurrentAnimationValue(inputName, inputValue) {
for (let renderPass of this.renderPasses) {
if (renderPass.scene) {
renderPass.scene.setCurrentAnimationValue(inputName, inputValue);
}
}
}
prepareToRender() {
this._renderPasses.forEach((renderPass, index)=>{
renderPass.prepareToRender(this);
});
}
}
GLBoost['Expression'] = Expression;
|
$(document).on('click', '.contact-click', function () {
var name = $("input#name-contact").val();
var surname = $("input#surname-contact").val();
var email = $("input#email-contact").val();
var message = $("textarea#message-contact").val();
var phone = $("input#phone-contact").val();
var htmlBody = '<h2>'+ name + ' ' + surname +' ha contactado con nosotros</h2>'+
'<h4><strong>Esta es su pregunta: </strong> </h4>'+
'<p>' + message + '</p>'+
'<h4><strong>Si desea contacta con él estos son sus datos: </strong></h4>' +
'<p><strong>Email: </strong>' + email + '</p>'+
'<p><strong>Teléfono: </strong>' + phone + '</p>';
var jsonFile = {
'name': name,
'surname': surname,
'mail': email,
'message': htmlBody,
'phone': phone
};
if(name && surname && email && message && phone && htmlBody){
$.ajax({
type: "POST",
url: "controllers/contactus.php",
data: {
Contact: jsonFile
},
dataType: "json"
}).done(function (data) {
if (data.response == 'ok') {
$('#contactModal').modal('show');
$('#contactModal').on('hidden.bs.modal', function () {
document.location = "home";
});
}
else{
alert("Uppss! Ha habido un error durante el envío: Por favor intentelo de nuevo más tarde");
document.location = "contactus";
}
});
}
else{
alert('Todos los campos del formulario son obligatorios, rellenelos para continuar');
}
}); |
/**
* angular-ui-utils - Swiss-Army-Knife of AngularJS tools (with no external dependencies!)
* @version v0.2.2 - 2015-03-12
* @link http://angular-ui.github.com
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
// READ: http://docs-next.angularjs.org/guide/ie
// element tags are statically defined in order to accommodate lazy-loading whereby directives are also unknown
// The ieshiv takes care of our ui.directives and AngularJS's ng-view, ng-include, ng-pluralize, ng-switch.
// However, IF you have custom directives that can be used as html tags (yours or someone else's) then
// add list of directives into <code>window.myCustomTags</code>
// <!--[if lte IE 8]>
// <script>
// window.myCustomTags = [ 'yourCustomDirective', 'somebodyElsesDirective' ]; // optional
// </script>
// <script src="build/angular-ui-ieshiv.js"></script>
// <![endif]-->
(function (window, document) {
"use strict";
var tags = [ "ngInclude", "ngPluralize", "ngView", "ngSwitch", "uiCurrency", "uiCodemirror", "uiDate", "uiEvent",
"uiKeypress", "uiKeyup", "uiKeydown", "uiMask", "uiMapInfoWindow", "uiMapMarker", "uiMapPolyline",
"uiMapPolygon", "uiMapRectangle", "uiMapCircle", "uiMapGroundOverlay", "uiModal", "uiReset",
"uiScrollfix", "uiSelect2", "uiShow", "uiHide", "uiToggle", "uiSortable", "uiTinymce"
];
window.myCustomTags = window.myCustomTags || []; // externally defined by developer using angular-ui directives
tags.push.apply(tags, window.myCustomTags);
var toCustomElements = function (str) {
var result = [];
var dashed = str.replace(/([A-Z])/g, function ($1) {
return " " + $1.toLowerCase();
});
var tokens = dashed.split(" ");
// If a token is just a single name (i.e. no namespace) then we juse define the elements the name given
if (tokens.length === 1) {
var name = tokens[0];
result.push(name);
result.push("x-" + name);
result.push("data-" + name);
} else {
var ns = tokens[0];
var dirname = tokens.slice(1).join("-");
// this is finite list and it seemed senseless to create a custom method
result.push(ns + ":" + dirname);
result.push(ns + "-" + dirname);
result.push("x-" + ns + "-" + dirname);
result.push("data-" + ns + "-" + dirname);
}
return result;
};
for (var i = 0, tlen = tags.length; i < tlen; i++) {
var customElements = toCustomElements(tags[i]);
for (var j = 0, clen = customElements.length; j < clen; j++) {
var customElement = customElements[j];
document.createElement(customElement);
}
}
})(window, document);
|
module.exports = {
escape: /template_start%-([\s\S]+?)%template_end/g,
evaluate: /template_start%([\s\S]+?)%template_end/g,
interpolate: /template_start%=([\s\S]+?)%template_end/g
}
|
var value = 'foo';
module.exports = value;
|
/*
* This is the HIU version of the original respond.js with support for min-height and max-height added. It under the same GPL V2 license.
*/
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
minh : thisq.match( /\(min\-height:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxh : thisq.match( /\(max\-height:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmWidth = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminwpx = parseFloat(ret);
return ret;
},
getEmHeight = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;height:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetHeight;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminhpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminwpx,
eminhpx,
//enable/disable styles
applyMedia = function( fromResize ){
var namew = "clientWidth",
nameh = "clientHeight",
docElemPropw = docElem[ namew ],
docElemProph = docElem[ nameh ],
currWidth = doc.compatMode === "CSS1Compat" && docElemPropw || doc.body[ namew ] || docElemPropw,
currHeight = doc.compatMode === "CSS1Compat" && docElemProph || doc.body[ nameh ] || docElemProph,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles )
{
var thisstyle = mediastyles[ i ],
minw = thisstyle.minw,
maxw = thisstyle.maxw,
minwnull = minw === null,
maxwnull = maxw === null,
minh = thisstyle.minh,
maxh = thisstyle.maxh,
minhnull = minh === null,
maxhnull = maxh === null,
em = "em";
if( !!minw )
{
minw = parseFloat( minw ) * ( minw.indexOf( em ) > -1 ? ( eminwpx || getEmWidth() ) : 1 );
}
if( !!maxw )
{
maxw = parseFloat( maxw ) * ( maxw.indexOf( em ) > -1 ? ( eminwpx || getEmWidth() ) : 1 );
}
if( !!minh )
{
minh = parseFloat( minh ) * ( minh.indexOf( em ) > -1 ? ( eminhpx || getEmHeight() ) : 1 );
}
if( !!maxh )
{
maxh = parseFloat( maxh ) * ( maxh.indexOf( em ) > -1 ? ( eminhpx || getEmHeight() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minwnull || !maxwnull || !minhnull || !maxhnull ) && ( minwnull || currWidth >= minw ) && ( maxwnull || currWidth <= maxw ) && ( minhnull || currHeight >= minh ) && ( maxhnull || currHeight <= maxh ) )
{
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
|
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
{
"id": "cordova-plugin-geolocation.Coordinates",
"file": "plugins/cordova-plugin-geolocation/www/Coordinates.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"Coordinates"
]
},
{
"id": "cordova-plugin-geolocation.PositionError",
"file": "plugins/cordova-plugin-geolocation/www/PositionError.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"PositionError"
]
},
{
"id": "cordova-plugin-geolocation.Position",
"file": "plugins/cordova-plugin-geolocation/www/Position.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"Position"
]
},
{
"id": "cordova-plugin-geolocation.geolocation",
"file": "plugins/cordova-plugin-geolocation/www/geolocation.js",
"pluginId": "cordova-plugin-geolocation",
"clobbers": [
"navigator.geolocation"
]
},
{
"id": "cordova-plugin-device.device",
"file": "plugins/cordova-plugin-device/www/device.js",
"pluginId": "cordova-plugin-device",
"clobbers": [
"device"
]
},
{
"id": "de.appplant.cordova.plugin.local-notification.LocalNotification",
"file": "plugins/de.appplant.cordova.plugin.local-notification/www/local-notification.js",
"pluginId": "de.appplant.cordova.plugin.local-notification",
"clobbers": [
"cordova.plugins.notification.local",
"plugin.notification.local"
]
},
{
"id": "de.appplant.cordova.plugin.local-notification.LocalNotification.Core",
"file": "plugins/de.appplant.cordova.plugin.local-notification/www/local-notification-core.js",
"pluginId": "de.appplant.cordova.plugin.local-notification",
"clobbers": [
"cordova.plugins.notification.local.core",
"plugin.notification.local.core"
]
},
{
"id": "de.appplant.cordova.plugin.local-notification.LocalNotification.Util",
"file": "plugins/de.appplant.cordova.plugin.local-notification/www/local-notification-util.js",
"pluginId": "de.appplant.cordova.plugin.local-notification",
"merges": [
"cordova.plugins.notification.local.core",
"plugin.notification.local.core"
]
},
{
"id": "cordova-plugin-badge.Badge",
"file": "plugins/cordova-plugin-badge/www/badge.js",
"pluginId": "cordova-plugin-badge",
"clobbers": [
"cordova.plugins.notification.badge"
]
},
{
"id": "cordova-sms-plugin.Sms",
"file": "plugins/cordova-sms-plugin/www/sms.js",
"pluginId": "cordova-sms-plugin",
"clobbers": [
"window.sms"
]
},
{
"id": "es6-promise-plugin.Promise",
"file": "plugins/es6-promise-plugin/www/promise.js",
"pluginId": "es6-promise-plugin",
"runs": true
},
{
"id": "cordova-plugin-x-socialsharing.SocialSharing",
"file": "plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js",
"pluginId": "cordova-plugin-x-socialsharing",
"clobbers": [
"window.plugins.socialsharing"
]
},
{
"id": "cordova-plugin-file.DirectoryEntry",
"file": "plugins/cordova-plugin-file/www/DirectoryEntry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryEntry"
]
},
{
"id": "cordova-plugin-file.DirectoryReader",
"file": "plugins/cordova-plugin-file/www/DirectoryReader.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.DirectoryReader"
]
},
{
"id": "cordova-plugin-file.Entry",
"file": "plugins/cordova-plugin-file/www/Entry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Entry"
]
},
{
"id": "cordova-plugin-file.File",
"file": "plugins/cordova-plugin-file/www/File.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.File"
]
},
{
"id": "cordova-plugin-file.FileEntry",
"file": "plugins/cordova-plugin-file/www/FileEntry.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileEntry"
]
},
{
"id": "cordova-plugin-file.FileError",
"file": "plugins/cordova-plugin-file/www/FileError.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileError"
]
},
{
"id": "cordova-plugin-file.FileReader",
"file": "plugins/cordova-plugin-file/www/FileReader.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileReader"
]
},
{
"id": "cordova-plugin-file.FileSystem",
"file": "plugins/cordova-plugin-file/www/FileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileSystem"
]
},
{
"id": "cordova-plugin-file.FileUploadOptions",
"file": "plugins/cordova-plugin-file/www/FileUploadOptions.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadOptions"
]
},
{
"id": "cordova-plugin-file.FileUploadResult",
"file": "plugins/cordova-plugin-file/www/FileUploadResult.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileUploadResult"
]
},
{
"id": "cordova-plugin-file.FileWriter",
"file": "plugins/cordova-plugin-file/www/FileWriter.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.FileWriter"
]
},
{
"id": "cordova-plugin-file.Flags",
"file": "plugins/cordova-plugin-file/www/Flags.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Flags"
]
},
{
"id": "cordova-plugin-file.LocalFileSystem",
"file": "plugins/cordova-plugin-file/www/LocalFileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.LocalFileSystem"
],
"merges": [
"window"
]
},
{
"id": "cordova-plugin-file.Metadata",
"file": "plugins/cordova-plugin-file/www/Metadata.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.Metadata"
]
},
{
"id": "cordova-plugin-file.ProgressEvent",
"file": "plugins/cordova-plugin-file/www/ProgressEvent.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.ProgressEvent"
]
},
{
"id": "cordova-plugin-file.fileSystems",
"file": "plugins/cordova-plugin-file/www/fileSystems.js",
"pluginId": "cordova-plugin-file"
},
{
"id": "cordova-plugin-file.requestFileSystem",
"file": "plugins/cordova-plugin-file/www/requestFileSystem.js",
"pluginId": "cordova-plugin-file",
"clobbers": [
"window.requestFileSystem"
]
},
{
"id": "cordova-plugin-file.resolveLocalFileSystemURI",
"file": "plugins/cordova-plugin-file/www/resolveLocalFileSystemURI.js",
"pluginId": "cordova-plugin-file",
"merges": [
"window"
]
},
{
"id": "cordova-plugin-file.isChrome",
"file": "plugins/cordova-plugin-file/www/browser/isChrome.js",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"id": "cordova-plugin-file.iosFileSystem",
"file": "plugins/cordova-plugin-file/www/ios/FileSystem.js",
"pluginId": "cordova-plugin-file",
"merges": [
"FileSystem"
]
},
{
"id": "cordova-plugin-file.fileSystems-roots",
"file": "plugins/cordova-plugin-file/www/fileSystems-roots.js",
"pluginId": "cordova-plugin-file",
"runs": true
},
{
"id": "cordova-plugin-file.fileSystemPaths",
"file": "plugins/cordova-plugin-file/www/fileSystemPaths.js",
"pluginId": "cordova-plugin-file",
"merges": [
"cordova"
],
"runs": true
},
{
"id": "cordova-plugin-file-transfer.FileTransferError",
"file": "plugins/cordova-plugin-file-transfer/www/FileTransferError.js",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransferError"
]
},
{
"id": "cordova-plugin-file-transfer.FileTransfer",
"file": "plugins/cordova-plugin-file-transfer/www/FileTransfer.js",
"pluginId": "cordova-plugin-file-transfer",
"clobbers": [
"window.FileTransfer"
]
},
{
"id": "cordova-plugin-camera.Camera",
"file": "plugins/cordova-plugin-camera/www/CameraConstants.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"Camera"
]
},
{
"id": "cordova-plugin-camera.CameraPopoverOptions",
"file": "plugins/cordova-plugin-camera/www/CameraPopoverOptions.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"CameraPopoverOptions"
]
},
{
"id": "cordova-plugin-camera.camera",
"file": "plugins/cordova-plugin-camera/www/Camera.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"navigator.camera"
]
},
{
"id": "cordova-plugin-camera.CameraPopoverHandle",
"file": "plugins/cordova-plugin-camera/www/ios/CameraPopoverHandle.js",
"pluginId": "cordova-plugin-camera",
"clobbers": [
"CameraPopoverHandle"
]
},
{
"id": "cordova-plugin-actionsheet.ActionSheet",
"file": "plugins/cordova-plugin-actionsheet/www/ActionSheet.js",
"pluginId": "cordova-plugin-actionsheet",
"clobbers": [
"window.plugins.actionsheet"
]
}
];
module.exports.metadata =
// TOP OF METADATA
{
"cordova-plugin-compat": "1.1.0",
"cordova-plugin-geolocation": "2.4.3",
"cordova-plugin-whitelist": "1.3.2",
"cordova-plugin-device": "1.1.6",
"cordova-plugin-app-event": "1.2.0",
"de.appplant.cordova.plugin.local-notification": "0.8.4",
"cordova-plugin-badge": "0.8.1",
"cordova-sms-plugin": "0.1.11",
"es6-promise-plugin": "4.1.0",
"cordova-plugin-x-socialsharing": "5.1.8",
"cordova-plugin-file": "4.3.3",
"cordova-plugin-file-transfer": "1.6.3",
"cordova-plugin-camera": "2.4.1",
"cordova-plugin-actionsheet": "2.3.3"
};
// BOTTOM OF METADATA
}); |
var currentLicenseStep = $("[data-step=1A]")
var licenseWizard = $('#license-wizard')
var buttons = $('.license-wizard-step button')
$('#show-license-wizard').click(function(event){
event.preventDefault()
if (licenseWizard.hasClass('hidden')) {
licenseWizard.removeClass('hidden')
} else {
close()
}
})
buttons.each(function(){
$(this).click(function(){
var action = $(this).data('action')
var nextStep = $(this).data('next-step')
if (action == 'restart') {
restart()
} else if (action == 'close') {
close()
} else if (nextStep) {
loadStep(nextStep)
}
})
})
function close() {
licenseWizard.addClass('hidden')
loadStep('1A')
}
function restart() {
loadStep('1A')
}
function loadStep(id) {
var nextStep = $("[data-step=" + id + "]")
currentLicenseStep.addClass('hidden')
nextStep.removeClass('hidden')
currentLicenseStep = nextStep
} |
/*
* satellite-js v1.2
* (c) 2013 Shashwat Kandadai and UCSC
* https://github.com/shashwatak/satellite-js
* License: MIT
*/
define([
'./constants',
'./gstime/gstime'
], function(
constants,
gstime
) {
'use strict';
return function (initlParameters) {
/*-----------------------------------------------------------------------------
*
* procedure initl
*
* this procedure initializes the spg4 propagator. all the initialization is
* consolidated here instead of having multiple loops inside other routines.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* ecco - eccentricity 0.0 - 1.0
* epoch - epoch time in days from jan 0, 1950. 0 hr
* inclo - inclination of satellite
* no - mean motion of satellite
* satn - satellite number
*
* outputs :
* ainv - 1.0 / a
* ao - semi major axis
* con41 -
* con42 - 1.0 - 5.0 cos(i)
* cosio - cosine of inclination
* cosio2 - cosio squared
* eccsq - eccentricity squared
* method - flag for deep space 'd', 'n'
* omeosq - 1.0 - ecco * ecco
* posq - semi-parameter squared
* rp - radius of perigee
* rteosq - square root of (1.0 - ecco*ecco)
* sinio - sine of inclination
* gsto - gst at time of observation rad
* no - mean motion of satellite
*
* locals :
* ak -
* d1 -
* del -
* adel -
* po -
*
* coupling :
* getgravconst
* gstime - find greenwich sidereal time from the julian date
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
// TODO: defined but never used
//var satn = initlParameters.satn;
var ecco = initlParameters.ecco,
epoch = initlParameters.epoch,
inclo = initlParameters.inclo,
no = initlParameters.no,
method = initlParameters.method,
opsmode = initlParameters.opsmode;
var ak, d1, adel, po, gsto;
// TODO: defined but never used
// var del;
// sgp4fix use old way of finding gst
// ----------------------- earth constants ----------------------
// sgp4fix identify constants and allow alternate values
// ------------- calculate auxillary epoch quantities ----------
var eccsq = ecco * ecco;
var omeosq = 1.0 - eccsq;
var rteosq = Math.sqrt(omeosq);
var cosio = Math.cos(inclo);
var cosio2 = cosio * cosio;
// ------------------ un-kozai the mean motion -----------------
ak = Math.pow(constants.xke / no, constants.x2o3);
d1 = 0.75 * constants.j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq);
var delPrime = d1 / (ak * ak);
adel = ak * (1.0 - delPrime * delPrime - delPrime *
(1.0 / 3.0 + 134.0 * delPrime * delPrime / 81.0));
delPrime = d1 / (adel * adel);
no = no / (1.0 + delPrime);
var ao = Math.pow(constants.xke / no, constants.x2o3);
var sinio = Math.sin(inclo);
po = ao * omeosq;
var con42 = 1.0 - 5.0 * cosio2;
var con41 = -con42 - cosio2 - cosio2;
var ainv = 1.0 / ao;
var posq = po * po;
var rp = ao * (1.0 - ecco);
method = 'n';
// sgp4fix modern approach to finding sidereal time
if (opsmode === 'a') {
// sgp4fix use old way of finding gst
// count integer number of days from 0 jan 1970
var ts70 = epoch - 7305.0;
var ds70 = Math.floor(ts70 + 1.0e-8);
var tfrac = ts70 - ds70;
// find greenwich location at epoch
var c1 = 1.72027916940703639e-2;
var thgr70 = 1.7321343856509374;
var fk5r = 5.07551419432269442e-15;
var c1p2p = c1 + constants.twoPi;
gsto = ( thgr70 + c1 * ds70 + c1p2p * tfrac + ts70 * ts70 * fk5r) % constants.twoPi;
if (gsto < 0.0) {
gsto = gsto + constants.twoPi;
}
}
else {
gsto = gstime(epoch + 2433281.5);
}
var initlResults = {
no: no,
method: method,
ainv: ainv,
ao: ao,
con41: con41,
con42: con42,
cosio: cosio,
cosio2: cosio2,
eccsq: eccsq,
omeosq: omeosq,
posq: posq,
rp: rp,
rteosq: rteosq,
sinio: sinio,
gsto: gsto
};
return initlResults;
};
}); |
//AngularJS modules define applications
var app = angular.module('myApp',[])
//AngularJS controllers control applications
app.controller('myCtrl',function($scope){
$scope.firstName = "gmr";
$scope.lastName = "90";
}); |
// Regex adapted from https://github.com/ceymard/gulp-ngcompile
module.exports = function processContent(fileContent, materialOnly) {
var NG_MODULE_REGEX = materialOnly ? /\.module\(('material\.[^']*'|"material\.[^"]*")\s*,(?:\s*\[([^\]]+)\])?/g : /\.module\(('[^']*'|"[^"]*")\s*,(?:\s*\[([^\]]+)\])?/g;
var match = NG_MODULE_REGEX.exec(fileContent || '');
var module = match && match[1] && match[1].slice(1, -1); //remove quotes
var depsMatch = match && match[2] && match[2].trim();
var dependencies = [];
if (depsMatch) {
dependencies = depsMatch.split(/\s*,\s*/).map(function(dep) {
dep = dep.slice(1, -1); //remove quotes
return dep;
});
}
return {
module: module || '',
dependencies: dependencies
};
};
|
/* */
'use strict';
var toObject = require("./_to-object"),
toIndex = require("./_to-index"),
toLength = require("./_to-length");
module.exports = [].copyWithin || function copyWithin(target, start) {
var O = toObject(this),
len = toLength(O.length),
to = toIndex(target, len),
from = toIndex(start, len),
end = arguments.length > 2 ? arguments[2] : undefined,
count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to),
inc = 1;
if (from < to && to < from + count) {
inc = -1;
from += count - 1;
to += count - 1;
}
while (count-- > 0) {
if (from in O)
O[to] = O[from];
else
delete O[to];
to += inc;
from += inc;
}
return O;
};
|
angular.module('myApp', [])
.controller('myController', ['$scope', 'FirstService', 'FirstFactory',
function($scope, myFirstService, myFirstFactory) {
$scope.userFromService = myFirstService.getUser();
$scope.createUserWithFactory = function(firstName, lastName) {
var user = myFirstFactory.createUser(firstName, lastName);
return JSON.stringify(user);
};
}])
.service('FirstService', function() {
var user = {
"firstName": "Garry",
"lastName": " Kasparov"
};
this.getUser = function() {
return JSON.stringify(user);
};
})
.factory('FirstFactory', function() {
return {
createUser: function(firstName, lastName) {
return {
"firstName": firstName,
"lastName": lastName
};
}
};
});
|
$(document).ready(function(){
$('.selector_busqueda').on('click', function(){
var valor = $(this).attr('value');
var nombre = $(this).attr('id') + '_input';
if ( $('#' + nombre).val() == '' ) {
$('#' + nombre).val(valor);
$(this).addClass('activo_on');
}else{
$('#' + nombre).val('');
$(this).removeClass('activo_on');
}
});
}); |
"use strict";
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.styles = void 0;
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _utils = require("@material-ui/utils");
var _withStyles = _interopRequireDefault(require("../styles/withStyles"));
var styles = function styles(theme) {
var elevations = {};
theme.shadows.forEach(function (shadow, index) {
elevations["elevation".concat(index)] = {
boxShadow: shadow
};
});
return (0, _extends2.default)({
/* Styles applied to the root element. */
root: {
backgroundColor: theme.palette.background.paper,
color: theme.palette.text.primary,
transition: theme.transitions.create('box-shadow')
},
/* Styles applied to the root element if `square={false}`. */
rounded: {
borderRadius: theme.shape.borderRadius
},
/* Styles applied to the root element if `variant="outlined"`. */
outlined: {
border: "1px solid ".concat(theme.palette.divider)
}
}, elevations);
};
exports.styles = styles;
var Paper = /*#__PURE__*/React.forwardRef(function Paper(props, ref) {
var classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
_props$square = props.square,
square = _props$square === void 0 ? false : _props$square,
_props$elevation = props.elevation,
elevation = _props$elevation === void 0 ? 1 : _props$elevation,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'elevation' : _props$variant,
other = (0, _objectWithoutProperties2.default)(props, ["classes", "className", "component", "square", "elevation", "variant"]);
return /*#__PURE__*/React.createElement(Component, (0, _extends2.default)({
className: (0, _clsx.default)(classes.root, className, variant === 'outlined' ? classes.outlined : classes["elevation".concat(elevation)], !square && classes.rounded),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? Paper.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: _propTypes.default.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: _propTypes.default.object,
/**
* @ignore
*/
className: _propTypes.default.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: _propTypes.default
/* @typescript-to-proptypes-ignore */
.elementType,
/**
* Shadow depth, corresponds to `dp` in the spec.
* It accepts values between 0 and 24 inclusive.
*/
elevation: (0, _utils.chainPropTypes)(_propTypes.default.number, function (props) {
var classes = props.classes,
elevation = props.elevation; // in case `withStyles` fails to inject we don't need this warning
if (classes === undefined) {
return null;
}
if (elevation != null && classes["elevation".concat(elevation)] === undefined) {
return new Error("Material-UI: This elevation `".concat(elevation, "` is not implemented."));
}
return null;
}),
/**
* If `true`, rounded corners are disabled.
*/
square: _propTypes.default.bool,
/**
* The variant to use.
*/
variant: _propTypes.default.oneOf(['elevation', 'outlined'])
} : void 0;
var _default = (0, _withStyles.default)(styles, {
name: 'MuiPaper'
})(Paper);
exports.default = _default; |
App.addChild('DocumentUploader', {
el: '[data-document-uploader]',
events: {
's3_upload_complete': 'updateUploadField'
},
activate: function () {
this.$el.find('[data-s3-uploader]').S3Uploader();
},
updateUploadField: function (e, content) {
var $fileInput = $(e.currentTarget).find('[type="file"]');
$fileInput.prop('disabled', true);
$fileInput.after('<i class="fa fa-paperclip" aria-hidden="true">' + content.filename + '</i>');
$(e.currentTarget).find('[data-document-field]').val(content.url);
},
});
|
'use strict';
const assert = require('assert');
const {User} = require('../users-utils');
describe('Rooms features', function () {
describe('Rooms', function () {
describe('Rooms.get', function () {
it('should be a function', function () {
assert.strictEqual(typeof Rooms.get, 'function');
});
});
describe('Rooms.rooms', function () {
it('should be a Map', function () {
assert.ok(Rooms.rooms instanceof Map);
});
});
});
describe('GameRoom', function () {
const packedTeam = 'Weavile||lifeorb||swordsdance,knockoff,iceshard,iciclecrash|Jolly|,252,,,4,252|||||';
let room;
let parent;
afterEach(function () {
for (const user of Users.users.values()) {
user.disconnectAll();
user.destroy();
}
if (room) room.destroy();
if (parent) parent.destroy();
});
it('should allow two users to join the battle', function () {
let p1 = new User();
let p2 = new User();
let options = [{rated: false, tour: false}, {rated: false, tour: {onBattleWin() {}}}, {rated: true, tour: false}, {rated: true, tour: {onBattleWin() {}}}];
for (let option of options) {
room = Rooms.createBattle('customgame', Object.assign({
p1,
p2,
p1team: packedTeam,
p2team: packedTeam,
}, option));
assert.ok(room.battle.p1 && room.battle.p2); // Automatically joined
}
});
it('should copy auth from tournament', function () {
parent = Rooms.createChatRoom('parentroom', '', {});
parent.getAuth = () => '%';
const p1 = new User();
const p2 = new User();
const options = {
p1,
p2,
p1team: packedTeam,
p2team: packedTeam,
rated: false,
auth: {},
tour: {
onBattleWin() {},
room: parent,
},
};
room = Rooms.createBattle('customgame', options);
assert.strictEqual(room.getAuth(new User()), '%');
});
it('should prevent overriding tournament room auth by a tournament player', function () {
parent = Rooms.createChatRoom('parentroom2', '', {});
parent.getAuth = () => '%';
const p1 = new User();
const p2 = new User();
const roomStaff = new User();
roomStaff.forceRename("Room auth", true);
const administrator = new User();
administrator.forceRename("Admin", true);
administrator.group = '~';
const options = {
p1,
p2,
p1team: packedTeam,
p2team: packedTeam,
rated: false,
auth: {},
tour: {
onBattleWin() {},
room: parent,
},
};
room = Rooms.createBattle('customgame', options);
roomStaff.joinRoom(room);
administrator.joinRoom(room);
assert.strictEqual(room.getAuth(roomStaff), '%', 'before promotion attempt');
Chat.parse("/roomvoice Room auth", room, p1, p1.connections[0]);
assert.strictEqual(room.getAuth(roomStaff), '%', 'after promotion attempt');
Chat.parse("/roomvoice Room auth", room, administrator, administrator.connections[0]);
assert.strictEqual(room.getAuth(roomStaff), '+', 'after being promoted by an administrator');
});
});
});
|
const controllers = require('../controllers');
const multer = require('multer');
const auth = require('./auth');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './content/images/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '_' + Date.now() + '.' + file.originalname.split('.')[1])
}
})
let upload = multer({
storage: storage
});
module.exports = (app) => {
app
.get('/', controllers.home.index)
.get('/product/add', auth.isAuthenticated, controllers.product.get.addGet)
.post('/product/add', auth.isAuthenticated, upload.single('image'), controllers.product.post.addPost)
.get('/category/add', auth.isInRole('Admin'), controllers.category.get.addGet)
.post('/category/add', auth.isInRole('Admin'), controllers.category.post.addPost)
.get('/category/:category/products', controllers.category.get.productByCategory)
.get('/product/edit/:id', auth.isAuthenticated, controllers.product.get.editGet)
.post('/product/edit/:id', auth.isAuthenticated, upload.single('image'), controllers.product.post.editPost)
.get('/product/delete/:id', auth.isAuthenticated, controllers.product.get.deleteGet)
.post('/product/delete/:id', auth.isAuthenticated, controllers.product.post.deletePost)
.get('/product/buy/:id', auth.isAuthenticated, controllers.product.get.buyGet)
.post('/product/buy/:id', auth.isAuthenticated, controllers.product.post.buyPost)
.get('/user/register', controllers.user.get.registerGet)
.post('/user/register', controllers.user.post.registerPost)
.get('/user/login', controllers.login.get.loginGet)
.post('/user/login', controllers.login.post.loginPost)
.post('/user/logout', controllers.logout.logout);
} |
ION.SimpleTree = new Class({
Implements: [Events, Options],
options:
{
'key': 'id',
'label': null,
'data' : [] // field of each item to add as data-x attribute
},
/**
*
* @param container
* @param items JSON object
* @param options object
*
*/
initialize:function(container, items, options)
{
this.container = $(container);
this.setOptions(options);
this.items = items;
this.tree = this.buildTree(this.items, 0, 0);
this.container.adopt(this.tree);
},
buildTree:function(items, id_parent, level)
{
var key = this.options.key;
var label = this.options.label; // item key used as label
// var mlClass = 'ml' + (parseInt(level) * 20);
var mlClass = 'ml16';
var ul = new Element('ul', {'class':'tree', 'data-id':id_parent});
var self = this;
Array.each(items, function(item)
{
var element = new Element('li',{'class':'f-open','data-id':item[key]});
// Left margin regarding parent
if (level > 0)
element.addClass(mlClass);
// Title
if (this.options.label)
new Element('a', {'class':'title', text:item[label]}).inject(item);
// Add data-x attributes
Array.each(this.options.data, function(dataKey){
element.setAttribute('data-'+dataKey.as, item[dataKey.key]);
});
ul.adopt(element);
if (item.children)
element.adopt(this.buildTree(item.children, item[key], level + 1));
// plus / minus icon
var pm = new Element('div', {'class': 'tree-img plus'})
.addEvent('click', self.openclose.bind(self))
.inject(element, 'top');
self.close(element);
}.bind(this));
return ul;
},
openclose: function(e)
{
if (typeOf(e.stop) == 'function') e.stop();
var el = e.target;
var li = el.getParent('li');
// Is the folder Open ? Yes ? Close it (Hide the content)
if (li.hasClass('f-open'))
{
this.close(li);
}
else
{
this.open(li);
}
},
open: function(element)
{
if ( ! element.hasClass('f-open'))
{
// All childrens UL
var elementContents = element.getChildren('ul');
var pmIcon = element.getFirst('div.tree-img.plus');
if (typeOf(pmIcon) != 'null')
pmIcon.addClass('minus').removeClass('plus');
elementContents.each(function(ul){ ul.setStyle('display', 'block'); });
element.addClass('f-open');
}
},
close: function(element)
{
if (element.hasClass('f-open'))
{
// All childrens UL
var elementContents = element.getChildren('ul');
var pmIcon = element.getFirst('div.tree-img.minus');
if (pmIcon)
pmIcon.addClass('plus').removeClass('minus');
elementContents.each(function(ul){ ul.setStyle('display', 'none');});
element.removeClass('f-open');
}
}
});
ION.PermissionTree = new Class({
Extends: ION.SimpleTree,
options:
{
cb_name: 'rules[]',
onCheck: null
},
initialize:function(container, items, options)
{
// console.log(options);
this.parent(container, items, options);
this.rules = this.get_rules_array();
if (typeOf(options.onCheck) != 'null')
this.options.onCheck = options.onCheck;
this.enhanceTree();
},
enhanceTree:function()
{
var lis = this.tree.getElements('li');
lis.each(function(li)
{
this.create_resource_li(li);
var actions = li.getAttribute('data-actions');
if (actions != '')
this.create_actions_li(li, actions);
}.bind(this));
// Replace +/- by space if no children
lis = this.tree.getElements('li');
lis.each(function(li)
{
if (li.getChildren('ul').length == 0)
{
var pm = li.getElement('div.plus');
if (pm)
{
new Element('div', {'class':'tree-img line node'}).inject(pm, 'before');
pm.destroy();
}
}
// Get LI children to add "partial rights" if some aren't checked
var cb = li.getElement('input[type=checkbox]');
if (cb.getProperty('checked') == true)
{
var cbs = li.getElements('input[type=checkbox]');
var partial = false;
cbs.each(function(cb)
{
if (partial == false)
{
if (cb.getProperty('checked') != true)
{
var a = li.getElement('label a');
new Element('span', {'class':'lite'}).set('text', ' (' + Lang.get('ionize_label_partial_permission') + ')').inject(a, 'bottom');
partial = true;
}
}
});
}
});
},
create_resource_li:function(container)
{
var id = container.getAttribute('data-id');
var a = new Element('a', {'text': container.getAttribute('data-title'), 'title':'action:access, resource:' + container.getAttribute('data-resource')});
var label = new Element('label', {
'for': this.options.cb_name + id
}).adopt(a).inject(container, 'top');
// Because label is injected on top, the +/- icon should be injected (moved) at top again.
var pmIcon = container.getElement('.tree-img');
if (pmIcon) pmIcon.inject(container, 'top');
this.inject_checkbox(label, container.getAttribute('data-resource'));
},
inject_checkbox:function(container, value)
{
var cb = new Element('input', {
'type':'checkbox',
'name': this.options.cb_name,
'value': value,
'id': container.getAttribute('for'),
'class':'mr5'
});
cb.inject(container, 'top');
// Set checked
if (this.rules.contains(value))
cb.setAttribute('checked', true);
// Event
this.set_checkbox_event(cb);
},
create_actions_li:function(container, actions)
{
actions = actions.split(',');
var id = container.getAttribute('data-id');
var ul = new Element('ul', {'class':'tree', 'data-id':id, 'style':'display:none;'});
actions.each(function(action)
{
var li = new Element('li',{'data-id':this.options.cb_name + '-' + action + id, 'class':'ml16'});
var spIcon = new Element('div', {'class':'tree-img line node'});
action = String.from(action).trim();
var a = new Element('a', {'text': action.replace('_', ' ').capitalize(), 'title':'action:' + action + ', resource:' + container.getAttribute('data-resource')});
var label = new Element('label', {
'for':this.options.cb_name + '-' + action + id
}).adopt(a).inject(li, 'top');
spIcon.inject(li, 'top');
li.inject(ul);
this.inject_checkbox(label, container.getAttribute('data-resource') + ':' + action);
}.bind(this));
ul.inject(container);
},
set_checkbox_event:function(cb)
{
var self = this;
cb.addEvent('change', function(evt)
{
var li = evt.target.getParent('li');
var childLis = li.getElements('li');
var checked = evt.target.getProperty('checked');
childLis.each(function(item){
item.getElement('input').setProperty('checked', checked);
});
if (typeOf(self.options.onCheck) == 'function')
self.options.onCheck(self);
});
},
get_rules_array:function()
{
var data = new Array();
if (this.options.rules)
{
this.options.rules.each(function(rule)
{
data.push(rule.resource);
if (rule.actions != '')
{
var actions = rule.actions.split(',');
actions.each(function(action){
data.push(rule.resource + ':' + action);
});
}
});
}
return data;
}
});
|
const AbstractEndpoint = require('../endpoint')
module.exports = class NodesEndpoint extends AbstractEndpoint {
constructor (client) {
super(client)
this.url = '/v2/nodes'
this.isPaginated = true
this.isBulk = true
this.cacheTime = 24 * 60 * 60
}
}
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 4C7.7 4 3.78 5.6.79 8.24.35 8.63.32 9.3.73 9.71l10.56 10.58c.39.39 1.02.39 1.42 0L23.27 9.71c.41-.41.38-1.08-.06-1.47C20.22 5.6 16.3 4 12 4zm0 4c-2.86 0-5.5.94-7.65 2.51L2.92 9.07C5.51 7.08 8.67 6 12 6s6.49 1.08 9.08 3.07l-1.43 1.43C17.5 8.94 14.86 8 12 8z"
}), 'NetworkWifiRounded'); |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M2 5c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1s-1-.45-1-1V6c0-.55.45-1 1-1zm4 0c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1s-1-.45-1-1V6c0-.55.45-1 1-1zm16 0H10c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM11.64 16.19l1.47-1.86c.2-.25.57-.25.78-.01l1.4 1.68 2.1-2.71c.2-.26.59-.26.79 0l2.21 2.9c.25.33.02.8-.4.8h-7.96c-.41.01-.65-.47-.39-.8z"
}), 'BurstModeRounded'); |
'use strict';
var Faye = {
VERSION: '0.8.9',
BAYEUX_VERSION: '1.0',
ID_LENGTH: 160,
JSONP_CALLBACK: 'jsonpcallback',
CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'],
MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'],
ENV: (typeof global === 'undefined') ? window : global,
extend: function(dest, source, overwrite) {
if (!source) return dest;
for (var key in source) {
if (!source.hasOwnProperty(key)) continue;
if (dest.hasOwnProperty(key) && overwrite === false) continue;
if (dest[key] !== source[key])
dest[key] = source[key];
}
return dest;
},
random: function(bitlength) {
bitlength = bitlength || this.ID_LENGTH;
if (bitlength > 32) {
var parts = Math.ceil(bitlength / 32),
string = '';
while (parts--) string += this.random(32);
var chars = string.split(''), result = '';
while (chars.length > 0) result += chars.pop();
return result;
}
var limit = Math.pow(2, bitlength) - 1,
maxSize = limit.toString(36).length,
string = Math.floor(Math.random() * limit).toString(36);
while (string.length < maxSize) string = '0' + string;
return string;
},
clientIdFromMessages: function(messages) {
var first = [].concat(messages)[0];
return first && first.clientId;
},
copyObject: function(object) {
var clone, i, key;
if (object instanceof Array) {
clone = [];
i = object.length;
while (i--) clone[i] = Faye.copyObject(object[i]);
return clone;
} else if (typeof object === 'object') {
clone = (object === null) ? null : {};
for (key in object) clone[key] = Faye.copyObject(object[key]);
return clone;
} else {
return object;
}
},
commonElement: function(lista, listb) {
for (var i = 0, n = lista.length; i < n; i++) {
if (this.indexOf(listb, lista[i]) !== -1)
return lista[i];
}
return null;
},
indexOf: function(list, needle) {
if (list.indexOf) return list.indexOf(needle);
for (var i = 0, n = list.length; i < n; i++) {
if (list[i] === needle) return i;
}
return -1;
},
map: function(object, callback, context) {
if (object.map) return object.map(callback, context);
var result = [];
if (object instanceof Array) {
for (var i = 0, n = object.length; i < n; i++) {
result.push(callback.call(context || null, object[i], i));
}
} else {
for (var key in object) {
if (!object.hasOwnProperty(key)) continue;
result.push(callback.call(context || null, key, object[key]));
}
}
return result;
},
filter: function(array, callback, context) {
var result = [];
for (var i = 0, n = array.length; i < n; i++) {
if (callback.call(context || null, array[i], i))
result.push(array[i]);
}
return result;
},
asyncEach: function(list, iterator, callback, context) {
var n = list.length,
i = -1,
calls = 0,
looping = false;
var iterate = function() {
calls -= 1;
i += 1;
if (i === n) return callback && callback.call(context);
iterator(list[i], resume);
};
var loop = function() {
if (looping) return;
looping = true;
while (calls > 0) iterate();
looping = false;
};
var resume = function() {
calls += 1;
loop();
};
resume();
},
// http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/
toJSON: function(object) {
if (this.stringify)
return this.stringify(object, function(key, value) {
return (this[key] instanceof Array)
? this[key]
: value;
});
return JSON.stringify(object);
},
logger: function(message) {
if (typeof console !== 'undefined') console.log(message);
},
timestamp: function() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds();
var pad = function(n) {
return n < 10 ? '0' + n : String(n);
};
return pad(year) + '-' + pad(month) + '-' + pad(day) + ' ' +
pad(hour) + ':' + pad(minute) + ':' + pad(second);
}
};
if (typeof window !== 'undefined')
window.Faye = Faye;
Faye.Class = function(parent, methods) {
if (typeof parent !== 'function') {
methods = parent;
parent = Object;
}
var klass = function() {
if (!this.initialize) return this;
return this.initialize.apply(this, arguments) || this;
};
var bridge = function() {};
bridge.prototype = parent.prototype;
klass.prototype = new bridge();
Faye.extend(klass.prototype, methods);
return klass;
};
Faye.Namespace = Faye.Class({
initialize: function() {
this._used = {};
},
exists: function(id) {
return this._used.hasOwnProperty(id);
},
generate: function() {
var name = Faye.random();
while (this._used.hasOwnProperty(name))
name = Faye.random();
return this._used[name] = name;
},
release: function(id) {
delete this._used[id];
}
});
Faye.Error = Faye.Class({
initialize: function(code, params, message) {
this.code = code;
this.params = Array.prototype.slice.call(params);
this.message = message;
},
toString: function() {
return this.code + ':' +
this.params.join(',') + ':' +
this.message;
}
});
Faye.Error.parse = function(message) {
message = message || '';
if (!Faye.Grammar.ERROR.test(message)) return new this(null, [], message);
var parts = message.split(':'),
code = parseInt(parts[0]),
params = parts[1].split(','),
message = parts[2];
return new this(code, params, message);
};
Faye.Error.versionMismatch = function() {
return new this(300, arguments, "Version mismatch").toString();
};
Faye.Error.conntypeMismatch = function() {
return new this(301, arguments, "Connection types not supported").toString();
};
Faye.Error.extMismatch = function() {
return new this(302, arguments, "Extension mismatch").toString();
};
Faye.Error.badRequest = function() {
return new this(400, arguments, "Bad request").toString();
};
Faye.Error.clientUnknown = function() {
return new this(401, arguments, "Unknown client").toString();
};
Faye.Error.parameterMissing = function() {
return new this(402, arguments, "Missing required parameter").toString();
};
Faye.Error.channelForbidden = function() {
return new this(403, arguments, "Forbidden channel").toString();
};
Faye.Error.channelUnknown = function() {
return new this(404, arguments, "Unknown channel").toString();
};
Faye.Error.channelInvalid = function() {
return new this(405, arguments, "Invalid channel").toString();
};
Faye.Error.extUnknown = function() {
return new this(406, arguments, "Unknown extension").toString();
};
Faye.Error.publishFailed = function() {
return new this(407, arguments, "Failed to publish").toString();
};
Faye.Error.serverError = function() {
return new this(500, arguments, "Internal server error").toString();
};
Faye.Deferrable = {
callback: function(callback, context) {
if (!callback) return;
if (this._deferredStatus === 'succeeded')
return callback.apply(context, this._deferredArgs);
this._callbacks = this._callbacks || [];
this._callbacks.push([callback, context]);
},
timeout: function(seconds, message) {
var _this = this;
var timer = Faye.ENV.setTimeout(function() {
_this.setDeferredStatus('failed', message);
}, seconds * 1000);
this._timer = timer;
},
errback: function(callback, context) {
if (!callback) return;
if (this._deferredStatus === 'failed')
return callback.apply(context, this._deferredArgs);
this._errbacks = this._errbacks || [];
this._errbacks.push([callback, context]);
},
setDeferredStatus: function() {
if (this._timer)
Faye.ENV.clearTimeout(this._timer);
var args = Array.prototype.slice.call(arguments),
status = args.shift(),
callbacks;
this._deferredStatus = status;
this._deferredArgs = args;
if (status === 'succeeded')
callbacks = this._callbacks;
else if (status === 'failed')
callbacks = this._errbacks;
if (!callbacks) return;
var callback;
while (callback = callbacks.shift())
callback[0].apply(callback[1], this._deferredArgs);
}
};
Faye.Publisher = {
countListeners: function(eventType) {
if (!this._subscribers || !this._subscribers[eventType]) return 0;
return this._subscribers[eventType].length;
},
bind: function(eventType, listener, context) {
this._subscribers = this._subscribers || {};
var list = this._subscribers[eventType] = this._subscribers[eventType] || [];
list.push([listener, context]);
},
unbind: function(eventType, listener, context) {
if (!this._subscribers || !this._subscribers[eventType]) return;
if (!listener) {
delete this._subscribers[eventType];
return;
}
var list = this._subscribers[eventType],
i = list.length;
while (i--) {
if (listener !== list[i][0]) continue;
if (context && list[i][1] !== context) continue;
list.splice(i,1);
}
},
trigger: function() {
var args = Array.prototype.slice.call(arguments),
eventType = args.shift();
if (!this._subscribers || !this._subscribers[eventType]) return;
var listeners = this._subscribers[eventType].slice(),
listener;
for (var i = 0, n = listeners.length; i < n; i++) {
listener = listeners[i];
listener[0].apply(listener[1], args);
}
}
};
Faye.Timeouts = {
addTimeout: function(name, delay, callback, context) {
this._timeouts = this._timeouts || {};
if (this._timeouts.hasOwnProperty(name)) return;
var self = this;
this._timeouts[name] = Faye.ENV.setTimeout(function() {
delete self._timeouts[name];
callback.call(context);
}, 1000 * delay);
},
removeTimeout: function(name) {
this._timeouts = this._timeouts || {};
var timeout = this._timeouts[name];
if (!timeout) return;
clearTimeout(timeout);
delete this._timeouts[name];
}
};
Faye.Logging = {
LOG_LEVELS: {
error: 3,
warn: 2,
info: 1,
debug: 0
},
logLevel: 'error',
log: function(messageArgs, level) {
if (!Faye.logger) return;
var levels = Faye.Logging.LOG_LEVELS;
if (levels[Faye.Logging.logLevel] > levels[level]) return;
var messageArgs = Array.prototype.slice.apply(messageArgs),
banner = ' [' + level.toUpperCase() + '] [Faye',
klass = this.className,
message = messageArgs.shift().replace(/\?/g, function() {
try {
return Faye.toJSON(messageArgs.shift());
} catch (e) {
return '[Object]';
}
});
for (var key in Faye) {
if (klass) continue;
if (typeof Faye[key] !== 'function') continue;
if (this instanceof Faye[key]) klass = key;
}
if (klass) banner += '.' + klass;
banner += '] ';
Faye.logger(Faye.timestamp() + banner + message);
}
};
(function() {
for (var key in Faye.Logging.LOG_LEVELS)
(function(level, value) {
Faye.Logging[level] = function() {
this.log(arguments, level);
};
})(key, Faye.Logging.LOG_LEVELS[key]);
})();
Faye.Grammar = {
LOWALPHA: /^[a-z]$/,
UPALPHA: /^[A-Z]$/,
ALPHA: /^([a-z]|[A-Z])$/,
DIGIT: /^[0-9]$/,
ALPHANUM: /^(([a-z]|[A-Z])|[0-9])$/,
MARK: /^(\-|\_|\!|\~|\(|\)|\$|\@)$/,
STRING: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,
TOKEN: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,
INTEGER: /^([0-9])+$/,
CHANNEL_SEGMENT: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+$/,
CHANNEL_SEGMENTS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/,
WILD_CARD: /^\*{1,2}$/,
CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/,
VERSION_ELEMENT: /^(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*$/,
VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/,
CLIENT_ID: /^((([a-z]|[A-Z])|[0-9]))+$/,
ID: /^((([a-z]|[A-Z])|[0-9]))+$/,
ERROR_MESSAGE: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*$/,
ERROR_ARGS: /^(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*$/,
ERROR_CODE: /^[0-9][0-9][0-9]$/,
ERROR: /^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/
};
Faye.Extensible = {
addExtension: function(extension) {
this._extensions = this._extensions || [];
this._extensions.push(extension);
if (extension.added) extension.added(this);
},
removeExtension: function(extension) {
if (!this._extensions) return;
var i = this._extensions.length;
while (i--) {
if (this._extensions[i] !== extension) continue;
this._extensions.splice(i,1);
if (extension.removed) extension.removed(this);
}
},
pipeThroughExtensions: function(stage, message, callback, context) {
this.debug('Passing through ? extensions: ?', stage, message);
if (!this._extensions) return callback.call(context, message);
var extensions = this._extensions.slice();
var pipe = function(message) {
if (!message) return callback.call(context, message);
var extension = extensions.shift();
if (!extension) return callback.call(context, message);
if (extension[stage]) extension[stage](message, pipe);
else pipe(message);
};
pipe(message);
}
};
Faye.extend(Faye.Extensible, Faye.Logging);
Faye.Channel = Faye.Class({
initialize: function(name) {
this.id = this.name = name;
},
push: function(message) {
this.trigger('message', message);
},
isUnused: function() {
return this.countListeners('message') === 0;
}
});
Faye.extend(Faye.Channel.prototype, Faye.Publisher);
Faye.extend(Faye.Channel, {
HANDSHAKE: '/meta/handshake',
CONNECT: '/meta/connect',
SUBSCRIBE: '/meta/subscribe',
UNSUBSCRIBE: '/meta/unsubscribe',
DISCONNECT: '/meta/disconnect',
META: 'meta',
SERVICE: 'service',
expand: function(name) {
var segments = this.parse(name),
channels = ['/**', name];
var copy = segments.slice();
copy[copy.length - 1] = '*';
channels.push(this.unparse(copy));
for (var i = 1, n = segments.length; i < n; i++) {
copy = segments.slice(0, i);
copy.push('**');
channels.push(this.unparse(copy));
}
return channels;
},
isValid: function(name) {
return Faye.Grammar.CHANNEL_NAME.test(name) ||
Faye.Grammar.CHANNEL_PATTERN.test(name);
},
parse: function(name) {
if (!this.isValid(name)) return null;
return name.split('/').slice(1);
},
unparse: function(segments) {
return '/' + segments.join('/');
},
isMeta: function(name) {
var segments = this.parse(name);
return segments ? (segments[0] === this.META) : null;
},
isService: function(name) {
var segments = this.parse(name);
return segments ? (segments[0] === this.SERVICE) : null;
},
isSubscribable: function(name) {
if (!this.isValid(name)) return null;
return !this.isMeta(name) && !this.isService(name);
},
Set: Faye.Class({
initialize: function() {
this._channels = {};
},
getKeys: function() {
var keys = [];
for (var key in this._channels) keys.push(key);
return keys;
},
remove: function(name) {
delete this._channels[name];
},
hasSubscription: function(name) {
return this._channels.hasOwnProperty(name);
},
subscribe: function(names, callback, context) {
if (!callback) return;
var name;
for (var i = 0, n = names.length; i < n; i++) {
name = names[i];
var channel = this._channels[name] = this._channels[name] || new Faye.Channel(name);
channel.bind('message', callback, context);
}
},
unsubscribe: function(name, callback, context) {
var channel = this._channels[name];
if (!channel) return false;
channel.unbind('message', callback, context);
if (channel.isUnused()) {
this.remove(name);
return true;
} else {
return false;
}
},
distributeMessage: function(message) {
var channels = Faye.Channel.expand(message.channel);
for (var i = 0, n = channels.length; i < n; i++) {
var channel = this._channels[channels[i]];
if (channel) channel.trigger('message', message.data);
}
}
})
});
Faye.Publication = Faye.Class(Faye.Deferrable);
Faye.Subscription = Faye.Class({
initialize: function(client, channels, callback, context) {
this._client = client;
this._channels = channels;
this._callback = callback;
this._context = context;
this._cancelled = false;
},
cancel: function() {
if (this._cancelled) return;
this._client.unsubscribe(this._channels, this._callback, this._context);
this._cancelled = true;
},
unsubscribe: function() {
this.cancel();
}
});
Faye.extend(Faye.Subscription.prototype, Faye.Deferrable);
Faye.Client = Faye.Class({
UNCONNECTED: 1,
CONNECTING: 2,
CONNECTED: 3,
DISCONNECTED: 4,
HANDSHAKE: 'handshake',
RETRY: 'retry',
NONE: 'none',
CONNECTION_TIMEOUT: 60.0,
DEFAULT_RETRY: 5.0,
DEFAULT_ENDPOINT: '/bayeux',
INTERVAL: 0.0,
initialize: function(endpoint, options) {
this.info('New client created for ?', endpoint);
this._options = options || {};
this.endpoint = endpoint || this.DEFAULT_ENDPOINT;
this.endpoints = this._options.endpoints || {};
this.transports = {};
this._cookies = Faye.CookieJar && new Faye.CookieJar();
this._headers = {};
this._disabled = [];
this.retry = this._options.retry || this.DEFAULT_RETRY;
this._state = this.UNCONNECTED;
this._channels = new Faye.Channel.Set();
this._messageId = 0;
this._responseCallbacks = {};
this._advice = {
reconnect: this.RETRY,
interval: 1000 * (this._options.interval || this.INTERVAL),
timeout: 1000 * (this._options.timeout || this.CONNECTION_TIMEOUT)
};
if (Faye.Event)
Faye.Event.on(Faye.ENV, 'beforeunload', function() {
if (Faye.indexOf(this._disabled, 'autodisconnect') < 0)
this.disconnect();
}, this);
},
disable: function(feature) {
this._disabled.push(feature);
},
setHeader: function(name, value) {
this._headers[name] = value;
},
getClientId: function() {
return this._clientId;
},
getState: function() {
switch (this._state) {
case this.UNCONNECTED: return 'UNCONNECTED';
case this.CONNECTING: return 'CONNECTING';
case this.CONNECTED: return 'CONNECTED';
case this.DISCONNECTED: return 'DISCONNECTED';
}
},
// Request
// MUST include: * channel
// * version
// * supportedConnectionTypes
// MAY include: * minimumVersion
// * ext
// * id
//
// Success Response Failed Response
// MUST include: * channel MUST include: * channel
// * version * successful
// * supportedConnectionTypes * error
// * clientId MAY include: * supportedConnectionTypes
// * successful * advice
// MAY include: * minimumVersion * version
// * advice * minimumVersion
// * ext * ext
// * id * id
// * authSuccessful
handshake: function(callback, context) {
if (this._advice.reconnect === this.NONE) return;
if (this._state !== this.UNCONNECTED) return;
this._state = this.CONNECTING;
var self = this;
this.info('Initiating handshake with ?', this.endpoint);
this._selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
this._send({
channel: Faye.Channel.HANDSHAKE,
version: Faye.BAYEUX_VERSION,
supportedConnectionTypes: [this._transport.connectionType]
}, function(response) {
if (response.successful) {
this._state = this.CONNECTED;
this._clientId = response.clientId;
this._selectTransport(response.supportedConnectionTypes);
this.info('Handshake successful: ?', this._clientId);
this.subscribe(this._channels.getKeys(), true);
if (callback) callback.call(context);
} else {
this.info('Handshake unsuccessful');
Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._advice.interval);
this._state = this.UNCONNECTED;
}
}, this);
},
// Request Response
// MUST include: * channel MUST include: * channel
// * clientId * successful
// * connectionType * clientId
// MAY include: * ext MAY include: * error
// * id * advice
// * ext
// * id
// * timestamp
connect: function(callback, context) {
if (this._advice.reconnect === this.NONE) return;
if (this._state === this.DISCONNECTED) return;
if (this._state === this.UNCONNECTED)
return this.handshake(function() { this.connect(callback, context) }, this);
this.callback(callback, context);
if (this._state !== this.CONNECTED) return;
this.info('Calling deferred actions for ?', this._clientId);
this.setDeferredStatus('succeeded');
this.setDeferredStatus('deferred');
if (this._connectRequest) return;
this._connectRequest = true;
this.info('Initiating connection for ?', this._clientId);
this._send({
channel: Faye.Channel.CONNECT,
clientId: this._clientId,
connectionType: this._transport.connectionType
}, this._cycleConnection, this);
},
// Request Response
// MUST include: * channel MUST include: * channel
// * clientId * successful
// MAY include: * ext * clientId
// * id MAY include: * error
// * ext
// * id
disconnect: function() {
if (this._state !== this.CONNECTED) return;
this._state = this.DISCONNECTED;
this.info('Disconnecting ?', this._clientId);
this._send({
channel: Faye.Channel.DISCONNECT,
clientId: this._clientId
}, function(response) {
if (response.successful) this._transport.close();
}, this);
this.info('Clearing channel listeners for ?', this._clientId);
this._channels = new Faye.Channel.Set();
},
// Request Response
// MUST include: * channel MUST include: * channel
// * clientId * successful
// * subscription * clientId
// MAY include: * ext * subscription
// * id MAY include: * error
// * advice
// * ext
// * id
// * timestamp
subscribe: function(channel, callback, context) {
if (channel instanceof Array)
return Faye.map(channel, function(c) {
return this.subscribe(c, callback, context);
}, this);
var subscription = new Faye.Subscription(this, channel, callback, context),
force = (callback === true),
hasSubscribe = this._channels.hasSubscription(channel);
if (hasSubscribe && !force) {
this._channels.subscribe([channel], callback, context);
subscription.setDeferredStatus('succeeded');
return subscription;
}
this.connect(function() {
this.info('Client ? attempting to subscribe to ?', this._clientId, channel);
if (!force) this._channels.subscribe([channel], callback, context);
this._send({
channel: Faye.Channel.SUBSCRIBE,
clientId: this._clientId,
subscription: channel
}, function(response) {
if (!response.successful) {
subscription.setDeferredStatus('failed', Faye.Error.parse(response.error));
return this._channels.unsubscribe(channel, callback, context);
}
var channels = [].concat(response.subscription);
this.info('Subscription acknowledged for ? to ?', this._clientId, channels);
subscription.setDeferredStatus('succeeded');
}, this);
}, this);
return subscription;
},
// Request Response
// MUST include: * channel MUST include: * channel
// * clientId * successful
// * subscription * clientId
// MAY include: * ext * subscription
// * id MAY include: * error
// * advice
// * ext
// * id
// * timestamp
unsubscribe: function(channel, callback, context) {
if (channel instanceof Array)
return Faye.map(channel, function(c) {
return this.unsubscribe(c, callback, context);
}, this);
var dead = this._channels.unsubscribe(channel, callback, context);
if (!dead) return;
this.connect(function() {
this.info('Client ? attempting to unsubscribe from ?', this._clientId, channel);
this._send({
channel: Faye.Channel.UNSUBSCRIBE,
clientId: this._clientId,
subscription: channel
}, function(response) {
if (!response.successful) return;
var channels = [].concat(response.subscription);
this.info('Unsubscription acknowledged for ? from ?', this._clientId, channels);
}, this);
}, this);
},
// Request Response
// MUST include: * channel MUST include: * channel
// * data * successful
// MAY include: * clientId MAY include: * id
// * id * error
// * ext * ext
publish: function(channel, data) {
var publication = new Faye.Publication();
this.connect(function() {
this.info('Client ? queueing published message to ?: ?', this._clientId, channel, data);
this._send({
channel: channel,
data: data,
clientId: this._clientId
}, function(response) {
if (response.successful)
publication.setDeferredStatus('succeeded');
else
publication.setDeferredStatus('failed', Faye.Error.parse(response.error));
}, this);
}, this);
return publication;
},
receiveMessage: function(message) {
this.pipeThroughExtensions('incoming', message, function(message) {
if (!message) return;
if (message.advice) this._handleAdvice(message.advice);
this._deliverMessage(message);
if (message.successful === undefined) return;
var callback = this._responseCallbacks[message.id];
if (!callback) return;
delete this._responseCallbacks[message.id];
callback[0].call(callback[1], message);
}, this);
},
_selectTransport: function(transportTypes) {
Faye.Transport.get(this, transportTypes, this._disabled, function(transport) {
this.debug('Selected ? transport for ?', transport.connectionType, transport.endpoint);
if (transport === this._transport) return;
if (this._transport) this._transport.close();
this._transport = transport;
this._transport.cookies = this._cookies;
this._transport.headers = this._headers;
transport.bind('down', function() {
if (this._transportUp !== undefined && !this._transportUp) return;
this._transportUp = false;
this.trigger('transport:down');
}, this);
transport.bind('up', function() {
if (this._transportUp !== undefined && this._transportUp) return;
this._transportUp = true;
this.trigger('transport:up');
}, this);
}, this);
},
_send: function(message, callback, context) {
message.id = this._generateMessageId();
if (callback) this._responseCallbacks[message.id] = [callback, context];
this.pipeThroughExtensions('outgoing', message, function(message) {
if (!message) return;
this._transport.send(message, this._advice.timeout / 1000);
}, this);
},
_generateMessageId: function() {
this._messageId += 1;
if (this._messageId >= Math.pow(2,32)) this._messageId = 0;
return this._messageId.toString(36);
},
_handleAdvice: function(advice) {
Faye.extend(this._advice, advice);
if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {
this._state = this.UNCONNECTED;
this._clientId = null;
this._cycleConnection();
}
},
_deliverMessage: function(message) {
if (!message.channel || message.data === undefined) return;
this.info('Client ? calling listeners for ? with ?', this._clientId, message.channel, message.data);
this._channels.distributeMessage(message);
},
_teardownConnection: function() {
if (!this._connectRequest) return;
this._connectRequest = null;
this.info('Closed connection for ?', this._clientId);
},
_cycleConnection: function() {
this._teardownConnection();
var self = this;
Faye.ENV.setTimeout(function() { self.connect() }, this._advice.interval);
}
});
Faye.extend(Faye.Client.prototype, Faye.Deferrable);
Faye.extend(Faye.Client.prototype, Faye.Publisher);
Faye.extend(Faye.Client.prototype, Faye.Logging);
Faye.extend(Faye.Client.prototype, Faye.Extensible);
Faye.Transport = Faye.extend(Faye.Class({
MAX_DELAY: 0.0,
batching: true,
initialize: function(client, endpoint) {
this._client = client;
this.endpoint = endpoint;
this._outbox = [];
},
close: function() {},
send: function(message, timeout) {
this.debug('Client ? sending message to ?: ?',
this._client._clientId, this.endpoint, message);
if (!this.batching) return this.request([message], timeout);
this._outbox.push(message);
this._timeout = timeout;
if (message.channel === Faye.Channel.HANDSHAKE)
return this.addTimeout('publish', 0.01, this.flush, this);
if (message.channel === Faye.Channel.CONNECT)
this._connectMessage = message;
if (this.shouldFlush && this.shouldFlush(this._outbox))
return this.flush();
this.addTimeout('publish', this.MAX_DELAY, this.flush, this);
},
flush: function() {
this.removeTimeout('publish');
if (this._outbox.length > 1 && this._connectMessage)
this._connectMessage.advice = {timeout: 0};
this.request(this._outbox, this._timeout);
this._connectMessage = null;
this._outbox = [];
},
receive: function(responses) {
this.debug('Client ? received from ?: ?',
this._client._clientId, this.endpoint, responses);
for (var i = 0, n = responses.length; i < n; i++) {
this._client.receiveMessage(responses[i]);
}
},
retry: function(message, timeout) {
var called = false,
retry = this._client.retry * 1000,
self = this;
return function() {
if (called) return;
called = true;
Faye.ENV.setTimeout(function() { self.request(message, timeout) }, retry);
};
}
}), {
MAX_URL_LENGTH: 2048,
get: function(client, allowed, disabled, callback, context) {
var endpoint = client.endpoint;
Faye.asyncEach(this._transports, function(pair, resume) {
var connType = pair[0], klass = pair[1],
connEndpoint = client.endpoints[connType] || endpoint;
if (Faye.indexOf(disabled, connType) >= 0)
return resume();
if (Faye.indexOf(allowed, connType) < 0) {
klass.isUsable(client, connEndpoint, function() {});
return resume();
}
klass.isUsable(client, connEndpoint, function(isUsable) {
if (!isUsable) return resume();
var transport = klass.hasOwnProperty('create') ? klass.create(client, connEndpoint) : new klass(client, connEndpoint);
callback.call(context, transport);
});
}, function() {
throw new Error('Could not find a usable connection type for ' + endpoint);
});
},
register: function(type, klass) {
this._transports.push([type, klass]);
klass.prototype.connectionType = type;
},
_transports: []
});
Faye.extend(Faye.Transport.prototype, Faye.Logging);
Faye.extend(Faye.Transport.prototype, Faye.Publisher);
Faye.extend(Faye.Transport.prototype, Faye.Timeouts);
Faye.Set = Faye.Class({
initialize: function() {
this._index = {};
},
add: function(item) {
var key = (item.id !== undefined) ? item.id : item;
if (this._index.hasOwnProperty(key)) return false;
this._index[key] = item;
return true;
},
forEach: function(block, context) {
for (var key in this._index) {
if (this._index.hasOwnProperty(key))
block.call(context, this._index[key]);
}
},
isEmpty: function() {
for (var key in this._index) {
if (this._index.hasOwnProperty(key)) return false;
}
return true;
},
member: function(item) {
for (var key in this._index) {
if (this._index[key] === item) return true;
}
return false;
},
remove: function(item) {
var key = (item.id !== undefined) ? item.id : item;
var removed = this._index.hasOwnProperty(key);
delete this._index[key];
return removed;
},
toArray: function() {
var array = [];
this.forEach(function(item) { array.push(item) });
return array;
}
});
Faye.Engine = {
get: function(options) {
return new Faye.Engine.Proxy(options);
},
METHODS: ['createClient', 'clientExists', 'destroyClient', 'ping', 'subscribe', 'unsubscribe']
};
Faye.Engine.Proxy = Faye.Class({
MAX_DELAY: 0.0,
INTERVAL: 0.0,
TIMEOUT: 60.0,
className: 'Engine',
initialize: function(options) {
this._options = options || {};
this._connections = {};
this.interval = this._options.interval || this.INTERVAL;
this.timeout = this._options.timeout || this.TIMEOUT;
var engineClass = this._options.type || Faye.Engine.Memory;
this._engine = engineClass.create(this, this._options);
this.bind('disconnect', function(clientId) {
var self = this;
setTimeout(function() { self.closeConnection(clientId) }, 10);
}, this);
this.debug('Created new engine: ?', this._options);
},
connect: function(clientId, options, callback, context) {
this.debug('Accepting connection from ?', clientId);
this._engine.ping(clientId);
var conn = this.connection(clientId, true);
conn.connect(options, callback, context);
this._engine.emptyQueue(clientId);
},
hasConnection: function(clientId) {
return this._connections.hasOwnProperty(clientId);
},
connection: function(clientId, create) {
var conn = this._connections[clientId];
if (conn || !create) return conn;
this._connections[clientId] = new Faye.Engine.Connection(this, clientId);
this.trigger('connection:open', clientId);
return this._connections[clientId];
},
closeConnection: function(clientId) {
this.debug('Closing connection for ?', clientId);
var conn = this._connections[clientId];
if (!conn) return;
if (conn.socket) conn.socket.close();
this.trigger('connection:close', clientId);
delete this._connections[clientId];
},
openSocket: function(clientId, socket) {
if (!clientId) return;
var conn = this.connection(clientId, true);
conn.socket = socket;
},
deliver: function(clientId, messages) {
if (!messages || messages.length === 0) return false;
var conn = this.connection(clientId, false);
if (!conn) return false;
for (var i = 0, n = messages.length; i < n; i++) {
conn.deliver(messages[i]);
}
return true;
},
generateId: function() {
return Faye.random();
},
flush: function(clientId) {
if (!clientId) return;
this.debug('Flushing connection for ?', clientId);
var conn = this.connection(clientId, false);
if (conn) conn.flush(true);
},
disconnect: function() {
if (this._engine.disconnect) return this._engine.disconnect();
},
publish: function(message) {
var channels = Faye.Channel.expand(message.channel);
return this._engine.publish(message, channels);
}
});
Faye.Engine.METHODS.forEach(function(method) {
Faye.Engine.Proxy.prototype[method] = function() {
return this._engine[method].apply(this._engine, arguments);
};
})
Faye.extend(Faye.Engine.Proxy.prototype, Faye.Publisher);
Faye.extend(Faye.Engine.Proxy.prototype, Faye.Logging);
Faye.Engine.Connection = Faye.Class({
initialize: function(engine, id, options) {
this._engine = engine;
this._id = id;
this._options = options;
this._inbox = [];
},
deliver: function(message) {
if (this.socket) return this.socket.send(message);
this._inbox.push(message);
this._beginDeliveryTimeout();
},
connect: function(options, callback, context) {
options = options || {};
var timeout = (options.timeout !== undefined) ? options.timeout / 1000 : this._engine.timeout;
this.setDeferredStatus('deferred');
this.callback(callback, context);
this._beginDeliveryTimeout();
this._beginConnectionTimeout(timeout);
},
flush: function(force) {
this._releaseConnection(force);
this.setDeferredStatus('succeeded', this._inbox);
this._inbox = [];
},
_releaseConnection: function(force) {
if (force || !this.socket) this._engine.closeConnection(this._id);
this.removeTimeout('connection');
this.removeTimeout('delivery');
},
_beginDeliveryTimeout: function() {
if (this._inbox.length === 0) return;
this.addTimeout('delivery', this._engine.MAX_DELAY, this.flush, this);
},
_beginConnectionTimeout: function(timeout) {
this.addTimeout('connection', timeout, this.flush, this);
}
});
Faye.extend(Faye.Engine.Connection.prototype, Faye.Deferrable);
Faye.extend(Faye.Engine.Connection.prototype, Faye.Timeouts);
Faye.Engine.Memory = function(server, options) {
this._server = server;
this._options = options || {};
this._namespace = new Faye.Namespace();
this._clients = {};
this._channels = {};
this._messages = {};
};
Faye.Engine.Memory.create = function(server, options) {
return new this(server, options);
};
Faye.Engine.Memory.prototype = {
createClient: function(callback, context) {
var clientId = this._namespace.generate();
this._server.debug('Created new client ?', clientId);
this.ping(clientId);
this._server.trigger('handshake', clientId);
callback.call(context, clientId);
},
destroyClient: function(clientId, callback, context) {
if (!this._namespace.exists(clientId)) return;
var clients = this._clients;
if (clients[clientId])
clients[clientId].forEach(function(channel) { this.unsubscribe(clientId, channel) }, this);
this.removeTimeout(clientId);
this._namespace.release(clientId);
delete this._messages[clientId];
this._server.debug('Destroyed client ?', clientId);
this._server.trigger('disconnect', clientId);
if (callback) callback.call(context);
},
clientExists: function(clientId, callback, context) {
callback.call(context, this._namespace.exists(clientId));
},
ping: function(clientId) {
var timeout = this._server.timeout;
if (typeof timeout !== 'number') return;
this._server.debug('Ping ?, ?', clientId, timeout);
this.removeTimeout(clientId);
this.addTimeout(clientId, 2 * timeout, function() {
this.destroyClient(clientId);
}, this);
},
subscribe: function(clientId, channel, callback, context) {
var clients = this._clients, channels = this._channels;
clients[clientId] = clients[clientId] || new Faye.Set();
var trigger = clients[clientId].add(channel);
channels[channel] = channels[channel] || new Faye.Set();
channels[channel].add(clientId);
this._server.debug('Subscribed client ? to channel ?', clientId, channel);
if (trigger) this._server.trigger('subscribe', clientId, channel);
if (callback) callback.call(context, true);
},
unsubscribe: function(clientId, channel, callback, context) {
var clients = this._clients,
channels = this._channels,
trigger = false;
if (clients[clientId]) {
trigger = clients[clientId].remove(channel);
if (clients[clientId].isEmpty()) delete clients[clientId];
}
if (channels[channel]) {
channels[channel].remove(clientId);
if (channels[channel].isEmpty()) delete channels[channel];
}
this._server.debug('Unsubscribed client ? from channel ?', clientId, channel);
if (trigger) this._server.trigger('unsubscribe', clientId, channel);
if (callback) callback.call(context, true);
},
publish: function(message, channels) {
this._server.debug('Publishing message ?', message);
var messages = this._messages,
clients = new Faye.Set(),
subs;
for (var i = 0, n = channels.length; i < n; i++) {
subs = this._channels[channels[i]];
if (!subs) continue;
subs.forEach(clients.add, clients);
}
clients.forEach(function(clientId) {
this._server.debug('Queueing for client ?: ?', clientId, message);
messages[clientId] = messages[clientId] || [];
messages[clientId].push(Faye.copyObject(message));
this.emptyQueue(clientId);
}, this);
this._server.trigger('publish', message.clientId, message.channel, message.data);
},
emptyQueue: function(clientId) {
if (!this._server.hasConnection(clientId)) return;
this._server.deliver(clientId, this._messages[clientId]);
delete this._messages[clientId];
}
};
Faye.extend(Faye.Engine.Memory.prototype, Faye.Timeouts);
Faye.Server = Faye.Class({
META_METHODS: ["handshake", "connect", "disconnect", "subscribe", "unsubscribe"],
initialize: function(options) {
this._options = options || {};
var engineOpts = this._options.engine || {};
engineOpts.timeout = this._options.timeout;
this._engine = Faye.Engine.get(engineOpts);
this.info('Created new server: ?', this._options);
},
flushConnection: function(messages) {
var clientId = Faye.clientIdFromMessages(messages);
this.info('Flushing connection for ?', clientId);
this._engine.flush(clientId);
},
openSocket: function(clientId, socket) {
this._engine.openSocket(clientId, new Faye.Server.Socket(this, socket));
},
closeSocket: function(clientId) {
this._engine.flush(clientId);
},
process: function(messages, local, callback, context) {
messages = [].concat(messages);
this.info('Processing messages: ? (local: ?)', messages, local);
if (messages.length === 0) return callback.call(context, []);
var processed = 0, responses = [], self = this;
var gatherReplies = function(replies) {
responses = responses.concat(replies);
processed += 1;
if (processed < messages.length) return;
var n = responses.length;
while (n--) {
if (!responses[n]) responses.splice(n,1);
}
self.info('Returning replies: ?', responses);
callback.call(context, responses);
};
var handleReply = function(replies) {
var extended = 0, expected = replies.length;
if (expected === 0) gatherReplies(replies);
for (var i = 0, n = replies.length; i < n; i++) {
this.debug('Processing reply: ?', replies[i]);
(function(index) {
self.pipeThroughExtensions('outgoing', replies[index], function(message) {
replies[index] = message;
extended += 1;
if (extended === expected) gatherReplies(replies);
});
})(i);
}
};
for (var i = 0, n = messages.length; i < n; i++) {
this.pipeThroughExtensions('incoming', messages[i], function(pipedMessage) {
this._handle(pipedMessage, local, handleReply, this);
}, this);
}
},
_makeResponse: function(message) {
var response = {};
if (message.id) response.id = message.id;
if (message.clientId) response.clientId = message.clientId;
if (message.channel) response.channel = message.channel;
if (message.error) response.error = message.error;
response.successful = !response.error;
return response;
},
_handle: function(message, local, callback, context) {
if (!message) return callback.call(context, []);
this.info('Handling message: ? (local: ?)', message, local);
var channelName = message.channel,
error = message.error,
response;
if (Faye.Channel.isMeta(channelName))
return this._handleMeta(message, local, callback, context);
if (!Faye.Grammar.CHANNEL_NAME.test(channelName))
error = Faye.Error.channelInvalid(channelName);
if (!error) this._engine.publish(message);
response = this._makeResponse(message);
if (error) response.error = error;
response.successful = !response.error;
callback.call(context, [response]);
},
_handleMeta: function(message, local, callback, context) {
var method = Faye.Channel.parse(message.channel)[1],
clientId = message.clientId,
response;
if (Faye.indexOf(this.META_METHODS, method) < 0) {
response = this._makeResponse(message);
response.error = Faye.Error.channelForbidden(message.channel);
response.successful = false;
return callback.call(context, [response]);
}
this[method](message, local, function(responses) {
responses = [].concat(responses);
for (var i = 0, n = responses.length; i < n; i++) this._advize(responses[i], message.connectionType);
callback.call(context, responses);
}, this);
},
_advize: function(response, connectionType) {
if (Faye.indexOf([Faye.Channel.HANDSHAKE, Faye.Channel.CONNECT], response.channel) < 0)
return;
var interval, timeout;
if (connectionType === 'eventsource') {
interval = Math.floor(this._engine.timeout * 1000);
timeout = 0;
} else {
interval = Math.floor(this._engine.interval * 1000);
timeout = Math.floor(this._engine.timeout * 1000);
}
response.advice = response.advice || {};
if (response.error) {
Faye.extend(response.advice, {reconnect: 'handshake'}, false);
} else {
Faye.extend(response.advice, {
reconnect: 'retry',
interval: interval,
timeout: timeout
}, false);
}
},
// MUST contain * version
// * supportedConnectionTypes
// MAY contain * minimumVersion
// * ext
// * id
handshake: function(message, local, callback, context) {
var response = this._makeResponse(message);
response.version = Faye.BAYEUX_VERSION;
if (!message.version)
response.error = Faye.Error.parameterMissing('version');
var clientConns = message.supportedConnectionTypes,
commonConns;
response.supportedConnectionTypes = Faye.CONNECTION_TYPES;
if (clientConns) {
commonConns = Faye.filter(clientConns, function(conn) {
return Faye.indexOf(Faye.CONNECTION_TYPES, conn) >= 0;
});
if (commonConns.length === 0)
response.error = Faye.Error.conntypeMismatch(clientConns);
} else {
response.error = Faye.Error.parameterMissing('supportedConnectionTypes');
}
response.successful = !response.error;
if (!response.successful) return callback.call(context, response);
this._engine.createClient(function(clientId) {
response.clientId = clientId;
callback.call(context, response);
}, this);
},
// MUST contain * clientId
// * connectionType
// MAY contain * ext
// * id
connect: function(message, local, callback, context) {
var response = this._makeResponse(message),
clientId = message.clientId,
connectionType = message.connectionType;
this._engine.clientExists(clientId, function(exists) {
if (!exists) response.error = Faye.Error.clientUnknown(clientId);
if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
if (Faye.indexOf(Faye.CONNECTION_TYPES, connectionType) < 0)
response.error = Faye.Error.conntypeMismatch(connectionType);
if (!connectionType) response.error = Faye.Error.parameterMissing('connectionType');
response.successful = !response.error;
if (!response.successful) {
delete response.clientId;
return callback.call(context, response);
}
if (message.connectionType === 'eventsource') {
message.advice = message.advice || {};
message.advice.timeout = 0;
}
this._engine.connect(response.clientId, message.advice, function(events) {
callback.call(context, [response].concat(events));
});
}, this);
},
// MUST contain * clientId
// MAY contain * ext
// * id
disconnect: function(message, local, callback, context) {
var response = this._makeResponse(message),
clientId = message.clientId;
this._engine.clientExists(clientId, function(exists) {
if (!exists) response.error = Faye.Error.clientUnknown(clientId);
if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
response.successful = !response.error;
if (!response.successful) delete response.clientId;
if (response.successful) this._engine.destroyClient(clientId);
callback.call(context, response);
}, this);
},
// MUST contain * clientId
// * subscription
// MAY contain * ext
// * id
subscribe: function(message, local, callback, context) {
var response = this._makeResponse(message),
clientId = message.clientId,
subscription = message.subscription,
channel;
subscription = subscription ? [].concat(subscription) : [];
this._engine.clientExists(clientId, function(exists) {
if (!exists) response.error = Faye.Error.clientUnknown(clientId);
if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
if (!message.subscription) response.error = Faye.Error.parameterMissing('subscription');
response.subscription = message.subscription || [];
for (var i = 0, n = subscription.length; i < n; i++) {
channel = subscription[i];
if (response.error) break;
if (!local && !Faye.Channel.isSubscribable(channel)) response.error = Faye.Error.channelForbidden(channel);
if (!Faye.Channel.isValid(channel)) response.error = Faye.Error.channelInvalid(channel);
if (response.error) break;
this._engine.subscribe(clientId, channel);
}
response.successful = !response.error;
callback.call(context, response);
}, this);
},
// MUST contain * clientId
// * subscription
// MAY contain * ext
// * id
unsubscribe: function(message, local, callback, context) {
var response = this._makeResponse(message),
clientId = message.clientId,
subscription = message.subscription,
channel;
subscription = subscription ? [].concat(subscription) : [];
this._engine.clientExists(clientId, function(exists) {
if (!exists) response.error = Faye.Error.clientUnknown(clientId);
if (!clientId) response.error = Faye.Error.parameterMissing('clientId');
if (!message.subscription) response.error = Faye.Error.parameterMissing('subscription');
response.subscription = message.subscription || [];
for (var i = 0, n = subscription.length; i < n; i++) {
channel = subscription[i];
if (response.error) break;
if (!local && !Faye.Channel.isSubscribable(channel)) response.error = Faye.Error.channelForbidden(channel);
if (!Faye.Channel.isValid(channel)) response.error = Faye.Error.channelInvalid(channel);
if (response.error) break;
this._engine.unsubscribe(clientId, channel);
}
response.successful = !response.error;
callback.call(context, response);
}, this);
}
});
Faye.extend(Faye.Server.prototype, Faye.Logging);
Faye.extend(Faye.Server.prototype, Faye.Extensible);
Faye.Server.Socket = Faye.Class({
initialize: function(server, socket) {
this._server = server;
this._socket = socket;
},
send: function(message) {
this._server.pipeThroughExtensions('outgoing', message, function(pipedMessage) {
this._socket.send(JSON.stringify([pipedMessage]));
}, this);
},
close: function() {
this._socket.close();
}
});
Faye.Transport.NodeLocal = Faye.extend(Faye.Class(Faye.Transport, {
batching: false,
request: function(message, timeout) {
message = Faye.copyObject(message);
this.endpoint.process(message, true, function(responses) {
this.receive(Faye.copyObject(responses));
}, this);
}
}), {
isUsable: function(client, endpoint, callback, context) {
callback.call(context, endpoint instanceof Faye.Server);
}
});
Faye.Transport.register('in-process', Faye.Transport.NodeLocal);
Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
UNCONNECTED: 1,
CONNECTING: 2,
CONNECTED: 3,
batching: false,
isUsable: function(callback, context) {
this.callback(function() { callback.call(context, true) });
this.errback(function() { callback.call(context, false) });
this.connect();
},
request: function(messages, timeout) {
if (messages.length === 0) return;
this._messages = this._messages || {};
for (var i = 0, n = messages.length; i < n; i++) {
this._messages[messages[i].id] = messages[i];
}
this.callback(function(socket) { socket.send(Faye.toJSON(messages)) });
this.connect();
},
close: function() {
if (!this._socket) return;
this._socket.onclose = this._socket.onerror = null;
this._socket.close();
delete this._socket;
this.setDeferredStatus('deferred');
this._state = this.UNCONNECTED;
},
connect: function() {
if (Faye.Transport.WebSocket._unloaded) return;
this._state = this._state || this.UNCONNECTED;
if (this._state !== this.UNCONNECTED) return;
this._state = this.CONNECTING;
var ws = Faye.Transport.WebSocket.getClass();
if (!ws) return this.setDeferredStatus('failed');
this._socket = new ws(Faye.Transport.WebSocket.getSocketUrl(this.endpoint));
var self = this;
this._socket.onopen = function() {
self._state = self.CONNECTED;
self._everConnected = true;
self.setDeferredStatus('succeeded', self._socket);
self.trigger('up');
};
this._socket.onmessage = function(event) {
var messages = JSON.parse(event.data);
if (!messages) return;
messages = [].concat(messages);
for (var i = 0, n = messages.length; i < n; i++) {
delete self._messages[messages[i].id];
}
self.receive(messages);
};
this._socket.onclose = this._socket.onerror = function() {
var wasConnected = (self._state === self.CONNECTED);
self.setDeferredStatus('deferred');
self._state = self.UNCONNECTED;
self.close();
if (wasConnected) return self.resend();
if (!self._everConnected) return self.setDeferredStatus('failed');
var retry = self._client.retry * 1000;
Faye.ENV.setTimeout(function() { self.connect() }, retry);
self.trigger('down');
};
},
resend: function() {
if (!this._messages) return;
var messages = Faye.map(this._messages, function(id, msg) { return msg });
this.request(messages);
}
}), {
getSocketUrl: function(endpoint) {
if (Faye.URI) endpoint = Faye.URI.parse(endpoint).toURL();
return endpoint.replace(/^http(s?):/ig, 'ws$1:');
},
getClass: function() {
return (Faye.WebSocket && Faye.WebSocket.Client) ||
Faye.ENV.WebSocket ||
Faye.ENV.MozWebSocket;
},
isUsable: function(client, endpoint, callback, context) {
this.create(client, endpoint).isUsable(callback, context);
},
create: function(client, endpoint) {
var sockets = client.transports.websocket = client.transports.websocket || {};
sockets[endpoint] = sockets[endpoint] || new this(client, endpoint);
return sockets[endpoint];
}
});
Faye.extend(Faye.Transport.WebSocket.prototype, Faye.Deferrable);
Faye.Transport.register('websocket', Faye.Transport.WebSocket);
if (Faye.Event)
Faye.Event.on(Faye.ENV, 'beforeunload', function() {
Faye.Transport.WebSocket._unloaded = true;
});
Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {
request: function(message, timeout) {
var uri = url.parse(this.endpoint),
secure = (uri.protocol === 'https:'),
client = secure ? https : http,
content = new Buffer(JSON.stringify(message), 'utf8'),
retry = this.retry(message, timeout),
self = this;
var cookies = this.cookies.getCookies({domain: uri.hostname, path: uri.pathname}),
params = this._buildParams(uri, content, cookies, secure),
request = client.request(params);
request.addListener('response', function(response) {
self._handleResponse(response, retry);
self._storeCookies(uri.hostname, response.headers['set-cookie']);
});
request.addListener('error', function() {
retry();
self.trigger('down');
});
request.write(content);
request.end();
},
_buildParams: function(uri, content, cookies, secure) {
return {
method: 'POST',
host: uri.hostname,
port: uri.port || (secure ? 443 : 80),
path: uri.pathname,
headers: Faye.extend({
'Content-Length': content.length,
'Content-Type': 'application/json',
'Cookie': cookies.toValueString(),
'Host': uri.hostname
}, this.headers)
};
},
_handleResponse: function(response, retry) {
var message = null,
body = '',
self = this;
response.setEncoding('utf8');
response.addListener('data', function(chunk) { body += chunk });
response.addListener('end', function() {
try {
message = JSON.parse(body);
} catch (e) {}
if (message) {
self.receive(message);
self.trigger('up');
} else {
retry();
self.trigger('down');
}
});
},
_storeCookies: function(hostname, cookies) {
if (!cookies) return;
var cookie;
for (var i = 0, n = cookies.length; i < n; i++) {
cookie = this.cookies.setCookie(cookies[i]);
cookie = cookie[0] || cookie;
cookie.domain = cookie.domain || hostname;
}
}
}), {
isUsable: function(client, endpoint, callback, context) {
callback.call(context, typeof endpoint === 'string');
}
});
Faye.Transport.register('long-polling', Faye.Transport.NodeHttp);
var crypto = require('crypto'),
fs = require('fs'),
http = require('http'),
https = require('https'),
net = require('net'),
path = require('path'),
tls = require('tls'),
url = require('url'),
querystring = require('querystring');
Faye.WebSocket = require('faye-websocket');
Faye.EventSource = Faye.WebSocket.EventSource;
Faye.CookieJar = require('cookiejar').CookieJar;
Faye.withDataFor = function(transport, callback, context) {
var data = '';
transport.setEncoding('utf8');
transport.addListener('data', function(chunk) { data += chunk });
transport.addListener('end', function() {
callback.call(context, data);
});
};
Faye.NodeAdapter = Faye.Class({
DEFAULT_ENDPOINT: '/bayeux',
SCRIPT_PATH: 'faye-browser-min.js',
// https://github.com/joyent/node/issues/2727
CIPHER_ORDER: 'ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM',
CIPHER_OPTIONS: require('constants').SSL_OP_CIPHER_SERVER_PREFERENCE,
TYPE_JSON: {'Content-Type': 'application/json; charset=utf-8'},
TYPE_SCRIPT: {'Content-Type': 'text/javascript; charset=utf-8'},
TYPE_TEXT: {'Content-Type': 'text/plain; charset=utf-8'},
initialize: function(options) {
this._options = options || {};
this._endpoint = this._options.mount || this.DEFAULT_ENDPOINT;
this._endpointRe = new RegExp('^' + this._endpoint.replace(/\/$/, '') + '(/[^/]+)*(\\.[^\\.]+)?$');
this._server = new Faye.Server(this._options);
this._static = new Faye.StaticServer(path.dirname(__filename) + '/../browser', /\.(?:js|map)$/);
this._static.map(path.basename(this._endpoint) + '.js', this.SCRIPT_PATH);
this._static.map('client.js', this.SCRIPT_PATH);
var extensions = this._options.extensions;
if (!extensions) return;
extensions = [].concat(extensions);
for (var i = 0, n = extensions.length; i < n; i++)
this.addExtension(extensions[i]);
},
addExtension: function(extension) {
return this._server.addExtension(extension);
},
removeExtension: function(extension) {
return this._server.removeExtension(extension);
},
bind: function() {
return this._server._engine.bind.apply(this._server._engine, arguments);
},
unbind: function() {
return this._server._engine.unbind.apply(this._server._engine, arguments);
},
getClient: function() {
return this._client = this._client || new Faye.Client(this._server);
},
listen: function(port, sslOptions, callback, context) {
var ssl = sslOptions && sslOptions.cert
? { key: fs.readFileSync(sslOptions.key),
cert: fs.readFileSync(sslOptions.cert),
ciphers: this.CIPHER_ORDER,
secureOptions: this.CIPHER_OPTIONS
}
: null;
if (ssl && sslOptions.ca)
ssl.ca = Faye.map(sslOptions.ca, function(ca) { return fs.readFileSync(ca) });
var httpServer = ssl
? https.createServer(ssl, function() {})
: http.createServer(function() {});
this.attach(httpServer);
httpServer.listen(port, function() {
if (callback) callback.call(context);
});
this._httpServer = httpServer;
},
stop: function(callback, context) {
this._httpServer.addListener('close', function() {
if (callback) callback.call(context);
});
this._httpServer.close();
},
attach: function(httpServer) {
this._overrideListeners(httpServer, 'request', 'handle');
this._overrideListeners(httpServer, 'upgrade', 'handleUpgrade');
},
_overrideListeners: function(httpServer, event, method) {
var listeners = httpServer.listeners(event),
self = this;
httpServer.removeAllListeners(event);
httpServer.addListener(event, function(request) {
if (self.check(request)) return self[method].apply(self, arguments);
for (var i = 0, n = listeners.length; i < n; i++)
listeners[i].apply(this, arguments);
});
},
check: function(request) {
var path = url.parse(request.url, true).pathname;
return !!this._endpointRe.test(path);
},
handle: function(request, response) {
var requestUrl = url.parse(request.url, true),
requestMethod = request.method,
self = this;
request.addListener('error', function(error) { self._returnError(response, error) });
response.addListener('error', function(error) { self._returnError(null, error) });
if (this._static.test(requestUrl.pathname))
return this._static.call(request, response);
// http://groups.google.com/group/faye-users/browse_thread/thread/4a01bb7d25d3636a
if (requestMethod === 'OPTIONS' || request.headers['access-control-request-method'] === 'POST')
return this._handleOptions(request, response);
if (Faye.EventSource.isEventSource(request))
return this.handleEventSource(request, response);
if (requestMethod === 'GET')
return this._callWithParams(request, response, requestUrl.query);
if (requestMethod === 'POST')
return Faye.withDataFor(request, function(data) {
var type = (request.headers['content-type'] || '').split(';')[0],
params = (type === 'application/json')
? {message: data}
: querystring.parse(data);
request.body = data;
self._callWithParams(request, response, params);
});
this._returnError(response, {message: 'Unrecognized request type'});
},
handleUpgrade: function(request, socket, head) {
var ws = new Faye.WebSocket(request, socket, head, null, {ping: this._options.ping}),
clientId = null,
self = this;
ws.onmessage = function(event) {
try {
self.debug('Received message via WebSocket[' + ws.version + ']: ?', event.data);
var message = JSON.parse(event.data),
cid = Faye.clientIdFromMessages(message);
if (clientId && cid !== clientId) self._server.closeSocket(clientId);
self._server.openSocket(cid, ws);
clientId = cid;
self._server.process(message, false, function(replies) {
if (ws) ws.send(JSON.stringify(replies));
});
} catch (e) {
self.error(e.message + '\nBacktrace:\n' + e.stack);
}
};
ws.onclose = function(event) {
self._server.closeSocket(clientId);
ws = null;
};
},
handleEventSource: function(request, response) {
var es = new Faye.EventSource(request, response, {ping: this._options.ping}),
clientId = es.url.split('/').pop(),
self = this;
this.debug('Opened EventSource connection for ?', clientId);
this._server.openSocket(clientId, es);
es.onclose = function(event) {
self._server.closeSocket(clientId);
es = null;
};
},
_callWithParams: function(request, response, params) {
if (!params.message)
return this._returnError(response, {message: 'Received request with no message: ' + this._formatRequest(request)});
try {
this.debug('Received message via HTTP ' + request.method + ': ?', params.message);
var message = JSON.parse(params.message),
jsonp = params.jsonp || Faye.JSONP_CALLBACK,
isGet = (request.method === 'GET'),
type = isGet ? this.TYPE_SCRIPT : this.TYPE_JSON,
headers = Faye.extend({}, type),
origin = request.headers.origin;
if (isGet) this._server.flushConnection(message);
if (origin) headers['Access-Control-Allow-Origin'] = origin;
headers['Cache-Control'] = 'no-cache, no-store';
this._server.process(message, false, function(replies) {
var body = JSON.stringify(replies);
if (isGet) body = jsonp + '(' + body + ');';
headers['Content-Length'] = new Buffer(body, 'utf8').length.toString();
headers['Connection'] = 'close';
this.debug('HTTP response: ?', body);
response.writeHead(200, headers);
response.write(body);
response.end();
}, this);
} catch (error) {
this._returnError(response, error);
}
},
_formatRequest: function(request) {
var method = request.method.toUpperCase(),
string = 'curl -X ' + method;
string += " 'http://" + request.headers.host + request.url + "'";
if (method === 'POST') {
string += " -H 'Content-Type: " + request.headers['content-type'] + "'";
string += " -d '" + request.body + "'";
}
return string;
},
_handleOptions: function(request, response) {
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'false',
'Access-Control-Max-Age': '86400',
'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Accept, Content-Type, Pragma, X-Requested-With'
};
response.writeHead(200, headers);
response.write('');
response.end();
},
_returnError: function(response, error) {
var message = error.message;
if (error.stack) message += '\nBacktrace:\n' + error.stack;
this.error(message);
if (!response) return;
response.writeHead(400, this.TYPE_TEXT);
response.write('Bad request');
response.end();
}
});
Faye.extend(Faye.NodeAdapter.prototype, Faye.Logging);
module.exports = Faye;
Faye.StaticServer = Faye.Class({
initialize: function(directory, pathRegex) {
this._directory = directory;
this._pathRegex = pathRegex;
this._pathMap = {};
this._index = {};
},
map: function(requestPath, filename) {
this._pathMap[requestPath] = filename;
},
test: function(pathname) {
return this._pathRegex.test(pathname);
},
call: function(request, response) {
var pathname = url.parse(request.url, true).pathname,
filename = path.basename(pathname);
filename = this._pathMap[filename] || filename;
this._index[filename] = this._index[filename] || {};
var cache = this._index[filename],
fullpath = path.join(this._directory, filename);
try {
cache.content = cache.content || fs.readFileSync(fullpath);
cache.digest = cache.digest || crypto.createHash('sha1').update(cache.content).digest('hex');
cache.mtime = cache.mtime || fs.statSync(fullpath).mtime;
} catch (e) {
response.writeHead(404, {});
return response.end();
}
var type = /\.js$/.test(pathname) ? 'TYPE_SCRIPT' : 'TYPE_JSON',
ims = request.headers['if-modified-since'];
var headers = {
'ETag': cache.digest,
'Last-Modified': cache.mtime.toGMTString()
};
if (request.headers['if-none-match'] === cache.digest) {
response.writeHead(304, headers);
response.end();
}
else if (ims && cache.mtime <= new Date(ims)) {
response.writeHead(304, headers);
response.end();
}
else {
headers['Content-Length'] = cache.content.length;
Faye.extend(headers, Faye.NodeAdapter.prototype[type]);
response.writeHead(200, headers);
response.write(cache.content);
response.end();
}
}
});
|
import expandPath from 'fireplace/utils/expand-path';
import {module, test} from 'qunit';
module('Utils - expandPath');
test('replaces placeholders from the provided context', function(assert) {
assert.equal(expandPath("/foo/{{bar}}/baz", {bar: 123}), "/foo/123/baz");
});
test('replaces nested placeholders from the provided context', function(assert) {
assert.equal(expandPath("/foo/{{foo.bar}}/baz", {foo: {bar: 123}}), "/foo/123/baz");
});
test('raises an error if a placeholder cannot be found', function(assert) {
assert.throws(function() {
expandPath("/foo/{{bar}}/baz", {baz: 123});
});
});
test('ignores strings with no placeholders', function(assert) {
assert.equal(expandPath("/foo/bar/baz"), "/foo/bar/baz");
});
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsxs(React.Fragment, {
children: [/*#__PURE__*/_jsx("path", {
d: "M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"
}), /*#__PURE__*/_jsx("path", {
d: "M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z",
opacity: ".3"
}), /*#__PURE__*/_jsx("path", {
d: "M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"
})]
}), 'SignalWifi1BarLock'); |
var runner;
runner = mocha.run();
var failedTests = [];
function logFailure(test, err) {
var flattenTitles = function (test) {
var titles = [];
while (test.parent.title) {
titles.push(test.parent.title);
test = test.parent;
}
return titles.reverse();
};
failedTests.push({
name: test.title,
result: false,
message: err.message,
stack: err.stack,
titles: flattenTitles(test)
});
}
runner.on('end', function () {
window.mochaResults = runner.stats;
window.mochaResults.reports = failedTests;
$('.demo').remove();
});
runner.on('fail', logFailure);
|
'use strict';
const DigsInitValidator = require('../../lib/definitions/init-validator');
const DigsValidator = require('../../lib/definitions/validator');
const validator = require('../../lib/validator');
describe(`definitions/DigsInitValidator`, () => {
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create('DigsInitValidator');
});
afterEach(() => {
sandbox.restore();
});
it(`should be a function`, () => {
expect(DigsInitValidator).to.be.a('function');
});
describe(`static`, () => {
describe(`property`, () => {
it(`should provide static property "validator"`, () => {
expect(DigsInitValidator.validator).to.equal(validator);
});
});
describe(`method`, () => {
describe(`validateInitArgs()`, () => {
beforeEach(() => {
sandbox.stub(DigsValidator.fixed.methods, 'doValidate');
});
it(`should be a function`, () => {
expect(DigsInitValidator.validateInitArgs).to.be.a('function');
});
it(`should provide a definition which provides an object with an` +
`"initValidationArgs" property`,
() => {
expect(DigsInitValidator.validateInitArgs('foo')())
.to
.have
.property(
'initValidationArgs');
});
it(`should provide an object which validates upon initialization`,
() => {
DigsInitValidator.validateInitArgs('foo')();
expect(DigsValidator.fixed.methods.doValidate).to.have.been
.calledWithExactly(
'foo',
[]);
});
describe(`when called multiple times`, () => {
it(`should use only the last specified validation schema`, () => {
DigsInitValidator.validateInitArgs('foo').validateInitArgs('bar')();
expect(DigsValidator.fixed.methods.doValidate).to.have.been
.calledWithExactly(
'bar',
[]);
});
it(`should provide an object with "initValidation" property using ` +
`only the last specified validation schema`,
() => {
expect(DigsInitValidator.validateInitArgs('foo')
.validateInitArgs('bar')().initValidationArgs).to.equal('bar');
});
});
});
describe(`validateInitInstance()`, () => {
beforeEach(() => {
sandbox.stub(DigsValidator.fixed.methods, 'doValidate');
});
it(`should be a function`, () => {
expect(DigsInitValidator.validateInitInstance).to.be.a('function');
});
it(`should provide a definition which provides an object with an` +
`"initValidationInstance" property`,
() => {
expect(DigsInitValidator.validateInitInstance('foo')()).to.have
.property('initValidationInstance');
});
it(`should provide an object which validates upon initialization`,
() => {
const obj = DigsInitValidator.validateInitInstance('foo')();
expect(DigsValidator.fixed.methods.doValidate).to.have.been
.calledWithExactly(
'foo',
obj);
});
describe(`when called multiple times`, () => {
it(`should use only the last specified validation schema`, () => {
const obj = DigsInitValidator.validateInitInstance('foo')
.validateInitInstance('bar')();
expect(DigsValidator.fixed.methods.doValidate).to.have.been
.calledWithExactly(
'bar',
obj);
});
it(`should provide an object with "initValidationInstance" ` +
`property using only the last specified validation schema`,
() => {
expect(DigsInitValidator.validateInitInstance('foo')
.validateInitInstance('bar')()
.initValidationInstance).to.equal('bar');
});
});
});
});
});
});
|
import './test.styl';
document.body.innerHTML = '<i class="fa fa-call fa-inverse fa-5x" aria-hidden="true"></i>';
|
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node / CommonJS
factory(require('jquery'));
} else {
// Browser globals.
factory(jQuery);
}
})(function ($) {
'use strict';
var location = window.location;
var NAMESPACE = 'qor.sorting';
var EVENT_ENABLE = 'enable.' + NAMESPACE;
var EVENT_DISABLE = 'disable.' + NAMESPACE;
var EVENT_CHANGE = 'change.' + NAMESPACE;
var EVENT_MOUSE_DOWN = 'mousedown.' + NAMESPACE;
var EVENT_MOUSE_UP = 'mouseup.' + NAMESPACE;
var EVENT_DRAG_START = 'dragstart.' + NAMESPACE;
var EVENT_DRAG_END = 'dragend.' + NAMESPACE;
var EVENT_DRAG_OVER = 'dragover.' + NAMESPACE;
var EVENT_DROP = 'drop.' + NAMESPACE;
var CLASS_SORTING = 'qor-sorting';
var CLASS_HIGHLIGHT = 'qor-sorting__highlight';
var CLASS_HOVER = 'qor-sorting__hover';
var SELECTOR_TR = 'tbody > tr';
function QorSorter(element, options) {
this.$element = $(element);
this.options = $.extend({}, QorSorter.DEFAULTS, $.isPlainObject(options) && options);
this.$source = null;
this.ascending = false;
this.orderType = 0; // 0 -> mix, 1 -> ascending order, -1 -> descending order
this.startY = 0;
this.init();
}
QorSorter.prototype = {
constructor: QorSorter,
init: function () {
var options = this.options;
var $this = this.$element;
var $rows = $this.find(SELECTOR_TR);
var orderType = 0;
var count = 0;
var index = 0;
var previousPosition;
$('body').addClass(CLASS_SORTING);
$this.find('tbody .qor-table__actions').append(QorSorter.TEMPLATE);
$rows.each(function (i) {
var position = $(this).find(options.input).data('position');
if (i > 0) {
if (position > previousPosition) {
count++;
} else {
count--;
}
}
previousPosition = position;
index = i;
});
if (count === index) {
orderType = 1;
} else if (-count === index) {
orderType = -1;
}
this.$rows = $rows;
this.orderType = orderType;
this.bind();
},
bind: function () {
var options = this.options;
this.$element.
on(EVENT_CHANGE, options.input, $.proxy(this.change, this)).
on(EVENT_MOUSE_DOWN, options.toggle, $.proxy(this.mousedown, this)).
on(EVENT_MOUSE_UP, $.proxy(this.mouseup, this)).
on(EVENT_DRAG_START, SELECTOR_TR, $.proxy(this.dragstart, this)).
on(EVENT_DRAG_END, SELECTOR_TR, $.proxy(this.dragend, this)).
on(EVENT_DRAG_OVER, SELECTOR_TR, $.proxy(this.dragover, this)).
on(EVENT_DROP, SELECTOR_TR, $.proxy(this.drop, this));
},
unbind: function () {
this.$element.
off(EVENT_CHANGE, this.change).
off(EVENT_MOUSE_DOWN, this.mousedown);
},
change: function (e) {
var options = this.options;
var orderType = this.orderType;
var $rows = this.$rows;
var $sourceInput = $(e.currentTarget);
var $source = $sourceInput.closest('tr');
var $tbody = $source.parent();
var source = $sourceInput.data();
var sourcePosition = source.position;
var targetPosition = parseInt($sourceInput.val(), 10);
var largethan = targetPosition > sourcePosition;
var $target;
$rows.each(function () {
var $this = $(this);
var $input = $this.find(options.input);
var position = $input.data('position');
if (position === targetPosition) {
$target = $this;
if (largethan) {
if (orderType === 1) {
$target.after($source);
} else if (orderType === -1) {
$target.before($source);
}
} else {
if (orderType === 1) {
$target.before($source);
} else if (orderType === -1) {
$target.after($source);
}
}
}
if (largethan) {
if (position > sourcePosition && position <= targetPosition) {
$input.data('position', --position).val(position);
}
} else {
if (position < sourcePosition && position >= targetPosition) {
$input.data('position', ++position).val(position);
}
}
});
$sourceInput.data('position', targetPosition);
if (!$target) {
if (largethan) {
if (orderType === 1) {
$tbody.append($source);
} else if (orderType === -1) {
$tbody.prepend($source);
}
} else {
if (orderType === 1) {
$tbody.prepend($source);
} else if (orderType === -1) {
$tbody.append($source);
}
}
}
this.sort($source, {
url: source.sortingUrl,
from: sourcePosition,
to: targetPosition,
});
},
mousedown: function (e) {
this.startY = e.pageY;
$(e.currentTarget).closest('tr').prop('draggable', true);
},
mouseup: function () {
this.$element.find(SELECTOR_TR).prop('draggable', false);
},
dragend: function (e) {
$(SELECTOR_TR).removeClass(CLASS_HOVER);
this.$element.find(SELECTOR_TR).prop('draggable', false);
},
dragstart: function (e) {
var event = e.originalEvent,
$target = $(e.currentTarget);
if ($target.prop('draggable') && event.dataTransfer) {
event.dataTransfer.effectAllowed = 'move';
this.$source = $target;
}
},
dragover: function (e) {
var $source = this.$source;
var options = this.options;
$(SELECTOR_TR).removeClass(CLASS_HOVER);
$(e.currentTarget).prev('tr').addClass(CLASS_HOVER);
if (!$source || e.currentTarget === this.$source[0]) {
return;
}
e.preventDefault();
},
drop: function (e) {
var options = this.options;
var orderType = this.orderType;
var movedown = e.pageY > this.startY;
var $source = this.$source;
var $sourceInput;
var $target;
var source;
var sourcePosition;
var targetPosition;
var largethan;
$(SELECTOR_TR).removeClass(CLASS_HOVER);
if (!$source || e.currentTarget === this.$source[0]) {
return;
}
e.preventDefault();
$target = $(e.currentTarget);
$sourceInput = $source.find(options.input);
source = $sourceInput.data();
sourcePosition = source.position;
targetPosition = $target.find(options.input).data('position');
largethan = targetPosition > sourcePosition;
this.$element.find(SELECTOR_TR).each(function () {
var $input = $(this).find(options.input);
var position = $input.data('position');
if (largethan) {
if (position > sourcePosition && position <= targetPosition) {
$input.data('position', --position).val(position);
}
} else {
if (position < sourcePosition && position >= targetPosition) {
$input.data('position', ++position).val(position);
}
}
});
$sourceInput.data('position', targetPosition).val(targetPosition);
if (largethan) {
if (orderType === 1) {
$target.after($source);
} else if (orderType === -1) {
$target.before($source);
} else {
if (movedown) {
$target.after($source);
} else {
$target.before($source);
}
}
} else {
if (orderType === 1) {
$target.before($source);
} else if (orderType === -1) {
$target.after($source);
} else {
if (movedown) {
$target.before($source);
} else {
$target.after($source);
}
}
}
this.sort($source, {
url: source.sortingUrl,
from: sourcePosition,
to: targetPosition,
});
},
sort: function ($row, data) {
var options = this.options;
if (data.url) {
this.highlight($row);
$.ajax(data.url, {
method: 'post',
data: {
from: data.from,
to: data.to,
},
success: function (actualPosition, textStatus, xhr) {
if (xhr.status === 200) {
$row.find(options.input).data('position', actualPosition).val(actualPosition);
}
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 422) {
if (window.confirm(xhr.responseText)) {
location.reload();
}
} else {
if (window.confirm([textStatus, errorThrown].join(': '))) {
location.reload();
}
}
}
});
}
},
highlight: function ($row) {
$row.addClass(CLASS_HIGHLIGHT);
setTimeout(function () {
$row.removeClass(CLASS_HIGHLIGHT);
}, 2000);
},
destroy: function () {
this.unbind();
this.$element.removeData(NAMESPACE);
},
};
QorSorter.DEFAULTS = {
toggle: false,
input: false,
};
QorSorter.TEMPLATE = '<a class="qor-sorting__toggle"><i class="material-icons">swap_vert</i></a>';
QorSorter.plugin = function (options) {
return this.each(function () {
var $this = $(this);
var data = $this.data(NAMESPACE);
var fn;
if (!data) {
if (/destroy/.test(options)) {
return;
}
$this.data(NAMESPACE, (data = new QorSorter(this, options)));
}
if (typeof options === 'string' && $.isFunction(fn = data[options])) {
fn.apply(data);
}
});
};
$(function () {
if (!/sorting\=true/.test(location.search)) {
return;
}
var selector = '.qor-js-table';
var options = {
toggle: '.qor-sorting__toggle',
input: '.qor-sorting__position',
};
$(document).
on(EVENT_DISABLE, function (e) {
QorSorter.plugin.call($(selector, e.target), 'destroy');
}).
on(EVENT_ENABLE, function (e) {
QorSorter.plugin.call($(selector, e.target), options);
}).
trigger('disable.qor.slideout').
triggerHandler(EVENT_ENABLE);
});
return QorSorter;
});
|
'use strict';
// Init the application configuration module for AngularJS application
var ApplicationConfiguration = (function () {
// Init module configuration options
var applicationModuleName = 'app';
var applicationModuleVendorDependencies = [
'ngResource',
'ngCookies',
'ngTouch',
'ngAnimate',
'ngSanitize',
'ui.router',
'ui.bootstrap',
'adaptive.detection',
'underscore'
];
// Add a new vertical module
var registerModule = function (moduleName, dependencies) {
// Create angular module
angular.module(moduleName, dependencies || []);
// Add the module to the AngularJS configuration file
angular.module(applicationModuleName).requires.push(moduleName);
};
return {
applicationModuleName : applicationModuleName,
applicationModuleVendorDependencies: applicationModuleVendorDependencies,
registerModule : registerModule
};
})();
|
'use strict';
var Message = require('mongoose').model('Message');
module.exports = {
run: function() {
for (var i = 0; i < 33; i++) {
var message = {
owner : '53e7777a9efe98ec111e22c7',
fromID: '53e777fd9efe98ec111e22c9',
from : 'Pesho',
text: 'hello message'
};
Message.create(message, function (err, report) {
if (err) {
console.log('Failed to create new report ' + err);
}
})
}
}
}; |
var runner = require('../setup');
Sugar = runner.load('../../packages/sugar-function');
// Tests
runner.loadTest('function');
runner.run(module, 'chained', Sugar);
|
import {
messages,
ruleName,
} from ".."
import rules from "../../../rules"
import { testRule } from "../../../testUtils"
const rule = rules[ruleName]
testRule(rule, {
ruleName,
config: [[
"transform",
"background-size",
]],
accept: [ {
code: "a { background-size: cover; }",
}, {
code: "a { transform: scale(1); }",
}, {
code: "a { -webkit-transform: scale(1); }",
}, {
code: "a { transform: scale(1); background-size: cover; }",
}, {
code: "a { transform: scale(1); -webkit-transform: scale(1); background-size: cover; }",
}, {
code: "a { $scss: 0; }",
}, {
code: "a { @less: 0; }",
}, {
code: "a { --custom-property: 0; }",
} ],
reject: [ {
code: "a { background: pink; }",
message: messages.rejected("background"),
line: 1,
column: 5,
}, {
code: "a { color: pink; }",
message: messages.rejected("color"),
line: 1,
column: 5,
}, {
code: "a { overflow: hidden; background-size: cover; }",
message: messages.rejected("overflow"),
line: 1,
column: 5,
}, {
code: "a { color: orange; -webkit-transform: scale(1); }",
message: messages.rejected("color"),
line: 1,
column: 5,
} ],
})
testRule(rule, {
ruleName,
config: [[
"/^background/",
]],
accept: [ {
code: "a { background: pink; }",
}, {
code: "a { background-color: pink; }",
}, {
code: "a { background-image: none; }",
}, {
code: "a { $scss: 0; }",
}, {
code: "a { @less: 0; }",
}, {
code: "a { --custom-property: 0; }",
} ],
reject: [{
code: "a { color: pink; }",
message: messages.rejected("color"),
line: 1,
column: 5,
}],
})
testRule(rule, {
ruleName,
config: ["/margin/"],
accept: [ {
code: "a { $padding: 0; }",
}, {
code: "a { @padding: 0; }",
}, {
code: "a { --padding: 0; }",
} ],
})
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdFlipToFront = function MdFlipToFront(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm11.6 35v-3.4h3.4v3.4h-3.4z m6.8 0v-3.4h3.2v3.4h-3.2z m13.2-10v-16.6h-16.6v16.6h16.6z m0-20q1.4 0 2.4 1t1 2.4v16.6q0 1.3-1 2.3t-2.4 1.1h-16.6q-1.4 0-2.4-1.1t-1-2.3v-16.6q0-1.4 1-2.4t2.4-1h16.6z m-6.6 30v-3.4h3.4v3.4h-3.4z m-20-20v-3.4h3.4v3.4h-3.4z m3.4 20q-1.4 0-2.4-1t-1-2.4h3.4v3.4z m-3.4-6.6v-3.4h3.4v3.4h-3.4z m0-6.8v-3.2h3.4v3.2h-3.4z' })
)
);
};
exports.default = MdFlipToFront;
module.exports = exports['default']; |
version https://git-lfs.github.com/spec/v1
oid sha256:2a4d5570aa31f4808aed3a83049c3189c8c78407e497dd3f276ed008e50384b4
size 5732
|
var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var chromeArgs = require('./chrome-args.js');
var menu = require('./menu.js');
var settings = require('./settings.js');
var teams = require("./teams.js");
var tray = require("./tray.js");
settings.load();
chromeArgs.apply(settings);
teams.listen();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
}
});
app.on('ready', function() {
var quitting = false;
mainWindow = new BrowserWindow(settings.get('window'));
var indexPath = `file://${__dirname}/browser/index.html`;
mainWindow.loadURL(indexPath);
app.on('activate', function(e, hasVisibleWindows) {
if (hasVisibleWindows) {
mainWindow.focus();
} else {
if (mainWindow == null) {
mainWindow = new BrowserWindow({width: 1024, height: 600});
} else {
mainWindow.show();
}
}
});
app.on('before-quit', function(e) {
quitting = true;
});
mainWindow.on('close', function(e) {
settings.set('window:fullscreen', mainWindow.isFullScreen());
if (!mainWindow.isFullScreen()) {
var bounds = mainWindow.getBounds();
settings.set('window:x', bounds.x);
settings.set('window:y', bounds.y);
settings.set('window:width', bounds.width);
settings.set('window:height', bounds.height);
}
settings.saveState();
// Quit when the window is closed if not on OS X or if the tray icon is disabled.
if (process.platform != 'darwin' && !tray.isEnabled()) {
return;
}
if (quitting) { return; }
e.preventDefault();
mainWindow.hide();
});
mainWindow.webContents.on('will-navigate', function (e) {
e.preventDefault();
});
mainWindow.on('closed', function() {
mainWindow = null;
});
menu.load();
// Show a system tray/menu bar icon if enabled in the settings.
if (settings.get('showTrayIcon') === true) {
tray.enable(mainWindow);
}
});
|
var http = require('http');
var avault = require('avault').createVault(__dirname);
var restMap = require('./queryToRestMap.js');
var sfConnector = require('volos-salesforce');
var sfConnectorObject;
avault.get('sf', function (profileString) {
if (!profileString) {
console.log('Error: required vault not found.');
} else {
var profile = JSON.parse(profileString);
var svr = http.createServer(function (req, resp) {
sfConnectorObject.dispatchRequest(req, resp);
});
svr.listen(9009, function () {
sfConnectorObject = new sfConnector.SfConnector({"profile": profile, restMap: restMap});
sfConnectorObject.initializePaths(restMap);
console.log(sfConnectorObject.applicationName + ' node server is listening');
});
}
});
|
var messaging_enabled = process.env.FH_AMQP_APP_ENABLED;
var messaging_user = process.env.FH_AMQP_USER;
var message_pass = process.env.FH_AMQP_PASS;
var messaging_nodes = process.env.FH_AMQP_NODES;
var messaging_max_cons = process.env.FH_AMQP_CONN_MAX || 10;
var messaging_vhost = process.env.FH_AMQP_VHOST;
var messaging_exchange ="fh-events";
var amqpManager;
var retAmqp;
module.exports = function (){
//first time requed set up singletons
function connect(cb){
if (messaging_enabled && messaging_enabled !== "false" && ! retAmqp) {
var clusterNodes = [];
var nodes = (messaging_nodes && messaging_nodes.split) ? messaging_nodes.split(",") : [];
var vhost = "";
if(messaging_vhost && messaging_vhost.trim() !== "/"){
vhost = messaging_vhost.trim();
if(vhost.indexOf("/") !== 0){
vhost = "/" + vhost;
}
}
for(var i=0; i < nodes.length; i++){
var node = nodes[i].trim();
node = "amqp://"+messaging_user+":"+message_pass+"@"+node+vhost;
clusterNodes.push(node);
}
var conf = {
"enabled": messaging_enabled,
"clusterNodes": clusterNodes,
"maxReconnectAttempts": messaging_max_cons
};
var amqpjs = require('fh-amqp-js');
amqpManager = new amqpjs.AMQPManager(conf);
amqpManager.connectToCluster();
amqpManager.on("error", function(err){
cb(err);
});
//all good set up object
amqpManager.on("connection", function(){
var retObj = {};
retObj["createErrorMessage"] = function (err){
err = err || {};
return {
"uid": process.env.FH_INSTANCE,
"timestamp": new Date().getTime(),
"eventType": "CRASHED",
"eventClass": "APP_STATE",
"eventLevel": "ERROR",
"domain": process.env.FH_DOMAIN,
"appName":process.env.FH_APPNAME,
"env": process.env.FH_ENV || "",
"updatedBy":"System",
"dyno": "",
"details": {"message": "app crashed", "error": err.message, "stackTrace": err.stack}
};
};
retObj["sendErrorMessage"] = function (err , cb){
var message = retObj.createErrorMessage(err);
amqpManager.publishTopic(messaging_exchange, "fh.events.nodeapp.app.crashed", message, function (err) {
//ignore errors
cb();
});
};
cb(undefined,retObj);
});
}else if(messaging_enabled && messaging_enabled !== "false" && retAmqp){
cb(undefined,retAmqp);
}else{
cb({"message":"messaging not enabled","code":503});
}
};
connect(function (er, conn){
retAmqp = conn;
});
return {
"getAmqp": function (cb){
connect(cb);
},
"getAmqpManager": function (){
return amqpManager;
}
};
};
|
"use strict";
var helpers = require("../helpers/helpers");
exports["Portugal"] = {
"guess:by:offset" : helpers.makeTestGuess("Portugal", { offset: true, expect: "Europe/London" }),
"guess:by:abbr" : helpers.makeTestGuess("Portugal", { abbr: true, expect: "Europe/Lisbon" }),
"1911" : helpers.makeTestYear("Portugal", [
["1911-12-31T23:59:59+00:00", "23:23:14", "LMT", 2205 / 60]
]),
"1912" : helpers.makeTestYear("Portugal", [
["1912-01-01T00:00:00+00:00", "00:00:00", "WET", 0]
]),
"1916" : helpers.makeTestYear("Portugal", [
["1916-06-17T22:59:59+00:00", "22:59:59", "WET", 0],
["1916-06-17T23:00:00+00:00", "00:00:00", "WEST", -60],
["1916-10-31T23:59:59+00:00", "00:59:59", "WEST", -60],
["1916-11-01T00:00:00+00:00", "00:00:00", "WET", 0]
]),
"1917" : helpers.makeTestYear("Portugal", [
["1917-02-28T22:59:59+00:00", "22:59:59", "WET", 0],
["1917-02-28T23:00:00+00:00", "00:00:00", "WEST", -60],
["1917-10-14T22:59:59+00:00", "23:59:59", "WEST", -60],
["1917-10-14T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1918" : helpers.makeTestYear("Portugal", [
["1918-03-01T22:59:59+00:00", "22:59:59", "WET", 0],
["1918-03-01T23:00:00+00:00", "00:00:00", "WEST", -60],
["1918-10-14T22:59:59+00:00", "23:59:59", "WEST", -60],
["1918-10-14T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1919" : helpers.makeTestYear("Portugal", [
["1919-02-28T22:59:59+00:00", "22:59:59", "WET", 0],
["1919-02-28T23:00:00+00:00", "00:00:00", "WEST", -60],
["1919-10-14T22:59:59+00:00", "23:59:59", "WEST", -60],
["1919-10-14T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1920" : helpers.makeTestYear("Portugal", [
["1920-02-29T22:59:59+00:00", "22:59:59", "WET", 0],
["1920-02-29T23:00:00+00:00", "00:00:00", "WEST", -60],
["1920-10-14T22:59:59+00:00", "23:59:59", "WEST", -60],
["1920-10-14T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1921" : helpers.makeTestYear("Portugal", [
["1921-02-28T22:59:59+00:00", "22:59:59", "WET", 0],
["1921-02-28T23:00:00+00:00", "00:00:00", "WEST", -60],
["1921-10-14T22:59:59+00:00", "23:59:59", "WEST", -60],
["1921-10-14T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1924" : helpers.makeTestYear("Portugal", [
["1924-04-16T22:59:59+00:00", "22:59:59", "WET", 0],
["1924-04-16T23:00:00+00:00", "00:00:00", "WEST", -60],
["1924-10-14T22:59:59+00:00", "23:59:59", "WEST", -60],
["1924-10-14T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1926" : helpers.makeTestYear("Portugal", [
["1926-04-17T22:59:59+00:00", "22:59:59", "WET", 0],
["1926-04-17T23:00:00+00:00", "00:00:00", "WEST", -60],
["1926-10-02T22:59:59+00:00", "23:59:59", "WEST", -60],
["1926-10-02T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1927" : helpers.makeTestYear("Portugal", [
["1927-04-09T22:59:59+00:00", "22:59:59", "WET", 0],
["1927-04-09T23:00:00+00:00", "00:00:00", "WEST", -60],
["1927-10-01T22:59:59+00:00", "23:59:59", "WEST", -60],
["1927-10-01T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1928" : helpers.makeTestYear("Portugal", [
["1928-04-14T22:59:59+00:00", "22:59:59", "WET", 0],
["1928-04-14T23:00:00+00:00", "00:00:00", "WEST", -60],
["1928-10-06T22:59:59+00:00", "23:59:59", "WEST", -60],
["1928-10-06T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1929" : helpers.makeTestYear("Portugal", [
["1929-04-20T22:59:59+00:00", "22:59:59", "WET", 0],
["1929-04-20T23:00:00+00:00", "00:00:00", "WEST", -60],
["1929-10-05T22:59:59+00:00", "23:59:59", "WEST", -60],
["1929-10-05T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1931" : helpers.makeTestYear("Portugal", [
["1931-04-18T22:59:59+00:00", "22:59:59", "WET", 0],
["1931-04-18T23:00:00+00:00", "00:00:00", "WEST", -60],
["1931-10-03T22:59:59+00:00", "23:59:59", "WEST", -60],
["1931-10-03T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1932" : helpers.makeTestYear("Portugal", [
["1932-04-02T22:59:59+00:00", "22:59:59", "WET", 0],
["1932-04-02T23:00:00+00:00", "00:00:00", "WEST", -60],
["1932-10-01T22:59:59+00:00", "23:59:59", "WEST", -60],
["1932-10-01T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1934" : helpers.makeTestYear("Portugal", [
["1934-04-07T22:59:59+00:00", "22:59:59", "WET", 0],
["1934-04-07T23:00:00+00:00", "00:00:00", "WEST", -60],
["1934-10-06T22:59:59+00:00", "23:59:59", "WEST", -60],
["1934-10-06T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1935" : helpers.makeTestYear("Portugal", [
["1935-03-30T22:59:59+00:00", "22:59:59", "WET", 0],
["1935-03-30T23:00:00+00:00", "00:00:00", "WEST", -60],
["1935-10-05T22:59:59+00:00", "23:59:59", "WEST", -60],
["1935-10-05T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1936" : helpers.makeTestYear("Portugal", [
["1936-04-18T22:59:59+00:00", "22:59:59", "WET", 0],
["1936-04-18T23:00:00+00:00", "00:00:00", "WEST", -60],
["1936-10-03T22:59:59+00:00", "23:59:59", "WEST", -60],
["1936-10-03T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1937" : helpers.makeTestYear("Portugal", [
["1937-04-03T22:59:59+00:00", "22:59:59", "WET", 0],
["1937-04-03T23:00:00+00:00", "00:00:00", "WEST", -60],
["1937-10-02T22:59:59+00:00", "23:59:59", "WEST", -60],
["1937-10-02T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1938" : helpers.makeTestYear("Portugal", [
["1938-03-26T22:59:59+00:00", "22:59:59", "WET", 0],
["1938-03-26T23:00:00+00:00", "00:00:00", "WEST", -60],
["1938-10-01T22:59:59+00:00", "23:59:59", "WEST", -60],
["1938-10-01T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1939" : helpers.makeTestYear("Portugal", [
["1939-04-15T22:59:59+00:00", "22:59:59", "WET", 0],
["1939-04-15T23:00:00+00:00", "00:00:00", "WEST", -60],
["1939-11-18T22:59:59+00:00", "23:59:59", "WEST", -60],
["1939-11-18T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1940" : helpers.makeTestYear("Portugal", [
["1940-02-24T22:59:59+00:00", "22:59:59", "WET", 0],
["1940-02-24T23:00:00+00:00", "00:00:00", "WEST", -60],
["1940-10-05T22:59:59+00:00", "23:59:59", "WEST", -60],
["1940-10-05T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1941" : helpers.makeTestYear("Portugal", [
["1941-04-05T22:59:59+00:00", "22:59:59", "WET", 0],
["1941-04-05T23:00:00+00:00", "00:00:00", "WEST", -60],
["1941-10-05T22:59:59+00:00", "23:59:59", "WEST", -60],
["1941-10-05T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1942" : helpers.makeTestYear("Portugal", [
["1942-03-14T22:59:59+00:00", "22:59:59", "WET", 0],
["1942-03-14T23:00:00+00:00", "00:00:00", "WEST", -60],
["1942-04-25T21:59:59+00:00", "22:59:59", "WEST", -60],
["1942-04-25T22:00:00+00:00", "00:00:00", "WEMT", -120],
["1942-08-15T21:59:59+00:00", "23:59:59", "WEMT", -120],
["1942-08-15T22:00:00+00:00", "23:00:00", "WEST", -60],
["1942-10-24T22:59:59+00:00", "23:59:59", "WEST", -60],
["1942-10-24T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1943" : helpers.makeTestYear("Portugal", [
["1943-03-13T22:59:59+00:00", "22:59:59", "WET", 0],
["1943-03-13T23:00:00+00:00", "00:00:00", "WEST", -60],
["1943-04-17T21:59:59+00:00", "22:59:59", "WEST", -60],
["1943-04-17T22:00:00+00:00", "00:00:00", "WEMT", -120],
["1943-08-28T21:59:59+00:00", "23:59:59", "WEMT", -120],
["1943-08-28T22:00:00+00:00", "23:00:00", "WEST", -60],
["1943-10-30T22:59:59+00:00", "23:59:59", "WEST", -60],
["1943-10-30T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1944" : helpers.makeTestYear("Portugal", [
["1944-03-11T22:59:59+00:00", "22:59:59", "WET", 0],
["1944-03-11T23:00:00+00:00", "00:00:00", "WEST", -60],
["1944-04-22T21:59:59+00:00", "22:59:59", "WEST", -60],
["1944-04-22T22:00:00+00:00", "00:00:00", "WEMT", -120],
["1944-08-26T21:59:59+00:00", "23:59:59", "WEMT", -120],
["1944-08-26T22:00:00+00:00", "23:00:00", "WEST", -60],
["1944-10-28T22:59:59+00:00", "23:59:59", "WEST", -60],
["1944-10-28T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1945" : helpers.makeTestYear("Portugal", [
["1945-03-10T22:59:59+00:00", "22:59:59", "WET", 0],
["1945-03-10T23:00:00+00:00", "00:00:00", "WEST", -60],
["1945-04-21T21:59:59+00:00", "22:59:59", "WEST", -60],
["1945-04-21T22:00:00+00:00", "00:00:00", "WEMT", -120],
["1945-08-25T21:59:59+00:00", "23:59:59", "WEMT", -120],
["1945-08-25T22:00:00+00:00", "23:00:00", "WEST", -60],
["1945-10-27T22:59:59+00:00", "23:59:59", "WEST", -60],
["1945-10-27T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1946" : helpers.makeTestYear("Portugal", [
["1946-04-06T22:59:59+00:00", "22:59:59", "WET", 0],
["1946-04-06T23:00:00+00:00", "00:00:00", "WEST", -60],
["1946-10-05T22:59:59+00:00", "23:59:59", "WEST", -60],
["1946-10-05T23:00:00+00:00", "23:00:00", "WET", 0]
]),
"1947" : helpers.makeTestYear("Portugal", [
["1947-04-06T01:59:59+00:00", "01:59:59", "WET", 0],
["1947-04-06T02:00:00+00:00", "03:00:00", "WEST", -60],
["1947-10-05T01:59:59+00:00", "02:59:59", "WEST", -60],
["1947-10-05T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1948" : helpers.makeTestYear("Portugal", [
["1948-04-04T01:59:59+00:00", "01:59:59", "WET", 0],
["1948-04-04T02:00:00+00:00", "03:00:00", "WEST", -60],
["1948-10-03T01:59:59+00:00", "02:59:59", "WEST", -60],
["1948-10-03T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1949" : helpers.makeTestYear("Portugal", [
["1949-04-03T01:59:59+00:00", "01:59:59", "WET", 0],
["1949-04-03T02:00:00+00:00", "03:00:00", "WEST", -60],
["1949-10-02T01:59:59+00:00", "02:59:59", "WEST", -60],
["1949-10-02T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1951" : helpers.makeTestYear("Portugal", [
["1951-04-01T01:59:59+00:00", "01:59:59", "WET", 0],
["1951-04-01T02:00:00+00:00", "03:00:00", "WEST", -60],
["1951-10-07T01:59:59+00:00", "02:59:59", "WEST", -60],
["1951-10-07T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1952" : helpers.makeTestYear("Portugal", [
["1952-04-06T01:59:59+00:00", "01:59:59", "WET", 0],
["1952-04-06T02:00:00+00:00", "03:00:00", "WEST", -60],
["1952-10-05T01:59:59+00:00", "02:59:59", "WEST", -60],
["1952-10-05T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1953" : helpers.makeTestYear("Portugal", [
["1953-04-05T01:59:59+00:00", "01:59:59", "WET", 0],
["1953-04-05T02:00:00+00:00", "03:00:00", "WEST", -60],
["1953-10-04T01:59:59+00:00", "02:59:59", "WEST", -60],
["1953-10-04T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1954" : helpers.makeTestYear("Portugal", [
["1954-04-04T01:59:59+00:00", "01:59:59", "WET", 0],
["1954-04-04T02:00:00+00:00", "03:00:00", "WEST", -60],
["1954-10-03T01:59:59+00:00", "02:59:59", "WEST", -60],
["1954-10-03T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1955" : helpers.makeTestYear("Portugal", [
["1955-04-03T01:59:59+00:00", "01:59:59", "WET", 0],
["1955-04-03T02:00:00+00:00", "03:00:00", "WEST", -60],
["1955-10-02T01:59:59+00:00", "02:59:59", "WEST", -60],
["1955-10-02T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1956" : helpers.makeTestYear("Portugal", [
["1956-04-01T01:59:59+00:00", "01:59:59", "WET", 0],
["1956-04-01T02:00:00+00:00", "03:00:00", "WEST", -60],
["1956-10-07T01:59:59+00:00", "02:59:59", "WEST", -60],
["1956-10-07T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1957" : helpers.makeTestYear("Portugal", [
["1957-04-07T01:59:59+00:00", "01:59:59", "WET", 0],
["1957-04-07T02:00:00+00:00", "03:00:00", "WEST", -60],
["1957-10-06T01:59:59+00:00", "02:59:59", "WEST", -60],
["1957-10-06T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1958" : helpers.makeTestYear("Portugal", [
["1958-04-06T01:59:59+00:00", "01:59:59", "WET", 0],
["1958-04-06T02:00:00+00:00", "03:00:00", "WEST", -60],
["1958-10-05T01:59:59+00:00", "02:59:59", "WEST", -60],
["1958-10-05T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1959" : helpers.makeTestYear("Portugal", [
["1959-04-05T01:59:59+00:00", "01:59:59", "WET", 0],
["1959-04-05T02:00:00+00:00", "03:00:00", "WEST", -60],
["1959-10-04T01:59:59+00:00", "02:59:59", "WEST", -60],
["1959-10-04T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1960" : helpers.makeTestYear("Portugal", [
["1960-04-03T01:59:59+00:00", "01:59:59", "WET", 0],
["1960-04-03T02:00:00+00:00", "03:00:00", "WEST", -60],
["1960-10-02T01:59:59+00:00", "02:59:59", "WEST", -60],
["1960-10-02T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1961" : helpers.makeTestYear("Portugal", [
["1961-04-02T01:59:59+00:00", "01:59:59", "WET", 0],
["1961-04-02T02:00:00+00:00", "03:00:00", "WEST", -60],
["1961-10-01T01:59:59+00:00", "02:59:59", "WEST", -60],
["1961-10-01T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1962" : helpers.makeTestYear("Portugal", [
["1962-04-01T01:59:59+00:00", "01:59:59", "WET", 0],
["1962-04-01T02:00:00+00:00", "03:00:00", "WEST", -60],
["1962-10-07T01:59:59+00:00", "02:59:59", "WEST", -60],
["1962-10-07T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1963" : helpers.makeTestYear("Portugal", [
["1963-04-07T01:59:59+00:00", "01:59:59", "WET", 0],
["1963-04-07T02:00:00+00:00", "03:00:00", "WEST", -60],
["1963-10-06T01:59:59+00:00", "02:59:59", "WEST", -60],
["1963-10-06T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1964" : helpers.makeTestYear("Portugal", [
["1964-04-05T01:59:59+00:00", "01:59:59", "WET", 0],
["1964-04-05T02:00:00+00:00", "03:00:00", "WEST", -60],
["1964-10-04T01:59:59+00:00", "02:59:59", "WEST", -60],
["1964-10-04T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1965" : helpers.makeTestYear("Portugal", [
["1965-04-04T01:59:59+00:00", "01:59:59", "WET", 0],
["1965-04-04T02:00:00+00:00", "03:00:00", "WEST", -60],
["1965-10-03T01:59:59+00:00", "02:59:59", "WEST", -60],
["1965-10-03T02:00:00+00:00", "02:00:00", "WET", 0]
]),
"1966" : helpers.makeTestYear("Portugal", [
["1966-04-03T01:59:59+00:00", "01:59:59", "WET", 0],
["1966-04-03T02:00:00+00:00", "03:00:00", "CET", -60]
]),
"1976" : helpers.makeTestYear("Portugal", [
["1976-09-25T23:59:59+00:00", "00:59:59", "CET", -60],
["1976-09-26T00:00:00+00:00", "00:00:00", "WET", 0]
]),
"1977" : helpers.makeTestYear("Portugal", [
["1977-03-26T23:59:59+00:00", "23:59:59", "WET", 0],
["1977-03-27T00:00:00+00:00", "01:00:00", "WEST", -60],
["1977-09-24T23:59:59+00:00", "00:59:59", "WEST", -60],
["1977-09-25T00:00:00+00:00", "00:00:00", "WET", 0]
]),
"1978" : helpers.makeTestYear("Portugal", [
["1978-04-01T23:59:59+00:00", "23:59:59", "WET", 0],
["1978-04-02T00:00:00+00:00", "01:00:00", "WEST", -60],
["1978-09-30T23:59:59+00:00", "00:59:59", "WEST", -60],
["1978-10-01T00:00:00+00:00", "00:00:00", "WET", 0]
]),
"1979" : helpers.makeTestYear("Portugal", [
["1979-03-31T23:59:59+00:00", "23:59:59", "WET", 0],
["1979-04-01T00:00:00+00:00", "01:00:00", "WEST", -60],
["1979-09-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["1979-09-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1980" : helpers.makeTestYear("Portugal", [
["1980-03-29T23:59:59+00:00", "23:59:59", "WET", 0],
["1980-03-30T00:00:00+00:00", "01:00:00", "WEST", -60],
["1980-09-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["1980-09-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1981" : helpers.makeTestYear("Portugal", [
["1981-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["1981-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["1981-09-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["1981-09-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1982" : helpers.makeTestYear("Portugal", [
["1982-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["1982-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["1982-09-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["1982-09-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1983" : helpers.makeTestYear("Portugal", [
["1983-03-27T01:59:59+00:00", "01:59:59", "WET", 0],
["1983-03-27T02:00:00+00:00", "03:00:00", "WEST", -60],
["1983-09-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["1983-09-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1984" : helpers.makeTestYear("Portugal", [
["1984-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["1984-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["1984-09-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["1984-09-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1985" : helpers.makeTestYear("Portugal", [
["1985-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["1985-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["1985-09-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["1985-09-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1986" : helpers.makeTestYear("Portugal", [
["1986-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["1986-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["1986-09-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["1986-09-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1987" : helpers.makeTestYear("Portugal", [
["1987-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["1987-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["1987-09-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["1987-09-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1988" : helpers.makeTestYear("Portugal", [
["1988-03-27T00:59:59+00:00", "00:59:59", "WET", 0],
["1988-03-27T01:00:00+00:00", "02:00:00", "WEST", -60],
["1988-09-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["1988-09-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1989" : helpers.makeTestYear("Portugal", [
["1989-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["1989-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["1989-09-24T00:59:59+00:00", "01:59:59", "WEST", -60],
["1989-09-24T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1990" : helpers.makeTestYear("Portugal", [
["1990-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["1990-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["1990-09-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["1990-09-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1991" : helpers.makeTestYear("Portugal", [
["1991-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["1991-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["1991-09-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["1991-09-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1992" : helpers.makeTestYear("Portugal", [
["1992-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["1992-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["1992-09-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["1992-09-27T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1993" : helpers.makeTestYear("Portugal", [
["1993-03-28T00:59:59+00:00", "01:59:59", "CET", -60],
["1993-03-28T01:00:00+00:00", "03:00:00", "CEST", -120],
["1993-09-26T00:59:59+00:00", "02:59:59", "CEST", -120],
["1993-09-26T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1994" : helpers.makeTestYear("Portugal", [
["1994-03-27T00:59:59+00:00", "01:59:59", "CET", -60],
["1994-03-27T01:00:00+00:00", "03:00:00", "CEST", -120],
["1994-09-25T00:59:59+00:00", "02:59:59", "CEST", -120],
["1994-09-25T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1995" : helpers.makeTestYear("Portugal", [
["1995-03-26T00:59:59+00:00", "01:59:59", "CET", -60],
["1995-03-26T01:00:00+00:00", "03:00:00", "CEST", -120],
["1995-09-24T00:59:59+00:00", "02:59:59", "CEST", -120],
["1995-09-24T01:00:00+00:00", "02:00:00", "CET", -60]
]),
"1996" : helpers.makeTestYear("Portugal", [
["1996-03-31T00:59:59+00:00", "01:59:59", "CET", -60],
["1996-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["1996-10-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["1996-10-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1997" : helpers.makeTestYear("Portugal", [
["1997-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["1997-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["1997-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["1997-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1998" : helpers.makeTestYear("Portugal", [
["1998-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["1998-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["1998-10-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["1998-10-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"1999" : helpers.makeTestYear("Portugal", [
["1999-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["1999-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["1999-10-31T00:59:59+00:00", "01:59:59", "WEST", -60],
["1999-10-31T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2000" : helpers.makeTestYear("Portugal", [
["2000-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["2000-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["2000-10-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["2000-10-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2001" : helpers.makeTestYear("Portugal", [
["2001-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["2001-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["2001-10-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["2001-10-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2002" : helpers.makeTestYear("Portugal", [
["2002-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["2002-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["2002-10-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["2002-10-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2003" : helpers.makeTestYear("Portugal", [
["2003-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["2003-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["2003-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["2003-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2004" : helpers.makeTestYear("Portugal", [
["2004-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["2004-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["2004-10-31T00:59:59+00:00", "01:59:59", "WEST", -60],
["2004-10-31T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2005" : helpers.makeTestYear("Portugal", [
["2005-03-27T00:59:59+00:00", "00:59:59", "WET", 0],
["2005-03-27T01:00:00+00:00", "02:00:00", "WEST", -60],
["2005-10-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["2005-10-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2006" : helpers.makeTestYear("Portugal", [
["2006-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["2006-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["2006-10-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["2006-10-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2007" : helpers.makeTestYear("Portugal", [
["2007-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["2007-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["2007-10-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["2007-10-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2008" : helpers.makeTestYear("Portugal", [
["2008-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["2008-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["2008-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["2008-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2009" : helpers.makeTestYear("Portugal", [
["2009-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["2009-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["2009-10-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["2009-10-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2010" : helpers.makeTestYear("Portugal", [
["2010-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["2010-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["2010-10-31T00:59:59+00:00", "01:59:59", "WEST", -60],
["2010-10-31T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2011" : helpers.makeTestYear("Portugal", [
["2011-03-27T00:59:59+00:00", "00:59:59", "WET", 0],
["2011-03-27T01:00:00+00:00", "02:00:00", "WEST", -60],
["2011-10-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["2011-10-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2012" : helpers.makeTestYear("Portugal", [
["2012-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["2012-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["2012-10-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["2012-10-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2013" : helpers.makeTestYear("Portugal", [
["2013-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["2013-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["2013-10-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["2013-10-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2014" : helpers.makeTestYear("Portugal", [
["2014-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["2014-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["2014-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["2014-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2015" : helpers.makeTestYear("Portugal", [
["2015-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["2015-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["2015-10-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["2015-10-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2016" : helpers.makeTestYear("Portugal", [
["2016-03-27T00:59:59+00:00", "00:59:59", "WET", 0],
["2016-03-27T01:00:00+00:00", "02:00:00", "WEST", -60],
["2016-10-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["2016-10-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2017" : helpers.makeTestYear("Portugal", [
["2017-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["2017-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["2017-10-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["2017-10-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2018" : helpers.makeTestYear("Portugal", [
["2018-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["2018-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["2018-10-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["2018-10-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2019" : helpers.makeTestYear("Portugal", [
["2019-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["2019-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["2019-10-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["2019-10-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2020" : helpers.makeTestYear("Portugal", [
["2020-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["2020-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["2020-10-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["2020-10-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2021" : helpers.makeTestYear("Portugal", [
["2021-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["2021-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["2021-10-31T00:59:59+00:00", "01:59:59", "WEST", -60],
["2021-10-31T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2022" : helpers.makeTestYear("Portugal", [
["2022-03-27T00:59:59+00:00", "00:59:59", "WET", 0],
["2022-03-27T01:00:00+00:00", "02:00:00", "WEST", -60],
["2022-10-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["2022-10-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2023" : helpers.makeTestYear("Portugal", [
["2023-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["2023-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["2023-10-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["2023-10-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2024" : helpers.makeTestYear("Portugal", [
["2024-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["2024-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["2024-10-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["2024-10-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2025" : helpers.makeTestYear("Portugal", [
["2025-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["2025-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["2025-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["2025-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2026" : helpers.makeTestYear("Portugal", [
["2026-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["2026-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["2026-10-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["2026-10-25T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2027" : helpers.makeTestYear("Portugal", [
["2027-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["2027-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["2027-10-31T00:59:59+00:00", "01:59:59", "WEST", -60],
["2027-10-31T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2028" : helpers.makeTestYear("Portugal", [
["2028-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["2028-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["2028-10-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["2028-10-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2029" : helpers.makeTestYear("Portugal", [
["2029-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["2029-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["2029-10-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["2029-10-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2030" : helpers.makeTestYear("Portugal", [
["2030-03-31T00:59:59+00:00", "00:59:59", "WET", 0],
["2030-03-31T01:00:00+00:00", "02:00:00", "WEST", -60],
["2030-10-27T00:59:59+00:00", "01:59:59", "WEST", -60],
["2030-10-27T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2031" : helpers.makeTestYear("Portugal", [
["2031-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["2031-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["2031-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["2031-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2032" : helpers.makeTestYear("Portugal", [
["2032-03-28T00:59:59+00:00", "00:59:59", "WET", 0],
["2032-03-28T01:00:00+00:00", "02:00:00", "WEST", -60],
["2032-10-31T00:59:59+00:00", "01:59:59", "WEST", -60],
["2032-10-31T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2033" : helpers.makeTestYear("Portugal", [
["2033-03-27T00:59:59+00:00", "00:59:59", "WET", 0],
["2033-03-27T01:00:00+00:00", "02:00:00", "WEST", -60],
["2033-10-30T00:59:59+00:00", "01:59:59", "WEST", -60],
["2033-10-30T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2034" : helpers.makeTestYear("Portugal", [
["2034-03-26T00:59:59+00:00", "00:59:59", "WET", 0],
["2034-03-26T01:00:00+00:00", "02:00:00", "WEST", -60],
["2034-10-29T00:59:59+00:00", "01:59:59", "WEST", -60],
["2034-10-29T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2035" : helpers.makeTestYear("Portugal", [
["2035-03-25T00:59:59+00:00", "00:59:59", "WET", 0],
["2035-03-25T01:00:00+00:00", "02:00:00", "WEST", -60],
["2035-10-28T00:59:59+00:00", "01:59:59", "WEST", -60],
["2035-10-28T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2036" : helpers.makeTestYear("Portugal", [
["2036-03-30T00:59:59+00:00", "00:59:59", "WET", 0],
["2036-03-30T01:00:00+00:00", "02:00:00", "WEST", -60],
["2036-10-26T00:59:59+00:00", "01:59:59", "WEST", -60],
["2036-10-26T01:00:00+00:00", "01:00:00", "WET", 0]
]),
"2037" : helpers.makeTestYear("Portugal", [
["2037-03-29T00:59:59+00:00", "00:59:59", "WET", 0],
["2037-03-29T01:00:00+00:00", "02:00:00", "WEST", -60],
["2037-10-25T00:59:59+00:00", "01:59:59", "WEST", -60],
["2037-10-25T01:00:00+00:00", "01:00:00", "WET", 0]
])
}; |
import eases from 'eases';
import { IDLE, OVER, SELECTED } from './LikeButtonF1States';
export default function transitions() {
return [
{
from: IDLE,
to: OVER,
animation: {
duration: 0.25,
ease: eases.backOut,
},
},
{
from: OVER,
to: IDLE,
animation: {
duration: 0.25,
ease: eases.expoOut,
},
},
{
from: OVER,
to: SELECTED,
bi: true,
animation: {
duration: 0.5,
ease: eases.expoIn,
},
},
{
from: IDLE,
to: SELECTED,
bi: true,
animation: {
duration: 0.5,
ease: eases.expoIn,
},
},
];
}
|
'use strict';
var object = require('../utils/object');
var string = require('../utils/string');
function factory (type, config, load, typed) {
var parser = load(require('./function/parser'))();
/**
* Documentation object
* @param {Object} doc Object containing properties:
* {string} name
* {string} category
* {string} description
* {string[]} syntax
* {string[]} examples
* {string[]} seealso
* @constructor
*/
function Help(doc) {
if (!(this instanceof Help)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
if (!doc) throw new Error('Argument "doc" missing');
this.doc = doc;
}
/**
* Attach type information
*/
Help.prototype.type = 'Help';
Help.prototype.isHelp = true;
/**
* Generate a string representation of the Help object
* @return {string} Returns a string
* @private
*/
Help.prototype.toString = function () {
var doc = this.doc || {};
var desc = '\n';
if (doc.name) {
desc += 'Name: ' + doc.name + '\n\n';
}
if (doc.category) {
desc += 'Category: ' + doc.category + '\n\n';
}
if (doc.description) {
desc += 'Description:\n ' + doc.description + '\n\n';
}
if (doc.syntax) {
desc += 'Syntax:\n ' + doc.syntax.join('\n ') + '\n\n';
}
if (doc.examples) {
desc += 'Examples:\n';
for (var i = 0; i < doc.examples.length; i++) {
var expr = doc.examples[i];
desc += ' ' + expr + '\n';
var res;
try {
res = parser.eval(expr);
}
catch (e) {
res = e;
}
if (res && !type.isHelp(res)) {
desc += ' ' + string.format(res, {precision: 14}) + '\n';
}
}
desc += '\n';
}
if (doc.seealso) {
desc += 'See also: ' + doc.seealso.join(', ') + '\n';
}
return desc;
};
/**
* Export the help object to JSON
*/
Help.prototype.toJSON = function () {
var obj = object.clone(this.doc);
obj.mathjs = 'Help';
return obj;
};
/**
* Instantiate a Help object from a JSON object
* @param {Object} json
* @returns {Help} Returns a new Help object
*/
Help.fromJSON = function (json) {
var doc = {};
for (var prop in json) {
if (prop !== 'mathjs') { // ignore mathjs field
doc[prop] = json[prop];
}
}
return new Help(doc);
};
/**
* Returns a string representation of the Help object
*/
Help.prototype.valueOf = Help.prototype.toString;
return Help;
}
exports.name = 'Help';
exports.path = 'type';
exports.factory = factory;
|
/* global editor */
/* global caselaw */
/* global _ */
/* global CKEDITOR */
/* global $ */
/* global moment */
/* global console */
(function() {
"use strict";
var pluginName = 'basic';
CKEDITOR.plugins.add(pluginName, {
init: function(editor) {
var formats = [{
label: "Bold",
command: "bold",
element: "strong"
},
{
label: "Italic",
command: "italic",
element: "em"
},
{
label: "Underline",
command: "underline",
element: "u"
},
{
label: "Subscript",
command: "subscript",
element: "sub"
},
{
label: "Superscript",
command: "superscript",
element: "sup"
},
{
label: "Strikethrough",
command: "strike",
element: "s"
}];
if (typeof editor.config.displayButtons !== "undefined") {
$("#tools button").hide();
_.each(editor.config.displayButtons.split(","), function(button){
$("[rel='" + button.trim() + "']").show();
});
}
for (var i = 0; i < formats.length; i++) {
var format = formats[i];
var style = new CKEDITOR.style({
element: format.element,
attributes: format.attributes
});
var stateChange = function(format) {
var styleCommand = function(style) {
this.style = style;
this.allowedContent = style;
this.requiredContent = style;
this.contextSensitive = true;
};
styleCommand.prototype = {
exec: function(editor) {
editor.focus();
if (this.state === CKEDITOR.TRISTATE_OFF) {
editor.applyStyle(this.style);
} else if (this.state === CKEDITOR.TRISTATE_ON) {
editor.removeStyle(this.style);
}
if (format.command !== 'fakecommand') {
editor.execCommand('fakecommand');
editor.execCommand('fakecommand');
} /* hack to change button state properly */
// force the save button activation and dirty state set to true
editor.fire('change');
},
refresh: function(editor,path) {
this.setState(
path && this.style.checkApplicable(path) ? (this.style.checkActive(path)?CKEDITOR.TRISTATE_ON:CKEDITOR.TRISTATE_OFF):CKEDITOR.TRISTATE_DISABLED
);
}
};
editor.addCommand(
format.command,
new styleCommand(style) //jshint ignore:line
);
var f = format;
return function () {
editor.attachStyleStateChange(style, function(state) {
if (!editor.readOnly) {
editor.getCommand(f.command).setState(state);
}
try {
switch (editor.getCommand(f.command).state) {
case CKEDITOR.TRISTATE_DISABLED:
// $("[rel='" + editor.getCommand(f.command).name + "']").addClass("disabled");
break;
case CKEDITOR.TRISTATE_OFF:
$("[rel='" + editor.getCommand(f.command).name + "']").removeClass("disabled");
$("[rel='" + editor.getCommand(f.command).name + "']").removeClass("active");
break;
default:
$("[rel='" + editor.getCommand(f.command).name + "']").addClass("active");
break;
}
} catch(e) {
console.log(editor.getCommand(f.command).name);
console.log(e);
}
});
};
};
stateChange(format)();
}
}
});
})();
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'it', {
title: 'Istruzioni di Accessibilità',
contents: 'Contenuti di Aiuto. Per chiudere questa finestra premi ESC.',
legend: [
{
name: 'Generale',
items: [
{
name: 'Barra degli strumenti Editor',
legend: 'Premere ${toolbarFocus} per passare alla barra degli strumenti. Usare TAB per spostarsi al gruppo successivo, MAIUSC+TAB per spostarsi a quello precedente. Usare FRECCIA DESTRA per spostarsi al pulsante successivo, FRECCIA SINISTRA per spostarsi a quello precedente. Premere SPAZIO o INVIO per attivare il pulsante della barra degli strumenti.'
},
{
name: 'Finestra Editor',
legend:
'All\'interno di una finestra di dialogo è possibile premere TAB per passare all\'elemento successivo della finestra, MAIUSC+TAB per passare a quello precedente; premere INVIO per inviare i dati della finestra, oppure ESC per annullare l\'operazione. Quando una finestra di dialogo ha più schede, è possibile passare all\'elenco delle schede sia con ALT+F10 che con TAB, in base all\'ordine delle tabulazioni della finestra. Quando l\'elenco delle schede è attivo, premere la FRECCIA DESTRA o la FRECCIA SINISTRA per passare rispettivamente alla scheda successiva o a quella precedente.'
},
{
name: 'Menù contestuale Editor',
legend: 'Premi ${contextMenu} o TASTO APPLICAZIONE per aprire il menu contestuale. Dunque muoviti all\'opzione successiva del menu con il tasto TAB o con la Freccia Sotto. Muoviti all\'opzione precedente con MAIUSC+TAB o con Freccia Sopra. Premi SPAZIO o INVIO per scegliere l\'opzione di menu. Apri il sottomenu dell\'opzione corrente con SPAZIO o INVIO oppure con la Freccia Destra. Torna indietro al menu superiore con ESC oppure Freccia Sinistra. Chiudi il menu contestuale con ESC.'
},
{
name: 'Box Lista Editor',
legend: 'All\'interno di un elenco di opzioni, per spostarsi all\'elemento successivo premere TAB oppure FRECCIA GIÙ. Per spostarsi all\'elemento precedente usare SHIFT+TAB oppure FRECCIA SU. Premere SPAZIO o INVIO per selezionare l\'elemento della lista. Premere ESC per chiudere l\'elenco di opzioni.'
},
{
name: 'Barra percorso elementi editor',
legend: 'Premere ${elementsPathFocus} per passare agli elementi della barra del percorso. Usare TAB o FRECCIA DESTRA per passare al pulsante successivo. Per passare al pulsante precedente premere MAIUSC+TAB o FRECCIA SINISTRA. Premere SPAZIO o INVIO per selezionare l\'elemento nell\'editor.'
}
]
},
{
name: 'Comandi',
items: [
{
name: ' Annulla comando',
legend: 'Premi ${undo}'
},
{
name: ' Ripeti comando',
legend: 'Premi ${redo}'
},
{
name: ' Comando Grassetto',
legend: 'Premi ${bold}'
},
{
name: ' Comando Corsivo',
legend: 'Premi ${italic}'
},
{
name: ' Comando Sottolineato',
legend: 'Premi ${underline}'
},
{
name: ' Comando Link',
legend: 'Premi ${link}'
},
{
name: ' Comando riduci barra degli strumenti',
legend: 'Premi ${toolbarCollapse}'
},
{
name: 'Comando di accesso al precedente spazio di focus',
legend: 'Premi ${accessPreviousSpace} per accedere il più vicino spazio di focus non raggiungibile prima del simbolo caret, per esempio due elementi HR adiacenti. Ripeti la combinazione di tasti per raggiungere spazi di focus distanti.'
},
{
name: 'Comando di accesso al prossimo spazio di focus',
legend: 'Premi ${accessNextSpace} per accedere il più vicino spazio di focus non raggiungibile dopo il simbolo caret, per esempio due elementi HR adiacenti. Ripeti la combinazione di tasti per raggiungere spazi di focus distanti.'
},
{
name: ' Aiuto Accessibilità',
legend: 'Premi ${a11yHelp}'
}
]
}
],
backspace: 'Backspace',
tab: 'Tab',
enter: 'Invio',
shift: 'Maiusc',
ctrl: 'Ctrl',
alt: 'Alt',
pause: 'Pausa',
capslock: 'Bloc Maiusc',
escape: 'Esc',
pageUp: 'Pagina sù',
pageDown: 'Pagina giù',
end: 'Fine',
home: 'Inizio',
leftArrow: 'Freccia sinistra',
upArrow: 'Freccia su',
rightArrow: 'Freccia destra',
downArrow: 'Freccia giù',
insert: 'Ins',
'delete': 'Canc',
leftWindowKey: 'Tasto di Windows sinistro',
rightWindowKey: 'Tasto di Windows destro',
selectKey: 'Tasto di selezione',
numpad0: '0 sul tastierino numerico',
numpad1: '1 sul tastierino numerico',
numpad2: '2 sul tastierino numerico',
numpad3: '3 sul tastierino numerico',
numpad4: '4 sul tastierino numerico',
numpad5: '5 sul tastierino numerico',
numpad6: '6 sul tastierino numerico',
numpad7: '7 sul tastierino numerico',
numpad8: '8 sul tastierino numerico',
numpad9: '9 sul tastierino numerico',
multiply: 'Moltiplicazione',
add: 'Più',
subtract: 'Sottrazione',
decimalPoint: 'Punto decimale',
divide: 'Divisione',
f1: 'F1',
f2: 'F2',
f3: 'F3',
f4: 'F4',
f5: 'F5',
f6: 'F6',
f7: 'F7',
f8: 'F8',
f9: 'F9',
f10: 'F10',
f11: 'F11',
f12: 'F12',
numLock: 'Bloc Num',
scrollLock: 'Bloc Scorr',
semiColon: 'Punto-e-virgola',
equalSign: 'Segno di uguale',
comma: 'Virgola',
dash: 'Trattino',
period: 'Punto',
forwardSlash: 'Barra',
graveAccent: 'Accento grave',
openBracket: 'Parentesi quadra aperta',
backSlash: 'Barra rovesciata',
closeBracket: 'Parentesi quadra chiusa',
singleQuote: 'Apostrofo'
} );
|
'use strict';
const parser = require('./../index');
function fromJson(jsonText) {
return parser.fromJson(jsonText, [
require('./nameParser')
])
}
module.exports = { fromJson }; |
'use strict';
// Production specific configuration
// =================================
module.exports = {
// Server IP
ip: process.env.OPENSHIFT_NODEJS_IP ||
process.env.IP ||
undefined,
// Server port
port: process.env.OPENSHIFT_NODEJS_PORT ||
process.env.PORT ||
9000,
// MongoDB connection options
mongo: {
uri: process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME ||
'mongodb://localhost/athena-manage'
},
staticPath: '/public/',
};
|
/* eslint no-param-reassign: "off" */
import { getDocument } from 'ssr-window';
import { bindMethods } from '../../shared/utils';
import { getSupport } from '../../shared/get-support';
import { getDevice } from '../../shared/get-device';
import $ from '../../shared/dom7';
const CardExpandable = {
open(cardEl = '.card-expandable', animate = true) {
const app = this;
const device = getDevice();
const document = getDocument();
const support = getSupport();
const $cardEl = $(cardEl).eq(0);
if (!$cardEl || !$cardEl.length) return;
if (
$cardEl.hasClass('card-opened') ||
$cardEl.hasClass('card-opening') ||
$cardEl.hasClass('card-closing')
)
return;
const $pageEl = $cardEl.parents('.page').eq(0);
if (!$pageEl.length) return;
if ($pageEl.find('.card-opened').length) {
return;
}
let prevented;
function prevent() {
prevented = true;
}
$cardEl.trigger('card:beforeopen', { prevent });
app.emit('cardBeforeOpen', $cardEl[0], prevent);
if (prevented) return;
const cardParams = Object.assign({ animate }, app.params.card, $cardEl.dataset());
const $pageContentEl = $cardEl.parents('.page-content');
let $backdropEl;
if ($cardEl.attr('data-backdrop-el')) {
$backdropEl = $($cardEl.attr('data-backdrop-el'));
}
if (!$backdropEl && cardParams.backdrop) {
$backdropEl = $pageContentEl.find('.card-backdrop');
if (!$backdropEl.length) {
$backdropEl = $('<div class="card-backdrop"></div>');
$pageContentEl.append($backdropEl);
}
}
let $navbarEl;
let $toolbarEl;
if (cardParams.hideNavbarOnOpen) {
$navbarEl = $pageEl.children('.navbar');
if (!$navbarEl.length) {
if ($pageEl[0].f7Page) $navbarEl = $pageEl[0].f7Page.$navbarEl;
}
}
if (cardParams.hideToolbarOnOpen) {
$toolbarEl = $pageEl.children('.toolbar');
if (!$toolbarEl.length) {
$toolbarEl = $pageEl.parents('.view').children('.toolbar');
}
if (!$toolbarEl.length) {
$toolbarEl = $pageEl.parents('.views').children('.toolbar');
}
}
const currTransform = $cardEl.css('transform');
let hasTransform;
if (currTransform && currTransform.match(/[2-9]/)) {
hasTransform = true;
}
const $cardContentEl = $cardEl.children('.card-content');
const $cardSizeEl = $(document.createElement('div')).addClass('card-expandable-size');
$cardEl.append($cardSizeEl);
let cardWidth = $cardEl[0].offsetWidth;
let cardHeight = $cardEl[0].offsetHeight;
let pageWidth = $pageEl[0].offsetWidth;
let pageHeight = $pageEl[0].offsetHeight;
let maxWidth = $cardSizeEl[0].offsetWidth || pageWidth;
let maxHeight = $cardSizeEl[0].offsetHeight || pageHeight;
let statusbarHeight;
if ($navbarEl && !cardParams.hideStatusbarOnOpen && maxHeight === pageHeight) {
statusbarHeight = parseInt($navbarEl.css('--f7-safe-area-top'), 10);
if (Number.isNaN(statusbarHeight)) statusbarHeight = 0;
}
if (statusbarHeight) {
maxHeight -= statusbarHeight;
}
let scaleX = maxWidth / cardWidth;
let scaleY = maxHeight / cardHeight;
let offset = $cardEl.offset();
let pageOffset = $pageEl.offset();
if (statusbarHeight) {
pageOffset.top += statusbarHeight / 2;
}
offset.left -= pageOffset.left;
let cardLeftOffset;
let cardTopOffset;
if (hasTransform) {
const transformValues = currTransform
.replace(/matrix\(|\)/g, '')
.split(',')
.map((el) => el.trim());
if (transformValues && transformValues.length > 1) {
const scale = parseFloat(transformValues[0]);
cardLeftOffset = offset.left - (cardWidth * (1 - scale)) / 2;
cardTopOffset = offset.top - pageOffset.top - (cardHeight * (1 - scale)) / 2;
if (app.rtl) cardLeftOffset -= $cardEl[0].scrollLeft;
} else {
cardLeftOffset = $cardEl[0].offsetLeft;
cardTopOffset =
$cardEl[0].offsetTop - ($pageContentEl.length ? $pageContentEl[0].scrollTop : 0);
}
} else {
cardLeftOffset = offset.left;
cardTopOffset = offset.top - pageOffset.top;
if (app.rtl) cardLeftOffset -= $cardEl[0].scrollLeft;
}
cardLeftOffset -= (pageWidth - maxWidth) / 2;
cardTopOffset -= (pageHeight - maxHeight) / 2;
let cardRightOffset = maxWidth - cardWidth - cardLeftOffset;
if (app.rtl) {
[cardLeftOffset, cardRightOffset] = [cardRightOffset, cardLeftOffset];
}
let cardBottomOffset = maxHeight - cardHeight - cardTopOffset;
let translateX = (cardRightOffset - cardLeftOffset) / 2;
let translateY = (cardBottomOffset - cardTopOffset) / 2;
if (cardParams.hideNavbarOnOpen && $navbarEl && $navbarEl.length) {
if ($navbarEl.closest('.navbar-hidden').length) {
// Was hidden
$cardEl[0].f7KeepNavbarOnClose = true;
} else {
delete $cardEl[0].f7KeepNavbarOnClose;
app.navbar.hide($navbarEl, cardParams.animate, cardParams.hideStatusbarOnOpen, true);
}
}
if (cardParams.hideToolbarOnOpen && $toolbarEl && $toolbarEl.length) {
if ($toolbarEl.closest('.toolbar-hidden').length) {
// Was hidden
$cardEl[0].f7KeepToolbarOnClose = true;
} else {
delete $cardEl[0].f7KeepToolbarOnClose;
app.toolbar.hide($toolbarEl, cardParams.animate);
}
}
if ($backdropEl) {
$backdropEl.removeClass('card-backdrop-out').addClass('card-backdrop-in');
}
$cardEl.removeClass('card-transitioning');
if (cardParams.animate) {
$cardEl.addClass('card-opening');
}
$cardEl.trigger('card:open');
app.emit('cardOpen', $cardEl[0]);
function transitionEnd() {
$pageEl.addClass('page-with-card-opened');
if (device.ios && $pageContentEl.length) {
$pageContentEl.css('height', `${$pageContentEl[0].offsetHeight + 1}px`);
setTimeout(() => {
$pageContentEl.css('height', '');
});
}
$cardEl.addClass('card-opened');
$cardEl.removeClass('card-opening');
$cardEl.trigger('card:opened');
app.emit('cardOpened', $cardEl[0], $pageEl[0]);
}
$cardContentEl
.css({
width: `${maxWidth}px`,
height: `${maxHeight}px`,
})
.transform(
`translate3d(${
app.rtl ? cardLeftOffset + translateX : -cardLeftOffset - translateX
}px, 0px, 0) scale(${1 / scaleX}, ${1 / scaleY})`,
);
$cardEl.transform(
`translate3d(${
app.rtl ? -translateX : translateX
}px, ${translateY}px, 0) scale(${scaleX}, ${scaleY})`,
);
if (cardParams.animate) {
$cardEl.transitionEnd(() => {
transitionEnd();
});
} else {
transitionEnd();
}
function onResize() {
$cardEl.removeClass('card-transitioning');
cardWidth = $cardEl[0].offsetWidth;
cardHeight = $cardEl[0].offsetHeight;
pageWidth = $pageEl[0].offsetWidth;
pageHeight = $pageEl[0].offsetHeight;
maxWidth = $cardSizeEl[0].offsetWidth || pageWidth;
maxHeight = $cardSizeEl[0].offsetHeight || pageHeight;
statusbarHeight = 0;
if ($navbarEl && !cardParams.hideStatusbarOnOpen && maxHeight === pageHeight) {
statusbarHeight = parseInt($navbarEl.css('--f7-safe-area-top'), 10);
if (Number.isNaN(statusbarHeight)) statusbarHeight = 0;
}
if (statusbarHeight) {
maxHeight -= statusbarHeight;
}
scaleX = maxWidth / cardWidth;
scaleY = maxHeight / cardHeight;
$cardEl.transform('translate3d(0px, 0px, 0) scale(1)');
offset = $cardEl.offset();
pageOffset = $pageEl.offset();
if (statusbarHeight) {
pageOffset.top += statusbarHeight / 2;
}
offset.left -= pageOffset.left;
offset.top -= pageOffset.top;
cardLeftOffset = offset.left - (pageWidth - maxWidth) / 2;
if (app.rtl) cardLeftOffset -= $cardEl[0].scrollLeft;
cardTopOffset = offset.top - (pageHeight - maxHeight) / 2;
cardRightOffset = maxWidth - cardWidth - cardLeftOffset;
cardBottomOffset = maxHeight - cardHeight - cardTopOffset;
if (app.rtl) {
[cardLeftOffset, cardRightOffset] = [cardRightOffset, cardLeftOffset];
}
translateX = (cardRightOffset - cardLeftOffset) / 2;
translateY = (cardBottomOffset - cardTopOffset) / 2;
$cardEl.transform(
`translate3d(${
app.rtl ? -translateX : translateX
}px, ${translateY}px, 0) scale(${scaleX}, ${scaleY})`,
);
$cardContentEl
.css({
width: `${maxWidth}px`,
height: `${maxHeight}px`,
})
.transform(
`translate3d(${
app.rtl ? cardLeftOffset + translateX : -cardLeftOffset - translateX
}px, 0px, 0) scale(${1 / scaleX}, ${1 / scaleY})`,
);
}
let cardScrollTop;
let isTouched;
let isMoved;
let touchStartX;
let touchStartY;
let touchEndX;
let touchEndY;
let isScrolling;
let progress;
let isV;
let isH;
let $cardScrollableEl;
function onTouchStart(e) {
if (!$(e.target).closest($cardEl).length) return;
if (!$cardEl.hasClass('card-opened')) return;
$cardScrollableEl = $cardEl.find(cardParams.scrollableEl);
if (
$cardScrollableEl[0] &&
$cardScrollableEl[0] !== $cardContentEl[0] &&
!$cardScrollableEl[0].contains(e.target)
) {
cardScrollTop = 0;
} else {
cardScrollTop = $cardScrollableEl.scrollTop();
}
isTouched = true;
touchStartX = e.targetTouches[0].pageX;
touchStartY = e.targetTouches[0].pageY;
isScrolling = undefined;
isV = false;
isH = false;
}
function onTouchMove(e) {
if (!isTouched) return;
touchEndX = e.targetTouches[0].pageX;
touchEndY = e.targetTouches[0].pageY;
if (typeof isScrolling === 'undefined') {
isScrolling = !!(
isScrolling || Math.abs(touchEndY - touchStartY) > Math.abs(touchEndX - touchStartX)
);
}
if (!isH && !isV) {
if (!isScrolling && e.targetTouches[0].clientX <= 50) {
isH = true;
} else {
isV = true;
}
}
if (!(isH || isV) || (isV && cardScrollTop !== 0)) {
isTouched = true;
isMoved = true;
return;
}
if (!isMoved) {
$cardEl.removeClass('card-transitioning');
}
isMoved = true;
progress = isV
? Math.max((touchEndY - touchStartY) / 150, 0)
: Math.max((touchEndX - touchStartX) / (cardWidth / 2), 0);
if ((progress > 0 && isV) || isH) {
if (isV && device.ios && $cardScrollableEl[0] === $cardContentEl[0]) {
$cardScrollableEl.css('-webkit-overflow-scrolling', 'auto');
$cardScrollableEl.scrollTop(0);
}
e.preventDefault();
}
if (progress > 1) progress **= 0.3;
if (progress > (isV ? 1.3 : 1.1)) {
isTouched = false;
isMoved = false;
app.card.close($cardEl);
} else {
$cardEl.transform(
`translate3d(${app.rtl ? -translateX : translateX}px, ${translateY}px, 0) scale(${
scaleX * (1 - progress * 0.2)
}, ${scaleY * (1 - progress * 0.2)})`,
);
}
}
function onTouchEnd() {
if (!isTouched || !isMoved) return;
isTouched = false;
isMoved = false;
if (device.ios) {
$cardScrollableEl.css('-webkit-overflow-scrolling', '');
}
if (progress >= 0.8) {
app.card.close($cardEl);
} else {
$cardEl
.addClass('card-transitioning')
.transform(
`translate3d(${
app.rtl ? -translateX : translateX
}px, ${translateY}px, 0) scale(${scaleX}, ${scaleY})`,
);
}
}
$cardEl[0].detachEventHandlers = function detachEventHandlers() {
app.off('resize', onResize);
if (support.touch && cardParams.swipeToClose) {
app.off('touchstart:passive', onTouchStart);
app.off('touchmove:active', onTouchMove);
app.off('touchend:passive', onTouchEnd);
}
};
app.on('resize', onResize);
if (support.touch && cardParams.swipeToClose) {
app.on('touchstart:passive', onTouchStart);
app.on('touchmove:active', onTouchMove);
app.on('touchend:passive', onTouchEnd);
}
},
close(cardEl = '.card-expandable.card-opened', animate = true) {
const app = this;
const device = getDevice();
const $cardEl = $(cardEl).eq(0);
if (!$cardEl || !$cardEl.length) return;
if (
!$cardEl.hasClass('card-opened') ||
$cardEl.hasClass('card-opening') ||
$cardEl.hasClass('card-closing')
)
return;
const $cardContentEl = $cardEl.children('.card-content');
const $pageContentEl = $cardEl.parents('.page-content');
const $pageEl = $cardEl.parents('.page').eq(0);
if (!$pageEl.length) return;
const cardParams = Object.assign({ animate }, app.params.card, $cardEl.dataset());
const $cardScrollableEl = $cardEl.find(cardParams.scrollableEl);
let $navbarEl;
let $toolbarEl;
let $backdropEl;
if ($cardEl.attr('data-backdrop-el')) {
$backdropEl = $($cardEl.attr('data-backdrop-el'));
}
if (cardParams.backdrop) {
$backdropEl = $cardEl.parents('.page-content').find('.card-backdrop');
}
if (cardParams.hideNavbarOnOpen) {
$navbarEl = $pageEl.children('.navbar');
if (!$navbarEl.length) {
if ($pageEl[0].f7Page) $navbarEl = $pageEl[0].f7Page.$navbarEl;
}
if ($navbarEl && $navbarEl.length && !$cardEl[0].f7KeepNavbarOnClose) {
app.navbar.show($navbarEl, cardParams.animate, true);
}
}
if (cardParams.hideToolbarOnOpen) {
$toolbarEl = $pageEl.children('.toolbar');
if (!$toolbarEl.length) {
$toolbarEl = $pageEl.parents('.view').children('.toolbar');
}
if (!$toolbarEl.length) {
$toolbarEl = $pageEl.parents('.views').children('.toolbar');
}
if ($toolbarEl && $toolbarEl.length && !$cardEl[0].f7KeepToolbarOnClose) {
app.toolbar.show($toolbarEl, cardParams.animate);
}
}
$pageEl.removeClass('page-with-card-opened');
if (device.ios && $pageContentEl.length) {
$pageContentEl.css('height', `${$pageContentEl[0].offsetHeight + 1}px`);
setTimeout(() => {
$pageContentEl.css('height', '');
});
}
if ($backdropEl && $backdropEl.length) {
$backdropEl.removeClass('card-backdrop-in').addClass('card-backdrop-out');
}
$cardEl.removeClass('card-opened card-transitioning');
if (cardParams.animate) {
$cardEl.addClass('card-closing');
} else {
$cardEl.addClass('card-no-transition');
}
$cardEl.transform('');
$cardEl.trigger('card:close');
app.emit('cardClose', $cardEl[0], $pageEl[0]);
const animateWidth = $cardEl.hasClass('card-expandable-animate-width');
function transitionEnd() {
if (!animateWidth) {
$cardContentEl.css({
width: '',
height: '',
});
}
if ($backdropEl && $backdropEl.length) {
$backdropEl.removeClass('card-backdrop-in card-backdrop-out');
}
$cardEl.removeClass('card-closing card-no-transition');
$cardEl.trigger('card:closed');
$cardEl.find('.card-expandable-size').remove();
app.emit('cardClosed', $cardEl[0], $pageEl[0]);
}
if (animateWidth) {
$cardContentEl.css({
width: '',
height: '',
});
}
$cardContentEl.transform('').scrollTop(0, animate ? 300 : 0);
if ($cardScrollableEl.length && $cardScrollableEl[0] !== $cardContentEl[0]) {
$cardScrollableEl.scrollTop(0, animate ? 300 : 0);
}
if (animate) {
$cardContentEl.transitionEnd(() => {
transitionEnd();
});
} else {
transitionEnd();
}
if ($cardEl[0].detachEventHandlers) {
$cardEl[0].detachEventHandlers();
delete $cardEl[0].detachEventHandlers;
}
},
toggle(cardEl = '.card-expandable', animate) {
const app = this;
const $cardEl = $(cardEl).eq(0);
if (!$cardEl.length) return;
if ($cardEl.hasClass('card-opened')) {
app.card.close($cardEl, animate);
} else {
app.card.open($cardEl, animate);
}
},
};
export default {
name: 'card',
params: {
card: {
hideNavbarOnOpen: true,
hideStatusbarOnOpen: true,
hideToolbarOnOpen: true,
scrollableEl: '.card-content',
swipeToClose: true,
closeByBackdropClick: true,
backdrop: true,
},
},
create() {
const app = this;
bindMethods(app, {
card: CardExpandable,
});
},
on: {
pageBeforeIn(page) {
const app = this;
if (
app.params.card.hideNavbarOnOpen &&
page.navbarEl &&
page.$el.find('.card-opened.card-expandable').length
) {
app.navbar.hide(page.navbarEl, true, app.params.card.hideStatusbarOnOpen, true);
}
if (
app.params.card.hideToolbarOnOpen &&
page.$el.find('.card-opened.card-expandable').length
) {
let $toolbarEl = page.$el.children('.toolbar');
if (!$toolbarEl.length) {
$toolbarEl = page.$el.parents('.view').children('.toolbar');
}
if (!$toolbarEl.length) {
$toolbarEl = page.$el.parents('.views').children('.toolbar');
}
if ($toolbarEl && $toolbarEl.length) {
app.toolbar.hide($toolbarEl);
}
}
},
},
clicks: {
'.card-close': function closeCard($clickedEl, data) {
const app = this;
app.card.close(data.card, data.animate);
},
'.card-open': function closeCard($clickedEl, data) {
const app = this;
app.card.open(data.card, data.animate);
},
'.card-expandable': function toggleExpandableCard($clickedEl, data, e) {
const app = this;
if (
$clickedEl.hasClass('card-opened') ||
$clickedEl.hasClass('card-opening') ||
$clickedEl.hasClass('card-closing')
)
return;
if ($(e.target).closest('.card-prevent-open, .card-close').length) return;
app.card.open($clickedEl);
},
'.card-backdrop-in': function onBackdropClick() {
const app = this;
let needToClose = false;
if (app.params.card.closeByBackdropClick) needToClose = true;
const $openedCardEl = $('.card-opened');
if (!$openedCardEl.length) return;
if ($openedCardEl.attr('data-close-by-backdrop-click') === 'true') {
needToClose = true;
} else if ($openedCardEl.attr('data-close-by-backdrop-click') === 'false') {
needToClose = false;
}
if (needToClose) app.card.close($openedCardEl);
},
},
};
|
/**
* Arrays
* Most of your answers should be stored in variables called q1, q2 etc..
* and the variables printed to the console.
* (i.e) console.log("Question 1" + q1)
*/
/**
* Question 1
* Create an array of image source filenames.
* Use "image1.png", "image2.png", and "image3.png" as the array values.
*/
// Your code here
/**
* Question 2
* Using the array from Question 1, store the first element of the array
* in variable q2.
*/
// Your code here
/**
* Question 3
* Get the length of the first array (number of elements in the array)
* and store it in variable q3
*/
// Your code here
/**
* Question 4
* Using the array from Question 1, store the last element of the array
* in variable q4. Hint: How can we get the number of elements in the array?
*/
// Your code here
// Bonus 1
// Using the array from Question 1, capitalize the first letter of each
// element in the array and store the elments in a new variable bonus1.
// The a final array should look like: ["Image1.png", "Image2.png", and "Image3.png]
// HINTS:
// -using the .split("") method will covert a string of text into an array
// -using the .join("") method wil join the elements back into a string
// -using .toUpperCase() will covert a letter from lower to upper case
// Your code here
//Perform the same action for each item in the array
// ____________________________________________________________________________
/**
* Arrays + Iteration
*/
/**
* Question 5
* Create an array of numbers using 1, 2, 3, and 4 as values.
* Use a for loop, .forEach() or .map() method to increase
* each value by 1. You can either store each new value back in the original
* array, or in a new array -- your choice. The end result should be
* an array of numbers with values 2, 3, 4, and 5.
*/
// Your code here
/**
* Question 6
* Using the array from Question 5, find the average of the numbers in the array
* (average = sum of all numbers/number of numbers). Store the average in q6.
*/
// Your code here
/**
* Question 7
* Loop through the array of ["green","blue","yellow"], and return only the
* color "blue". Store the new array in q8.
*/
// Your code here
/** - BONUS 2
* Using the array of ["a","b","c","a","b"], create a new array which contains
* only unique values from the array provided. Store the new array in bonus2.
* HINTS:
* - the .filter() method can be used to return comparisons that evaluate to true
* - the .reduce() method can also be used to return true evaluations and also create a new array
* - the .indexOf() method can be used to find the first matching value of an element in an array
*/
// Your code here
/** - BONUS 3
* Using the array of [1,2,3,1,2], determine if any one value is the sum of the values
* before and after it's index position. Store the index & index value in bonus3.
* HINTS:
* - a for() loop can be used to iterate through each element in array
* - the .slice() method can be used to disect an array
* - the .reduce() method can be used to sum all the values in an array
*/
|
var fullPrice = $('#fullPrice');
var vipPercent = $('[name^="vipPercent"]');
var vipPrice = $('[name^="vipPrice"]');
fullPrice.on('input' ,function(){
if(isNaN(fullPrice.val())){
$('#fullPriceMsg').html('ข้อมูลไม่ถูกต้อง');
$('#submitBtn').prop('disabled', true);
}else{
$('#fullPriceMsg').html('');
$('#submitBtn').prop('disabled', false);
for (var i=0; i<vipPercent.length ;i++) {
changePrice($('[name^="vipPercent"]')[i]['id']);
}
}
});
$('[name^="vipPercent"]').on('input', function(){
if ( isNaN($(this).val()) ) {
$("#msgPp"+($(this).attr('id').substr(2))).html('ข้อมูลไม่ถูกต้อง');
}else{
$("#msgPp"+($(this).attr('id').substr(2))).html('');
}
changePrice($(this).attr('id'));
});
$('[name^="vipPrice"]').on('input' ,function(){
if ( isNaN($(this).val()) ) {
$("#msgPm"+($(this).attr('id').substr(2))).html('ข้อมูลไม่ถูกต้อง');
}else{
$("#msgPm"+($(this).attr('id').substr(2))).html('');
}
changePercent($(this).attr('id'));
});
console.log("vipPrice count = "+$('[name^="vipPrice"]').length);
/*
$('#submitBtn').click(function (){
for (var i=0;i<vipPrice.length;i++) {
if (vipPrice[i]['value'] != '' && isNaN(vipPrice[i]['value'])) {
alert(vipPrice[i]['value']);
return;
}
}
for (var i=0;i<vipPercent.length;i++) {
if (vipPercent[i]['value'] != '' && isNaN(vipPercent[i]['value'])) {
return;
}
}
$('#productForm').validate(function (){alert('valid');});
});*/
function changePrice(id){
percent = $('#'+id);
price = $('#pm'+id.substr(2));
if (percent.val()=='' || isNaN(percent.val()) || !validFp() ) {
price.val('');
return;
}
$("#msgPp"+id.substr(2)).html('');
fpInt = parseFloat(fullPrice.val());
pInt = parseFloat(percent.val());
newPrice = fpInt-((pInt/100)*fpInt);
//console.log(newPrice);
price.val(newPrice.toFixed(2));
$("#msgPm"+id.substr(2)).html('');
//$('#fullPriceMsg').html(percent.val());
}
function changePercent(id){
percent = $('#pp'+id.substr(2));
price = $('#'+id);
if (price.val()=='' || isNaN(price.val()) || !validFp() ) {
percent.val('');
return;
}
fpInt = parseFloat(fullPrice.val());
pInt = parseFloat(price.val());
newPercent = (fpInt-pInt)/fpInt * 100;
percent.val(newPercent.toFixed(2));
$("#msgPp"+id.substr(2)).html('');
}
function validFp(){
if (isNaN(fullPrice.val()) || fullPrice.val().length==0 || parseInt(fullPrice.val()) <= 0) {
return false;
}
return true;
}
function validField(val){
return val.length == 0
} |
module.exports.plugins = []
module.exports.plugins.push({
register: require('good'),
options: {
opsInterval: 15000,
reporters: [{
reporter: require('good-console'),
events: {log: '*', response: '*', ops: '*', error: '*'}
}]
}
})
|
/**
* @fileOverview 表单验证
* @ignore
*/
var BUI = require('bui-common'),
Rules = require('./rules');
/**
* @class BUI.Form.ValidView
* @private
* 对控件内的字段域进行验证的视图
*/
var ValidView = function(){
};
ValidView.prototype = {
/**
* 获取错误信息的容器
* @protected
* @return {jQuery}
*/
getErrorsContainer : function(){
var _self = this,
errorContainer = _self.get('errorContainer');
if(errorContainer){
if(BUI.isString(errorContainer)){
return _self.get('el').find(errorContainer);
}
return errorContainer;
}
return _self.getContentElement();
},
/**
* 显示错误
*/
showErrors : function(errors){
var _self = this,
errorsContainer = _self.getErrorsContainer(),
errorTpl = _self.get('errorTpl');
_self.clearErrors();
if(!_self.get('showError')){
return ;
}
//如果仅显示第一条错误记录
if(_self.get('showOneError')){
if(errors && errors.length){
_self.showError(errors[0],errorTpl,errorsContainer);
}
return ;
}
BUI.each(errors,function(error){
if(error){
_self.showError(error,errorTpl,errorsContainer);
}
});
},
/**
* 显示一条错误
* @protected
* @template
* @param {String} msg 错误信息
*/
showError : function(msg,errorTpl,container){
},
/**
* @protected
* @template
* 清除错误
*/
clearErrors : function(){
}
};
/**
* 对控件内的字段域进行验证
* @class BUI.Form.Valid
*/
var Valid = function(){
};
Valid.ATTRS = {
/**
* 控件固有的验证规则,例如,日期字段域,有的date类型的验证
* @protected
* @type {Object}
*/
defaultRules : {
value : {}
},
/**
* 控件固有的验证出错信息,例如,日期字段域,不是有效日期的验证字段
* @protected
* @type {Object}
*/
defaultMessages : {
value : {}
},
/**
* 验证规则
* @type {Object}
*/
rules : {
shared : false,
value : {}
},
/**
* 验证信息集合
* @type {Object}
*/
messages : {
shared : false,
value : {}
},
/**
* 验证器 验证容器内的表单字段是否通过验证
* @type {Function}
*/
validator : {
},
/**
* 存放错误信息容器的选择器,如果未提供则默认显示在控件中
* @private
* @type {String}
*/
errorContainer : {
view : true
},
/**
* 显示错误信息的模板
* @type {Object}
*/
errorTpl : {
view : true,
value : '<span class="x-field-error"><span class="x-icon x-icon-mini x-icon-error">!</span><label class="x-field-error-text">{error}</label></span>'
},
/**
* 显示错误
* @type {Boolean}
*/
showError : {
view : true,
value : true
},
/**
* 是否仅显示一个错误
* @type {Boolean}
*/
showOneError: {
},
/**
* 错误信息,这个验证错误不包含子控件的验证错误
* @type {String}
*/
error : {
},
/**
* 暂停验证
* <pre><code>
* field.set('pauseValid',true); //可以调用field.clearErrors()
* field.set('pauseValid',false); //可以同时调用field.valid()
* </code></pre>
* @type {Boolean}
*/
pauseValid : {
value : false
}
};
Valid.prototype = {
__bindUI : function(){
var _self = this;
//监听是否禁用
_self.on('afterDisabledChange',function(ev){
var disabled = ev.newVal;
if(disabled){
_self.clearErrors(false,false);
}else{
_self.valid();
}
});
},
/**
* 是否通过验证
* @template
* @return {Boolean} 是否通过验证
*/
isValid : function(){
},
/**
* 进行验证
*/
valid : function(){
},
/**
* @protected
* @template
* 验证自身的规则和验证器
*/
validControl : function(){
},
//验证规则
validRules : function(rules,value){
if(!rules){
return null;
}
if(this.get('pauseValid')){
return null;
}
var _self = this,
messages = _self._getValidMessages(),
error = null;
for(var name in rules){
if(rules.hasOwnProperty(name)){
var baseValue = rules[name];
error = Rules.valid(name,value,baseValue,messages[name],_self);
if(error){
break;
}
}
}
return error;
},
//获取验证错误信息
_getValidMessages : function(){
var _self = this,
defaultMessages = _self.get('defaultMessages'),
messages = _self.get('messages');
return BUI.merge(defaultMessages,messages);
},
/**
* @template
* @protected
* 控件本身是否通过验证,不考虑子控件
* @return {String} 验证的错误
*/
getValidError : function(value){
var _self = this,
validator = _self.get('validator'),
error = null;
error = _self.validRules(_self.get('defaultRules'),value) || _self.validRules(_self.get('rules'),value);
if(!error && !this.get('pauseValid')){
if(_self.parseValue){
value = _self.parseValue(value);
}
error = validator ? validator.call(this,value) : '';
}
return error;
},
/**
* 获取验证出错信息,包括自身和子控件的验证错误信息
* @return {Array} 出错信息
*/
getErrors : function(){
},
/**
* 显示错误
* @param {Array} errors 显示错误
*/
showErrors : function(errors){
var _self = this,
errors = errors || _self.getErrors();
_self.get('view').showErrors(errors);
},
/**
* 清除错误
* @param {Boolean} reset 清除错误时是否重置
* @param {Boolean} [deep = true] 是否清理子控件的错误
*/
clearErrors : function(reset,deep){
deep = deep == null ? true : deep;
var _self = this,
children = _self.get('children');
if(deep){
BUI.each(children,function(item){
if(item.clearErrors){
if(item.field){
item.clearErrors(reset);
}else{
item.clearErrors(reset,deep);
}
}
});
}
_self.set('error',null);
_self.get('view').clearErrors();
},
/**
* 添加验证规则
* @param {String} name 规则名称
* @param {*} [value] 规则进行校验的进行对比的值,如max : 10
* @param {String} [message] 出错信息,可以使模板
* <ol>
* <li>如果 value 是单个值,例如最大值 value = 10,那么模板可以写成: '输入值不能大于{0}!'</li>
* <li>如果 value 是个复杂对象,数组时,按照索引,对象时按照 key 阻止。如:value= {max:10,min:5} ,则'输入值不能大于{max},不能小于{min}'</li>
* </ol>
* var field = form.getField('name');
* field.addRule('required',true);
*
* field.addRule('max',10,'不能大于{0}');
*/
addRule : function(name,value,message){
var _self = this,
rules = _self.get('rules'),
messages = _self.get('messages');
rules[name] = value;
if(message){
messages[name] = message;
}
},
/**
* 添加多个验证规则
* @param {Object} rules 多个验证规则
* @param {Object} [messages] 验证规则的出错信息
* var field = form.getField('name');
* field.addRules({
* required : true,
* max : 10
* });
*/
addRules : function(rules,messages){
var _self = this;
BUI.each(rules,function(value,name){
var msg = messages ? messages[name] : null;
_self.addRule(name,value,msg);
});
},
/**
* 移除指定名称的验证规则
* @param {String} name 验证规则名称
* var field = form.getField('name');
* field.remove('required');
*/
removeRule : function(name){
var _self = this,
rules = _self.get('rules');
delete rules[name];
},
/**
* 清理验证规则
*/
clearRules : function(){
var _self = this;
_self.set('rules',{});
}
};
Valid.View = ValidView;
module.exports = Valid;
|
// 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 Rendering engine detection.
* @see <a href="http://www.useragentstring.com/">User agent strings</a>
* For information on the browser brand (such as Safari versus Chrome), see
* goog.userAgent.product.
* @author arv@google.com (Erik Arvidsson)
* @see ../demos/useragent.html
*/
goog.provide('goog.userAgent');
goog.require('goog.labs.userAgent.browser');
goog.require('goog.labs.userAgent.engine');
goog.require('goog.labs.userAgent.platform');
goog.require('goog.labs.userAgent.util');
goog.require('goog.string');
/**
* @define {boolean} Whether we know at compile-time that the browser is IE.
*/
goog.define('goog.userAgent.ASSUME_IE', false);
/**
* @define {boolean} Whether we know at compile-time that the browser is EDGE.
*/
goog.define('goog.userAgent.ASSUME_EDGE', false);
/**
* @define {boolean} Whether we know at compile-time that the browser is GECKO.
*/
goog.define('goog.userAgent.ASSUME_GECKO', false);
/**
* @define {boolean} Whether we know at compile-time that the browser is WEBKIT.
*/
goog.define('goog.userAgent.ASSUME_WEBKIT', false);
/**
* @define {boolean} Whether we know at compile-time that the browser is a
* mobile device running WebKit e.g. iPhone or Android.
*/
goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);
/**
* @define {boolean} Whether we know at compile-time that the browser is OPERA.
*/
goog.define('goog.userAgent.ASSUME_OPERA', false);
/**
* @define {boolean} Whether the
* {@code goog.userAgent.isVersionOrHigher}
* function will return true for any version.
*/
goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);
/**
* Whether we know the browser engine at compile-time.
* @type {boolean}
* @private
*/
goog.userAgent.BROWSER_KNOWN_ =
goog.userAgent.ASSUME_IE ||
goog.userAgent.ASSUME_EDGE ||
goog.userAgent.ASSUME_GECKO ||
goog.userAgent.ASSUME_MOBILE_WEBKIT ||
goog.userAgent.ASSUME_WEBKIT ||
goog.userAgent.ASSUME_OPERA;
/**
* Returns the userAgent string for the current browser.
*
* @return {string} The userAgent string.
*/
goog.userAgent.getUserAgentString = function() {
return goog.labs.userAgent.util.getUserAgent();
};
/**
* TODO(nnaze): Change type to "Navigator" and update compilation targets.
* @return {Object} The native navigator object.
*/
goog.userAgent.getNavigator = function() {
// Need a local navigator reference instead of using the global one,
// to avoid the rare case where they reference different objects.
// (in a WorkerPool, for example).
return goog.global['navigator'] || null;
};
/**
* Whether the user agent is Opera.
* @type {boolean}
*/
goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_OPERA :
goog.labs.userAgent.browser.isOpera();
/**
* Whether the user agent is Internet Explorer.
* @type {boolean}
*/
goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_IE :
goog.labs.userAgent.browser.isIE();
/**
* Whether the user agent is Microsoft Edge.
* @type {boolean}
*/
goog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_EDGE :
goog.labs.userAgent.engine.isEdge();
/**
* Whether the user agent is MS Internet Explorer or MS Edge.
* @type {boolean}
*/
goog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;
/**
* Whether the user agent is Gecko. Gecko is the rendering engine used by
* Mozilla, Firefox, and others.
* @type {boolean}
*/
goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_GECKO :
goog.labs.userAgent.engine.isGecko();
/**
* Whether the user agent is WebKit. WebKit is the rendering engine that
* Safari, Android and others use.
* @type {boolean}
*/
goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?
goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :
goog.labs.userAgent.engine.isWebKit();
/**
* Whether the user agent is running on a mobile device.
*
* This is a separate function so that the logic can be tested.
*
* TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().
*
* @return {boolean} Whether the user agent is running on a mobile device.
* @private
*/
goog.userAgent.isMobile_ = function() {
return goog.userAgent.WEBKIT &&
goog.labs.userAgent.util.matchUserAgent('Mobile');
};
/**
* Whether the user agent is running on a mobile device.
*
* TODO(nnaze): Consider deprecating MOBILE when labs.userAgent
* is promoted as the gecko/webkit logic is likely inaccurate.
*
* @type {boolean}
*/
goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT ||
goog.userAgent.isMobile_();
/**
* Used while transitioning code to use WEBKIT instead.
* @type {boolean}
* @deprecated Use {@link goog.userAgent.product.SAFARI} instead.
* TODO(nicksantos): Delete this from goog.userAgent.
*/
goog.userAgent.SAFARI = goog.userAgent.WEBKIT;
/**
* @return {string} the platform (operating system) the user agent is running
* on. Default to empty string because navigator.platform may not be defined
* (on Rhino, for example).
* @private
*/
goog.userAgent.determinePlatform_ = function() {
var navigator = goog.userAgent.getNavigator();
return navigator && navigator.platform || '';
};
/**
* The platform (operating system) the user agent is running on. Default to
* empty string because navigator.platform may not be defined (on Rhino, for
* example).
* @type {string}
*/
goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();
/**
* @define {boolean} Whether the user agent is running on a Macintosh operating
* system.
*/
goog.define('goog.userAgent.ASSUME_MAC', false);
/**
* @define {boolean} Whether the user agent is running on a Windows operating
* system.
*/
goog.define('goog.userAgent.ASSUME_WINDOWS', false);
/**
* @define {boolean} Whether the user agent is running on a Linux operating
* system.
*/
goog.define('goog.userAgent.ASSUME_LINUX', false);
/**
* @define {boolean} Whether the user agent is running on a X11 windowing
* system.
*/
goog.define('goog.userAgent.ASSUME_X11', false);
/**
* @define {boolean} Whether the user agent is running on Android.
*/
goog.define('goog.userAgent.ASSUME_ANDROID', false);
/**
* @define {boolean} Whether the user agent is running on an iPhone.
*/
goog.define('goog.userAgent.ASSUME_IPHONE', false);
/**
* @define {boolean} Whether the user agent is running on an iPad.
*/
goog.define('goog.userAgent.ASSUME_IPAD', false);
/**
* @type {boolean}
* @private
*/
goog.userAgent.PLATFORM_KNOWN_ =
goog.userAgent.ASSUME_MAC ||
goog.userAgent.ASSUME_WINDOWS ||
goog.userAgent.ASSUME_LINUX ||
goog.userAgent.ASSUME_X11 ||
goog.userAgent.ASSUME_ANDROID ||
goog.userAgent.ASSUME_IPHONE ||
goog.userAgent.ASSUME_IPAD;
/**
* Whether the user agent is running on a Macintosh operating system.
* @type {boolean}
*/
goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_MAC : goog.labs.userAgent.platform.isMacintosh();
/**
* Whether the user agent is running on a Windows operating system.
* @type {boolean}
*/
goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_WINDOWS :
goog.labs.userAgent.platform.isWindows();
/**
* Whether the user agent is Linux per the legacy behavior of
* goog.userAgent.LINUX, which considered ChromeOS to also be
* Linux.
* @return {boolean}
* @private
*/
goog.userAgent.isLegacyLinux_ = function() {
return goog.labs.userAgent.platform.isLinux() ||
goog.labs.userAgent.platform.isChromeOS();
};
/**
* Whether the user agent is running on a Linux operating system.
*
* Note that goog.userAgent.LINUX considers ChromeOS to be Linux,
* while goog.labs.userAgent.platform considers ChromeOS and
* Linux to be different OSes.
*
* @type {boolean}
*/
goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_LINUX :
goog.userAgent.isLegacyLinux_();
/**
* @return {boolean} Whether the user agent is an X11 windowing system.
* @private
*/
goog.userAgent.isX11_ = function() {
var navigator = goog.userAgent.getNavigator();
return !!navigator &&
goog.string.contains(navigator['appVersion'] || '', 'X11');
};
/**
* Whether the user agent is running on a X11 windowing system.
* @type {boolean}
*/
goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_X11 :
goog.userAgent.isX11_();
/**
* Whether the user agent is running on Android.
* @type {boolean}
*/
goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_ANDROID :
goog.labs.userAgent.platform.isAndroid();
/**
* Whether the user agent is running on an iPhone.
* @type {boolean}
*/
goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_IPHONE :
goog.labs.userAgent.platform.isIphone();
/**
* Whether the user agent is running on an iPad.
* @type {boolean}
*/
goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?
goog.userAgent.ASSUME_IPAD :
goog.labs.userAgent.platform.isIpad();
/**
* @return {string} The string that describes the version number of the user
* agent.
* Assumes user agent is opera.
* @private
*/
goog.userAgent.operaVersion_ = function() {
var version = goog.global.opera.version;
try {
return version();
} catch (e) {
return version;
}
};
/**
* @return {string} The string that describes the version number of the user
* agent.
* @private
*/
goog.userAgent.determineVersion_ = function() {
// All browsers have different ways to detect the version and they all have
// different naming schemes.
if (goog.userAgent.OPERA && goog.global['opera']) {
return goog.userAgent.operaVersion_();
}
// version is a string rather than a number because it may contain 'b', 'a',
// and so on.
var version = '';
var arr = goog.userAgent.getVersionRegexResult_();
if (arr) {
version = arr ? arr[1] : '';
}
if (goog.userAgent.IE) {
// IE9 can be in document mode 9 but be reporting an inconsistent user agent
// version. If it is identifying as a version lower than 9 we take the
// documentMode as the version instead. IE8 has similar behavior.
// It is recommended to set the X-UA-Compatible header to ensure that IE9
// uses documentMode 9.
var docMode = goog.userAgent.getDocumentMode_();
if (docMode > parseFloat(version)) {
return String(docMode);
}
}
return version;
};
/**
* @return {Array|undefined} The version regex matches from parsing the user
* agent string. These regex statements must be executed inline so they can
* be compiled out by the closure compiler with the rest of the useragent
* detection logic when ASSUME_* is specified.
* @private
*/
goog.userAgent.getVersionRegexResult_ = function() {
var userAgent = goog.userAgent.getUserAgentString();
if (goog.userAgent.GECKO) {
return /rv\:([^\);]+)(\)|;)/.exec(userAgent);
}
if (goog.userAgent.EDGE) {
return /Edge\/([\d\.]+)/.exec(userAgent);
}
if (goog.userAgent.IE) {
return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(userAgent);
}
if (goog.userAgent.WEBKIT) {
// WebKit/125.4
return /WebKit\/(\S+)/.exec(userAgent);
}
};
/**
* @return {number|undefined} Returns the document mode (for testing).
* @private
*/
goog.userAgent.getDocumentMode_ = function() {
// NOTE(user): goog.userAgent may be used in context where there is no DOM.
var doc = goog.global['document'];
return doc ? doc['documentMode'] : undefined;
};
/**
* The version of the user agent. This is a string because it might contain
* 'b' (as in beta) as well as multiple dots.
* @type {string}
*/
goog.userAgent.VERSION = goog.userAgent.determineVersion_();
/**
* Compares two version numbers.
*
* @param {string} v1 Version of first item.
* @param {string} v2 Version of second item.
*
* @return {number} 1 if first argument is higher
* 0 if arguments are equal
* -1 if second argument is higher.
* @deprecated Use goog.string.compareVersions.
*/
goog.userAgent.compare = function(v1, v2) {
return goog.string.compareVersions(v1, v2);
};
/**
* Cache for {@link goog.userAgent.isVersionOrHigher}.
* Calls to compareVersions are surprisingly expensive and, as a browser's
* version number is unlikely to change during a session, we cache the results.
* @const
* @private
*/
goog.userAgent.isVersionOrHigherCache_ = {};
/**
* Whether the user agent version is higher or the same as the given version.
* NOTE: When checking the version numbers for Firefox and Safari, be sure to
* use the engine's version, not the browser's version number. For example,
* Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.
* Opera and Internet Explorer versions match the product release number.<br>
* @see <a href="http://en.wikipedia.org/wiki/Safari_version_history">
* Webkit</a>
* @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a>
*
* @param {string|number} version The version to check.
* @return {boolean} Whether the user agent version is higher or the same as
* the given version.
*/
goog.userAgent.isVersionOrHigher = function(version) {
return goog.userAgent.ASSUME_ANY_VERSION ||
goog.userAgent.isVersionOrHigherCache_[version] ||
(goog.userAgent.isVersionOrHigherCache_[version] =
goog.string.compareVersions(goog.userAgent.VERSION, version) >= 0);
};
/**
* Deprecated alias to {@code goog.userAgent.isVersionOrHigher}.
* @param {string|number} version The version to check.
* @return {boolean} Whether the user agent version is higher or the same as
* the given version.
* @deprecated Use goog.userAgent.isVersionOrHigher().
*/
goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;
/**
* Whether the IE effective document mode is higher or the same as the given
* document mode version.
* NOTE: Only for IE, return false for another browser.
*
* @param {number} documentMode The document mode version to check.
* @return {boolean} Whether the IE effective document mode is higher or the
* same as the given version.
*/
goog.userAgent.isDocumentModeOrHigher = function(documentMode) {
return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;
};
/**
* Deprecated alias to {@code goog.userAgent.isDocumentModeOrHigher}.
* @param {number} version The version to check.
* @return {boolean} Whether the IE effective document mode is higher or the
* same as the given version.
* @deprecated Use goog.userAgent.isDocumentModeOrHigher().
*/
goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;
/**
* For IE version < 7, documentMode is undefined, so attempt to use the
* CSS1Compat property to see if we are in standards mode. If we are in
* standards mode, treat the browser version as the document mode. Otherwise,
* IE is emulating version 5.
* @type {number|undefined}
* @const
*/
goog.userAgent.DOCUMENT_MODE = (function() {
var doc = goog.global['document'];
var mode = goog.userAgent.getDocumentMode_();
if (!doc || !goog.userAgent.IE) {
return undefined;
}
return mode || (doc['compatMode'] == 'CSS1Compat' ?
parseInt(goog.userAgent.VERSION, 10) : 5);
})();
|
function getStartLocationFromURL() {
var curUrl = window.location.toString();
var anchor_index = curUrl.indexOf('#/');
if (anchor_index != -1) {
return curUrl.substring(anchor_index + 2);
}else{
return null;
}
}
function getUrlParameterByName(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function raiseCommandEvent(commandName, params) {
var element = document.createElement("flexCommandEvent");
element.setAttribute("commandName", commandName);
for(var index in params) {
element.setAttribute(index, params[index]);
}
document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("flexCommandEvent", true, false);
element.dispatchEvent(evt);
}
function setisScrollableWindow(isScrollable) {
setisOnScrollableWindow(isScrollable);
}
function notifyLogin() {
raiseCommandEvent("login");
}
function notifyLogout() {
raiseCommandEvent("logout");
}
function notifyPearlDeleted(pearlUrl) {
var params = [];
params['pearlUrl'] = pearlUrl;
raiseCommandEvent("pearlDeleted", params);
}
function detectPearlbar() {
raiseCommandEvent("detectPearlbar");
raiseCommandEvent("getPearlbarVersion");
}
function updateFirefoxAddon(addonTitle, addonURL, addonIcon) {
if(getOSName() == "Linux") {
openNewPopup(getWebSiteUrl()+"collector/downloadProxy.html?url="+addonURL, 300, 100);
}
else {
openWindow(addonURL, "_top");
}
}
function callPearlbarCommand(commandName, param) {
getMainApplication().pearlbarCommand(commandName, param);
}
function onPearlbarCommandEvent(event) {
var commandName = event.target.getAttribute("commandName");
if(commandName == "pearlbarIsInstalled") {
pearlbarIsInstalled = true;
callPearlbarCommand("pearlbarIsInstalled");
}
else if(commandName == "returnPearlbarVersion") {
var value = event.target.getAttribute("value");
callPearlbarCommand("setPearlbarVersion", value);
}
}
if (window.addEventListener) {
window.addEventListener("pearlbarCommandEvent", onPearlbarCommandEvent, false);
}
else if (window.attachEvent) {
window.attachEvent("pearlbarCommandEvent", onPearlbarCommandEvent)
}
function notifyNewAccountCreated(userId) {
if(self.location.hostname == "www.pearltrees.com") {
if(pingbackUrl) {
(new Image).src = pingbackUrl+"&userId="+userId;
}
if(_gaq) {
_gaq.push(['_setAllowAnchor', true]);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackEvent', 'Home', 'Create Account', self.location.search]);
}
}
if(piwikTracker) {
var pearltreesPingBackUrl = pkBaseURL+"piwik.php?url=" +
encodeURIComponent(getServicesUrl()+"piwik/logAccountCreated/"+self.location.search) +
"&action_name=create_account&idsite=" + pkSite + "&title=create_account&urlref=" + encodeURIComponent(document.referrer)+"&rec=1&rand=" + Math.random();
(new Image).src = pearltreesPingBackUrl;
}
}
function notifyUserHasDockedPearlWindow(userId) {
(new Image).src = getServicesUrl()+"check/userHasDockedPearlWindow/?userId="+userId;
}
function getBrowserName() {
return BrowserDetect.browser;
}
function getOSName() {
return BrowserDetect.OS;
}
function getBrowserVersion() {
return BrowserDetect.version;
}
function getSessionID() {
return readCookie('PEARLTREES-AUTH');
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function getUserLang() {
return userLang;
}
function createCookie(name,value,seconds) {
if (seconds) {
var date = new Date();
date.setTime(date.getTime()+(seconds*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function hideWaitingPanel() {
stopPreloader();
getMainApplication().style.width='100%';
getMainApplication().style.height='100%';
document.getElementById('page').style.display='none';
document.getElementById('page').innerHTML='';
}
function onApplicationExit(){
var app = getMainApplication();
if(app && app.onApplicationExit) {
app.onApplicationExit();
}
}
function getInvitationEmail(){
return invitationEmail;
}
function getInvitationKey(){
return invitationKey;
}
function getFbRequestId(){
return fbRequestId;
}
function getAbModel(){
return abModel;
}
function getLostPasswordToken(){
return lostPasswordToken;
}
function getOrigin() {
return origin;
}
function getUserName() {
return userName;
}
function getUserId() {
return userId;
}
function getWebSiteUrl() {
return webSiteUrl;
}
function getStaticContentUrl() {
return staticContentUrl;
}
function getFbAppId() {
return fbAppId;
}
function getLogoUrl() {
return logoUrl;
}
function getMetaLogoUrl() {
return metaLogoUrl;
}
function getThumbLogoUrl() {
return thumbLogoUrl;
}
function getScrapLogoUrl() {
return scrapLogoUrl;
}
function getAvatarUrl() {
return avatarUrl;
}
function getBackgroundUrl() {
return backgroundUrl;
}
function getBiblioUrl() {
return biblioUrl;
}
function getThumbshotUrl() {
return thumbshotUrl;
}
function getServicesUrl() {
return servicesUrl;
}
function getMediaUrl() {
return mediaUrl;
}
function getShortenerDomain() {
return shortenerDomain;
}
function getClientLang() {
var urlParam = getUrlParameterByName("lang");
if(urlParam) {
return urlParam;
}else{
return clientLang;
}
}
function getClientId() {
return clientId;
}
function getLoginUsername() {
return loginUsername;
}
function getStartTime() {
return startTime;
}
function getStartupMessage() {
return startupMessage;
}
function getUserInvitingYou() {
return userInvitingYou;
}
function getPromoBigWindow() {
return promoBigWindow;
}
function getAdPermission() {
var curUrl = window.location.toString();
if (curUrl.indexOf("ad=no") > 0) {
return false;
}
else {
return true;
}
}
function getTeaserMode() {
return teaserMode;
}
function getAbModel() {
return abModel;
}
function getCountryCode() {
return countryCode;
}
function getAddPearlEmail() {
return pearlByMail;
}
function getPearlWindowStatus() {
return pearlWindowStatus;
}
function getPromoLittleWindow() {
return promoLittleWindow;
}
function getArrivalTreeId() {
return arrivalTreeId;
}
function getPlayerStartUrl() {
return startPlayerWithUrl;
}
function changeParentUrl(parentUrl) {
top.location = parentUrl;
}
function getInnerWidth() {
var windowWidth = window.innerWidth;
if(!windowWidth) { windowWidth = document.documentElement.clientWidth; }
if(windowWidth <= 0) { windowWidth = document.body.clientWidth; }
return windowWidth;
}
function getInnerHeight() {
var windowHeight = window.innerHeight;
if(!windowHeight) { windowHeight = document.documentElement.clientHeight; }
if(windowHeight <= 0) { windowHeight = document.body.clientHeight; }
return windowHeight;
}
function loadIFrame(frameID, iframeID, url) {
document.getElementById(iframeID).src = url;
}
if(self.location.href.indexOf("/#/embedWindow=1") != -1) {
return;
}
if (typeof _gaq !== "undefined") {
if(_gaq && self.location.hostname == "www.pearltrees.com") {
_gaq.push(['_setAllowAnchor', true]);
_gaq.push(['_trackPageview']);
}
}
if(typeof piwikTracker != "undefined") {
(new Image).src = pkBaseURL+"piwik.php?url=" +
encodeURIComponent(window.location) + "&action_name=" + encodeURIComponent(title) + "&idsite=" + pkSite + "&title=" +
encodeURIComponent(title) + "&urlref=" + encodeURIComponent(document.referrer)+"&rec=1&rand=" + Math.random();
}
var app = getMainApplication();
if(app && app.onSendPageViewStat) {
app.onSendPageViewStat();
}
}
var isReloadingPage = false;
function reloadPage() {
if (!isReloadingPage){
isReloadingPage = true;
self.location.reload(true);
}
}
function getLocalLastSaveDate() {
var lastSaveDate = readCookie("lastSaveDate");
if (lastSaveDate==null) {
return 0;
}
return lastSaveDate
}
function setLocalLastSaveDate(lastSaveDate) {
createCookie("lastSaveDate", lastSaveDate,5);
}
var prefetchFrameCounter = 0;
function loadPageInIframe(url) {
}
function loadPageInCache(url, keepUrl) {
var f = document.createElement("iframe");
f.style.display = "none";
f.id = "prefetchFrame" + (prefetchFrameCounter++);
if (keepUrl) {
f.src = url;
} else {
f.src = staticContentUrl + "s/prefetch/" + (ff ? "link" : "load") + "?url=" + encodeURIComponent(url);
}
f.onload = function () {pageInCacheLoaded(f.id);};
document.body.appendChild(f);
return f.id;
return loadPageInFrame(cachedUrl);
}
function removePageInCache(id) {
var f = document.getElementById(id);
if (f) document.body.removeChild(f);
}
/*function loadPageInCache(url) {
var v = readCookie("prefetch");
if (v == "1") {
setTimeout('loadPageInCache0("' + url + '")', 5000);
}
}*/
function pageInCacheLoaded(id) {
var app = getMainApplication();
if(app && app.onPageInCacheLoaded) {
app.onPageInCacheLoaded(id);
}
}
/*
function moveIFrame(frameID, iframeID, x,y,w,h)
{
var frameRef=document.getElementById(frameID);
if (frameRef) {
frameRef.style.left=x;
frameRef.style.top=y;
frameRef.width = w;
frameRef.height = h;
}
var iFrameRef=document.getElementById(iframeID);
if (iFrameRef) {
iFrameRef.width=w;
iFrameRef.height=h;
}
}
*/
function testCookieEnabled(){
var cookieEnabled=(navigator.cookieEnabled)? true : false
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}
return cookieEnabled;
}
function getPotentialBadFrameId() {
return readCookie("potentialBadFrameId");
}
function savePotentialBadFrameId(lastPearlId) {
createCookie("potentialBadFrameId", lastPearlId, 60);
}
function openWindow(url, target) {
var newWin = window.open(url, target);
return newWin && !newWin.closed && typeof newWin != 'undefined' && typeof newWin.closed != 'undefined';
}
function openNewPopup(url, width, height) {
var coordinates = getCenteredCoords(width, height);
var newWin = window.open(url, "_blank", "location=0,menubar=0,scrollbars=1,toolbar=0,resizable=1,status=0,directories=0,width=" + width + ",height=" + height + ",left=" + coordinates[0] +",top=" + coordinates[1]);
return newWin && !newWin.closed && typeof newWin != 'undefined' && typeof newWin.closed != 'undefined';
}
var monitoredPopup;
var intervalChecker;
var monitoredPopupAnswer;
function openMonitoredPopup(url, width, height) {
var coordinates = getCenteredCoords(width, height);
monitoredPopupAnswer = null;
monitoredPopup = window.open(url, "_blank", "location=0,menubar=0,scrollbars=1,toolbar=0,resizable=1,status=0,directories=0," +
"width=" + width + ",height=" + height + ",left=" + coordinates[0] +",top=" + coordinates[1]);
if (isMonitoredPopupClosed()) {
return false;
}
intervalChecker = window.setInterval(waitForPopupClose, 80);
return true;
}
function closeMonitoredPopup() {
if (monitoredPopup) {
monitoredPopup.close();
if ((null !== intervalChecker)) {
window.clearInterval(intervalChecker);
intervalChecker = null;
}
}
}
function isMonitoredPopupClosed() {
if (monitoredPopup && monitoredPopupAnswer == null) {
try {
monitoredPopupUrl = monitoredPopup.location.href;
if(monitoredPopupUrl) {
monitoredPopupAnswer = monitoredPopup.answer;
if (monitoredPopupAnswer) {
closeMonitoredPopup();
return true;
}
}
}catch(error){
}
}
try {
return !monitoredPopup || monitoredPopup.closed || typeof monitoredPopup == 'undefined' || typeof monitoredPopup.closed=='undefined';
}
catch (err) {
return true;
}
}
function waitForPopupClose() {
if (isMonitoredPopupClosed()) {
monitoredPopup = null;
if(getMainApplication()) {
getMainApplication().onMonitoredPopupClose();
}
if ((null !== intervalChecker)) {
window.clearInterval(intervalChecker);
intervalChecker = null;
}
}
}
function getMonitoredPopupAnswer() {
return monitoredPopupAnswer;
}
function getCenteredCoords(width, height) {
var parentSize = this.getWindowInnerSize();
var parentPos = this.getParentCoords();
var xPos = parentPos[0] +
Math.max(0, Math.floor((parentSize[0] - width) / 2));
var yPos = parentPos[1] +
Math.max(0, Math.floor((parentSize[1] - height) / 2));
return [xPos, yPos];
}
function getWindowInnerSize() {
var width = 0;
var height = 0;
var elem = null;
if ('innerWidth' in window) {
width = window.innerWidth;
height = window.innerHeight;
} else {
if (('BackCompat' === window.document.compatMode)
&& ('body' in window.document)) {
elem = window.document.body;
} else if ('documentElement' in window.document) {
elem = window.document.documentElement;
}
if (elem !== null) {
width = elem.offsetWidth;
height = elem.offsetHeight;
}
}
return [width, height];
}
function getParentCoords() {
var width = 0;
var height = 0;
if ('screenLeft' in window) {
width = window.screenLeft;
height = window.screenTop;
} else if ('screenX' in window) {
width = window.screenX;
height = window.screenY;
}
return [width, height];
}
function isBrowserMSIE() { return (getBrowserName() == 'Explorer') }
function isBrowserFirefoxOnMac() { return ( (getBrowserName() == 'Firefox') && (BrowserDetect.OS == "Mac") ) }
function getZoom() {
var zoomFactor = getZoomFactor();
return zoomFactor;
}
function isZoomFactorNotOne() {
var zoomFactor = getZoom();
if ((zoomFactor < 0.98) || (zoomFactor > 1.02)) return 1;
return 0;
}
function closeNodeById(id) {
var node = document.getElementById(id);
if (node != null) node.parentNode.removeChild(node);
}
function applyStyleToNode(node, styleString) {
if (isBrowserMSIE()) {
node.style.setAttribute('cssText', styleString);
} else {
node.setAttribute('style', styleString);
}
}
function closeFacepile() {
closeNodeById("facepileSolidBackground");
closeNodeById("facepile");
}
function styleFacePile(z_index, absolute_top, absolute_left, _width, _height) {
var styleString = "";
styleString += "z-index:" + z_index + "; ";
styleString += "position: absolute; ";
styleString += "top:" + absolute_top + "px; ";
styleString += "left:" + absolute_left + "px; ";
styleString += "width:" + _width + "px; ";
styleString += "height:" + _height + "px;";
return styleString;
}
function openFacepileSolidBackground(z_index, _top, _left, _width, _height) {
var id = "facepileSolidBackground";
var node = document.getElementById(id);
if (node != null) return;
var body = document.getElementsByTagName("body")[0];
if (body == null) return;
var div = document.createElement('div');
div.setAttribute('id', id);
var myStaticContentUrl = getStaticContentUrl();
var url = getStaticContentUrl() + "flash/solidBackground-ffffff.swf";
var styleString = styleFacePile(z_index, _top, _left, _width, _height);
applyStyleToNode(div, styleString);
var flashObject = document.createElement('object');
flashObject.setAttribute("width", "100%");
flashObject.setAttribute("height", "100%");
flashObject.setAttribute("type", "application/x-shockwave-flash");
flashObject.setAttribute("data", url);
var flashParamMovie = document.createElement('param');
flashParamMovie.setAttribute("name", "movie");
flashParamMovie.setAttribute("value", url);
var flashParamWMode = document.createElement('param');
flashParamWMode.setAttribute("name", "wmode");
flashParamWMode.setAttribute("value", "opaque");
flashObject.appendChild(flashParamMovie);
flashObject.appendChild(flashParamWMode);
div.appendChild(flashObject);
body.appendChild(div);
}
function resizeFacepile(z_index, banner_width, offset_x, offset_y, _width, _height) {
var absolute_top = offset_y;
var absolute_left = newLeft + offset_x;
var styleString = styleFacePile(z_index, absolute_top, absolute_left, _width, _height);
var divNode = document.getElementById("facepile");
if (divNode != null) applyStyleToNode(divNode, styleString);
var divSolidNode = document.getElementById("facepileSolidBackground");
if (divNode != null) applyStyleToNode(divSolidNode, styleString);
}
function openFacepile(z_index, banner_width, offset_x, offset_y, _width, _height, url) {
var node = document.getElementById("facepile");
if (node != null) return;
var body = document.getElementsByTagName("body")[0];
if (body == null) return;
var div = document.createElement('div');
div.setAttribute('id', "facepile");
var absolute_top = offset_y;
var absolute_left = offset_x;
openFacepileSolidBackground(z_index, absolute_top, absolute_left, _width, _height);
var styleString = styleFacePile(z_index, absolute_top, absolute_left, _width, _height);
applyStyleToNode(div, styleString);
var iframe = document.createElement('iframe');
iframe.setAttribute('src', url);
iframe.setAttribute('scrolling', "no");
iframe.setAttribute('frameBorder', '0');
var delta = -3;
var iFrameStyleString = "";
iFrameStyleString += "border: none; ";
iFrameStyleString += "overflow: hidden; ";
iFrameStyleString += "width:" + _width + "px; ";
iFrameStyleString += "height:" + (_height -2*delta) + "px;";
iFrameStyleString += "position: relative;";
iFrameStyleString += "top: " + delta + "px;";
iFrameStyleString += "background-color: white;";
applyStyleToNode(iframe, iFrameStyleString);
div.appendChild(iframe);
body.appendChild(div);
}
var fbSdkInitialized;
var facebookId = null;
var facebookIdIsLoading = true;
window.fbAsyncInit = function() {
fbSdkInitialized = false;
FB.init({
appId : getFbAppId(),
channelUrl : getWebSiteUrl() + 'channel.html',
status : true,
cookie : true,
xfbml : true
});
fbSdkInitialized = true;
FB.getLoginStatus(function(response) {
facebookIdIsLoading = false;
if (response.status === 'connected') {
facebookId = response.authResponse.userID;
}
});
};
function loadFacebookSdk(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
status: true;
ref.parentNode.insertBefore(js, ref);
}
function getFacebookId() {
return facebookId;
}
function getFacebookIdIsLoading() {
return facebookIdIsLoading;
}
function updateFacebookToken(updateUrl) {
var timeout = 10000;
var listenInterval = 1000;
$('#fbAuthIframe').get(0).src = updateUrl;
listenFbAuthIframe(function(result) {
if(result == "timeout") {
}else{
}
if(getMainApplication()) {
getMainApplication().onIFrameFilled();
}
$('#fbAuthIframe').get(0).src = null;
}, (new Date()).getTime(), timeout, listenInterval);
}
function listenFbAuthIframe(callback, startTime, timeout, listenInterval) {
var iframeUrl = null;
var iframeContent = null;
var duration = (new Date()).getTime() - startTime;
try {
iframeUrl = $('#fbAuthIframe').get(0).contentWindow.location.href;
if(iframeUrl && iframeUrl.indexOf(getWebSiteUrl()) == 0) {
iframeContent = $('#fbAuthIframe').contents().text();
if(iframeContent == "") iframeContent = null;
}
}catch(error){
}
if(iframeContent) {
callback(iframeContent);
}
else {
if(duration <= timeout) {
setTimeout("listenFbAuthIframe("+callback+", "+startTime+", "+timeout+", "+listenInterval+")", listenInterval);
}else {
callback("timeout");
}
}
}
function installChromeExtension() {
var apiAvailable = typeof chrome !== 'undefined' && chrome.webstore && chrome.webstore.install;
if (apiAvailable) {
try {
chrome.webstore.install(undefined, undefined, function(err) {
apiAvailable = false;
console.log('inline install failed: ' + err);
});
} catch(err) {
console.log('inline install failed: ' + err)
apiAvailable = false;
}
}
if(!apiAvailable) {
window.open("https://chrome.google.com/webstore/detail/bgngjfgpahnnncnimlhjgjhdajmaeeoa", "_blank");
}
}
function getLocationName() {
return locationName;
}
function getBackgroundHash() {
return backgroundHash;
}
function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
};
function isFileApiSupported() {
return (window.File !== undefined
&& window.FileReader !== undefined
&& window.FileList != undefined
&& window.Blob !== undefined);
}
function protectTabDuringUpload(message) {
window.onbeforeunload = function() {
onApplicationExit();
return message;
}
}
function unprotectTabAfterUpload() {
window.onbeforeunload = onApplicationExit;
}
var UploadHelper = (function () {
function UploadHelper() {
}
UploadHelper.getHTMLContainer = function () {
return mainContainer;
};
UploadHelper.getFileSelector = function () {
return document.getElementById("fileSelector");
};
return UploadHelper;
})();
var FileBatch = (function () {
function FileBatch(files, urlIds) {
this.files = [];
this.urlIds = [];
this.excludedFiles = [];
for (var i = 0; i < files.length; i++) {
this.files[i] = files[i];
var file_to_big = files[i].size > Uploader.MAX_FILE_SIZE;
this.excludedFiles[i] = file_to_big;
}
this.urlIds = urlIds;
}
FileBatch.prototype.excludeFile = function (position) {
if (position < this.excludedFiles.length) {
this.excludedFiles[position] = true;
}
};
return FileBatch;
})();
var Uploader = (function () {
function Uploader(action) {
var _this = this;
this.lastFileSentPosition = -1;
this.fileBatches = [];
this.lastBatchSentPosition = -1;
this.batchNumber = 0;
this.currentBatchUrlIds = [];
this.currentBatchSize = 0;
this.isUploading = false;
this.sizeFilesSentComplete = 0;
this.sizeCurrentFileSent = 0;
this.onFilesSelect = function (evt) {
_this.waitingFiles = evt.target.files;
var mainApp = getMainApplication();
if (mainApp) {
var fileInfoArray = FileInfo.makeFileInfoArray(_this.waitingFiles);
mainApp.notifySelectFiles(fileInfoArray, _this.fileBatches.length + 1);
}
refreshFileSelectorInHtml();
};
this.upload_url = getServicesUrl() + action;
this.uploadStatus_url = getServicesUrl() + 'file/status';
this.isUploading = false;
}
Uploader.getInstance = function () {
if (!Uploader.instance) {
Uploader.instance = new Uploader('file/chunks');
}
return Uploader.instance;
};
Uploader.newInstance = function () {
Uploader.instance = new Uploader('file/chunks');
return Uploader.instance;
};
Uploader.prototype.openFileSelector = function () {
var fileSelector = UploadHelper.getFileSelector();
fileSelector.addEventListener('change', this.onFilesSelect, false);
fileSelector.click();
};
Uploader.prototype.sendCurrentFileSuccess = function () {
this.lastFileSentPosition++;
this.sizeFilesSentComplete += this.getCurrentBatchFiles()[this.lastFileSentPosition].size;
this.sizeCurrentFileSent = 0;
var mainApp = getMainApplication();
if (mainApp) {
mainApp.notifyUploadFileComplete(this.lastFileSentPosition, this.lastBatchSentPosition + 1);
}
if (this.lastFileSentPosition > this.getCurrentBatchFiles().length - 2) {
this.sendCurrentBatchComplete();
} else {
this.sendNextFileIfExist();
}
};
Uploader.prototype.getCurrentBatchFiles = function () {
return this.fileBatches[this.lastBatchSentPosition + 1].files;
};
Uploader.prototype.getCurrentBatchUrlIds = function () {
return this.fileBatches[this.lastBatchSentPosition + 1].urlIds;
};
Uploader.prototype.sendCurrentBatchComplete = function () {
this.lastBatchSentPosition++;
var mainApp = getMainApplication();
if (mainApp) {
mainApp.notifyUploadBatchComplete(this.lastBatchSentPosition);
}
if (this.lastBatchSentPosition > this.fileBatches.length - 2) {
this.sendAllFilesSuccess();
} else {
this.sendNextBatchIfExist();
}
};
Uploader.prototype.sendCurrentFileError = function () {
this.excludeFile(this.lastFileSentPosition + 1, this.lastBatchSentPosition + 1);
var mainApp = getMainApplication();
if (mainApp) {
mainApp.notifyUploadFileError(this.lastFileSentPosition + 1, this.lastBatchSentPosition + 1);
}
if (this.lastFileSentPosition > this.getCurrentBatchFiles().length - 2) {
this.sendCurrentBatchComplete();
} else {
this.sendNextFileIfExist();
}
this.lastFileSentPosition++;
};
Uploader.prototype.excludeFile = function (positionFile, positionBatch) {
if (positionBatch < this.fileBatches.length) {
var batch = this.fileBatches[positionBatch];
batch.excludeFile(positionFile);
if (positionBatch == this.lastBatchSentPosition + 1) {
this.currentBatchSize -= batch.files[positionFile].size;
}
}
};
Uploader.prototype.sendNextBatchIfExist = function () {
this.lastFileSentPosition = -1;
this.sizeFilesSentComplete = 0;
var batchToSendPosition = this.lastBatchSentPosition + 1;
if (batchToSendPosition < this.fileBatches.length) {
var currentBatch = this.fileBatches[batchToSendPosition];
this.computeBatchSize();
this.sendNextFileIfExist();
} else {
this.sendAllFilesSuccess();
}
};
Uploader.prototype.sendNextFileIfExist = function () {
var fileToSendPosition = this.lastFileSentPosition + 1;
if (fileToSendPosition < this.getCurrentBatchFiles().length) {
if (this.fileBatches[this.lastBatchSentPosition + 1].excludedFiles[fileToSendPosition]) {
this.lastFileSentPosition++;
this.sendNextFileIfExist();
return;
}
var file;
file = this.getCurrentBatchFiles()[this.lastFileSentPosition + 1];
this.fileUploader = new FileUploader(file, this, this.getCurrentBatchUrlIds()[fileToSendPosition]);
this.fileUploader.upload();
this.sizeCurrentFileSent = 0;
} else {
this.sendCurrentBatchComplete();
}
};
Uploader.prototype.computeBatchSize = function () {
this.currentBatchSize = 0;
for (var i = 0; i < this.getCurrentBatchFiles().length; i++) {
if (!this.fileBatches[this.lastBatchSentPosition + 1].excludedFiles[i])
this.currentBatchSize += this.getCurrentBatchFiles()[i].size;
}
};
Uploader.prototype.computeSentFilesSize = function () {
var result = 0;
for (var i = 0; i < this.lastFileSentPosition + 1; i++) {
if (!this.fileBatches[this.lastBatchSentPosition + 1].excludedFiles[i])
result += this.getCurrentBatchFiles()[i].size;
}
return result;
};
Uploader.prototype.notifyUploadStart = function () {
if (!this.isUploading) {
this.isUploading = true;
var mainApp = getMainApplication();
if (mainApp) {
mainApp.notifyUploadStart();
}
}
};
Uploader.prototype.sendAllFilesSuccess = function () {
this.isUploading = false;
var mainApp = getMainApplication();
if (mainApp) {
mainApp.uploadFilesDone();
}
};
Uploader.prototype.setUrlIdsToWaitingFiles = function (urlIds) {
if (urlIds.length != this.waitingFiles.length) {
var mainApp = getMainApplication();
if (mainApp) {
mainApp.notifyUploadBatchError(this.fileBatches.length);
}
return;
}
var newFileBatch = new FileBatch(this.waitingFiles, urlIds);
this.fileBatches.push(newFileBatch);
if (!this.isUploading) {
this.sendNextBatchIfExist();
}
};
Uploader.prototype.removeUploadFile = function (filePosition, batchPosition) {
this.excludeFile(filePosition, batchPosition);
if (filePosition == this.lastFileSentPosition + 1 && batchPosition == this.lastBatchSentPosition + 1) {
this.fileUploader.cancelUpload();
this.sendNextFileIfExist();
} else {
}
this.updateProgress(this.sizeCurrentFileSent);
};
Uploader.prototype.updateProgress = function (bytesSentCurrentFile) {
this.sizeCurrentFileSent = bytesSentCurrentFile;
var progressBatch = Math.round((this.sizeCurrentFileSent + this.sizeFilesSentComplete) * 100 / this.currentBatchSize);
var progressFile = Math.round(this.sizeCurrentFileSent * 100 / this.getCurrentBatchFiles()[this.lastFileSentPosition + 1].size);
this.fireProgress(progressBatch, progressFile);
};
Uploader.prototype.fireProgress = function (batchProgress, fileProgress) {
var mainApp = getMainApplication();
if (mainApp) {
mainApp.updateUploadProgress(batchProgress, fileProgress, this.lastFileSentPosition + 1, this.lastBatchSentPosition + 1);
}
};
Uploader.prototype.cancelUpload = function () {
this.isUploading = false;
this.fileUploader.cancelUpload();
};
Uploader.MEGABYTE = 1024 * 1024;
Uploader.CHUNK_SIZE = Uploader.MEGABYTE;
Uploader.MAX_FILE_SIZE = 300 * Uploader.MEGABYTE;
return Uploader;
})();
var FileUploader = (function () {
function FileUploader(file, uploader, urlId) {
var _this = this;
this.lastByteSentBeforeCurrentChunk = -1;
this.retryCount = 0;
this.isPausing = false;
this.onXhrStart = function (evt) {
if (_this.uploader.isUploading) {
} else {
_this.uploader.notifyUploadStart();
}
};
this.onXhrLoadEnd = function (evt) {
};
this.onXhrLoad = function (evt) {
_this.handleXhrStatus();
};
this.onXhrError = function (evt) {
_this.handleXhrStatus();
};
this.onXhrProgress = function (evt) {
var bytesSent = _this.lastByteSentBeforeCurrentChunk + evt.loaded;
_this.uploader.updateProgress(bytesSent);
};
this.onXhrAbort = function (evt) {
};
this.onXhrStateChange = function (evt) {
};
this.file = file;
this.uploader = uploader;
this.urlId = parseInt(urlId);
}
FileUploader.prototype.cancelUpload = function () {
if (this.xhr) {
this.xhr.abort();
clearInterval(this.restarter);
}
};
FileUploader.prototype.reset = function (file) {
this.file = file;
this.lastByteSentBeforeCurrentChunk = -1;
clearInterval(this.restarter);
};
FileUploader.prototype.upload = function () {
this.uploader.updateProgress(0);
this.sendNextFileChunk();
};
FileUploader.prototype.makeChunk = function (startByte, stopByte) {
startByte = startByte >= 0 ? startByte : 0;
stopByte = stopByte >= startByte ? stopByte : this.file.size - 1;
stopByte = Math.min(stopByte, this.file.size - 1);
var blob;
if (Blob.prototype.slice !== undefined) {
blob = this.file.slice(startByte, stopByte + 1);
} else if (Blob.prototype.webkitSlice !== undefined) {
blob = this.file.webkitSlice(startByte, stopByte + 1);
} else if (Blob.prototype.mozSlice !== undefined) {
blob = this.file.slice(startByte, stopByte + 1);
}
this.currentBlobSize = blob.size;
return blob;
};
FileUploader.prototype.sendNextFileChunk = function () {
if (this.lastByteSentBeforeCurrentChunk > this.file.size - 2) {
return;
}
var start = this.lastByteSentBeforeCurrentChunk + 1;
var nextStop = start + Uploader.CHUNK_SIZE;
if (nextStop > this.file.size - 1) {
nextStop = this.file.size - 1;
}
this.initXHR();
var chunk = this.makeChunk(start, nextStop);
var fd = this.addParamsToChunk(chunk);
this.xhr.send(fd);
};
FileUploader.prototype.initXHR = function () {
this.xhr = new XMLHttpRequest();
this.xhr.onload = this.onXhrLoad;
this.xhr.onloadend = this.onXhrLoadEnd;
this.xhr.onerror = this.onXhrError;
this.xhr.upload.onprogress = this.onXhrProgress;
this.xhr.onloadstart = this.onXhrStart;
this.xhr.onabort = this.onXhrAbort;
this.xhr.onreadystatechange = this.onXhrStateChange;
this.xhr.open('POST', this.uploader.upload_url);
};
FileUploader.prototype.addParamsToChunk = function (chunk) {
var fd = new FormData();
fd.append('urlId', this.urlId.toString());
fd.append('size', this.file.size.toString());
fd.append('position', (this.lastByteSentBeforeCurrentChunk + 1).toString());
fd.append('content', chunk);
return fd;
};
FileUploader.prototype.handleXhrStatus = function () {
var uploader = Uploader.getInstance();
if (this.xhr.status == 200) {
this.lastByteSentBeforeCurrentChunk += this.currentBlobSize;
this.uploader.updateProgress(this.lastByteSentBeforeCurrentChunk + 1);
if (this.lastByteSentBeforeCurrentChunk > this.file.size - 2) {
this.sendFileSuccess();
} else {
this.sendNextFileChunk();
}
} else if (this.xhr.status == 400) {
cancelUpload();
uploader.sendCurrentFileError();
} else if (this.xhr.status == 409) {
this.isPausing = true;
this.tryToRestartUploadingPeriodically();
} else {
this.isPausing = true;
this.tryToRestartUploadingPeriodically();
}
};
FileUploader.prototype.checkUploadStatusFromServer = function () {
var _this = this;
var uploader = Uploader.getInstance();
var uploadStatusRequest = new XMLHttpRequest();
uploadStatusRequest.open("GET", uploader.uploadStatus_url + "?urlId=" + this.urlId.toString());
try {
uploadStatusRequest.send();
var that = this;
uploadStatusRequest.onloadend = function (evt) {
if (_this.isPausing) {
var hasConnection = uploadStatusRequest.status >= 200 && uploadStatusRequest.status < 300 || uploadStatusRequest.status === 304;
if (hasConnection) {
var json = JSON.parse(uploadStatusRequest.responseText);
var uploadStatus = json["FILE_CREATION_STATUS"];
if (uploadStatus == 0) {
var filePosition = json["FILE_POSITION"];
_this.lastByteSentBeforeCurrentChunk = filePosition - 1;
_this.checkSuccess();
} else if (uploadStatus == 1) {
_this.uploader.cancelUpload();
_this.uploader.sendCurrentFileError();
} else if (uploadStatus == 2) {
_this.checkAgain();
}
} else {
_this.checkAgain();
}
}
};
} catch (error) {
this.checkAgain();
}
};
FileUploader.prototype.checkSuccess = function () {
clearInterval(this.restarter);
this.resumeUploading();
this.retryCount = 0;
};
FileUploader.prototype.checkAgain = function () {
this.retryCount++;
};
FileUploader.prototype.tryToRestartUploadingPeriodically = function () {
var that = this;
this.restarter = setInterval(function () {
that.checkUploadStatusFromServer();
}, 3000);
};
FileUploader.prototype.resumeUploading = function () {
if (this.isPausing) {
this.isPausing = false;
this.uploader.updateProgress(this.lastByteSentBeforeCurrentChunk + 1);
this.sendNextFileChunk();
}
};
FileUploader.prototype.sendFileSuccess = function () {
this.uploader.sendCurrentFileSuccess();
};
FileUploader.MAX_RETRY_ACCEPTED = 120;
return FileUploader;
})();
var FileInfo = (function () {
function FileInfo(fileName, fileSize) {
this.fileName = fileName;
this.fileSize = fileSize;
}
FileInfo.makeFileInfoArray = function (fl) {
var result = [];
for (var i = 0; i < fl.length; i++) {
var file = fl[i];
result[i] = new FileInfo(file.name, file.size);
}
return result;
};
FileInfo.makeFileInfo = function (f) {
var fileInfo = new FileInfo(f.name, f.size);
return fileInfo;
};
return FileInfo;
})();
function refreshFileSelectorInHtml() {
var fileSelector = document.getElementById("fileSelector");
if (fileSelector) {
fileSelector.parentNode.removeChild(fileSelector);
}
fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.setAttribute('id', 'fileSelector');
fileSelector.setAttribute('multiple', 'multiple');
fileSelector.setAttribute('width', '1000');
fileSelector.setAttribute('height', '1000');
fileSelector.setAttribute('top', '0');
fileSelector.setAttribute('left', '0');
UploadHelper.getHTMLContainer().appendChild(fileSelector);
}
function uploadDocuments() {
Uploader.getInstance().openFileSelector();
}
function applyUrlIdToUploadingFiles(urlIds) {
var uploader = Uploader.getInstance();
uploader.setUrlIdsToWaitingFiles(urlIds);
}
function cancelUpload() {
var uploader = Uploader.getInstance();
if (uploader) {
uploader.cancelUpload();
}
}
function removeUploadFile(filePosition, batchPosition) {
var uploader = Uploader.getInstance();
uploader.removeUploadFile(filePosition, batchPosition);
}
function listenToFireFoxAddonInstallation() {
if (window.addEventListener !== undefined) {
window.addEventListener('addonPearltreesInstalled', function() { notifyAddonInstalledFF() });
}
}
function notifyAddonInstalledFF() {
var app = getMainApplication();
if(app) {
app.notifyAddonInstalledFF();
}
}
function isBrowserMSIEMetro() {
return isBrowserMSIE() && getBrowserVersion() > 9 && !isActivexSupported();
}
function isActivexSupported() {
var supported = null;
try {
new ActiveXObject("");
}
catch (e) {
errorName = e.name;
}
try {
supported = !!new ActiveXObject("htmlfile");
} catch (e) {
supported = false;
}
if(errorName != 'ReferenceError' && supported==false){
supported = false;
}else{
supported = true;
}
return supported;
}
function openAlert(message) {
alert(message);
} |
import React from 'react';
import DataProcessor from './DataProcessor';
export default class SparklinesReferenceLine extends React.Component {
static propTypes = {
type: React.PropTypes.oneOf(['max', 'min', 'mean', 'avg', 'median']),
style: React.PropTypes.object
};
static defaultProps = {
type: 'mean',
style: { stroke: 'red', strokeOpacity: .75, strokeDasharray: '2, 2' }
};
render() {
const { points, margin, type, style } = this.props;
const ypoints = points.map(p => p.y);
const y = DataProcessor.calculateFromData(ypoints, type);
return (
<line
x1={points[0].x} y1={y + margin}
x2={points[points.length - 1].x} y2={y + margin}
style={style} />
)
}
}
|
/* skel-viewport.js v3.0.0-dev | (c) n33 | skel.io | MIT licensed */
(function(_) { "use strict"; var __ = {
/******************************/
/* Properties */
/******************************/
/**
* Default config.
* @type {object}
*/
config: {
// Width.
width: 'device-width',
// Height.
height: '',
// Scalable?
scalable: true,
// Breakpoints.
breakpoints: {}
},
/******************************/
/* Methods */
/******************************/
/**
* Initializes Viewport module.
* @param {object} config Config.
*/
init: function(config) {
// Extend with user config.
_.extend(__.config, config);
// Add state handler.
_.addStateHandler('viewport', __.stateHandler);
// Add initial <meta> element.
_.attach(_.newAttachment(
'mv',
__.newViewportMeta('initial-scale=1'),
1,
true
));
// Hack: IE viewport fix.
if (_.vars.browser == 'ie'
&& _.vars.IEVersion >= 10) {
// Add <style> element for -ms-viewport.
_.attach(_.newAttachment(
'mVie',
_.newStyle('@-ms-viewport{width:device-width}'),
1,
true
));
// Force browser to accept new viewport.
window.setTimeout(function() {
var body = document.getElementsByTagName('body')[0],
h = body.style.height;
body.style.height = '10000px';
window.setTimeout(function() {
body.style.height = h;
}, 250);
}, 250);
}
return _;
},
/**
* Creates a new viewport <meta> element.
* @param {string} content Content.
* @return {DOMElement} Viewport <meta> element.
*/
newViewportMeta: function(content) {
var e = document.createElement('meta');
e.name = 'viewport';
e.content = content;
return e;
},
/**
* State handler.
* @return {array} Attachments.
*/
stateHandler: function() {
var attachment, config,
a;
// Generate state config.
config = _.generateStateConfig(
{
width: __.config.width,
height: __.config.height,
scalable: __.config.scalable
},
__.config.breakpoints
);
// Create <meta> element attachment.
// Content.
a = [];
// Scalable.
a.push('user-scalable=' + (config.scalable ? 'yes' : 'no'));
// Width.
if (config.width)
a.push('width=' + config.width);
// Height.
if (config.height)
a.push('height=' + config.height);
// Set initial scale if we're using device-width.
if (config.width == 'device-width')
a.push('initial-scale=1');
// Attachment.
attachment = _.newAttachment(
'mv-' + _.stateId,
__.newViewportMeta(a.join(',')),
1
);
return [attachment];
}
}; _.viewport = __.init; })(skel); |
import { equals, stringMaker, valueOf } from './data_structure_util';
/**
* @signature
* @description d
* @namespace Reader
* @memberOf dataStructures
* @property {function} of
* @param {function} run - a
* @return {dataStructures.reader} - b
*/
function Reader(run) {
return Object.create(reader, {
run: {
value: run
}
});
}
/**
* @signature
* @description d
* @memberOf dataStructures.Reader
* @param {*} val - a
* @return {dataStructures.reader} - b
*/
Reader.of = function _of(val) {
return Reader(constant(val));
};
/**
* @description d
* @memberOf dataStructures
*/
var reader = {
chain: function _chain(f) {
return Reader(e => f(this.run(e)).run(e));
},
map: function _map(f) {
return this.chain(a => Reader.of(f(a)));
},
apply: function _apply(m) {
return this.chain(f => m.map(f));
},
get [Symbol.toStringTag]() {
return 'Reader';
}
}; |
'use strict';
//Stats service used for stats REST endpoint
angular.module('mean.stats').factory('Stats', ['$resource', function($resource) {
var stats = $resource('/stats/:roomId/:cmd',
{roomId:'@id'},
{
rooms: {method: 'GET', params:{cmd: 'rooms'}, isArray: true},
roomsbytype: {method: 'GET', params:{cmd: 'roomsbytype'}, isArray: true},
webrtcstats: {method: 'GET', params:{cmd: 'webrtcstats'}}
});
var statsFactory = {};
statsFactory.rooms = function(cb) {
stats.rooms({},cb);
};
statsFactory.roomsbytype = function(cb) {
stats.roomsbytype({},cb);
};
statsFactory.webrtcstats = function(roomId,cb) {
stats.webrtcstats({roomId:roomId},cb);
};
return statsFactory;
}]);
|
var searchData=
[
['getting_20started',['Getting started',['../getting_started_ref.html',1,'']]],
['groups',['groups',['../md_groups.html',1,'']]]
];
|
(function() {
var HolyCarousel;
$.fn.tojqa = function() {
var arr, i;
arr = new Array(this.length);
i = 0;
this.each(function() {
return arr[i++] = $(this);
});
return arr;
};
HolyCarousel = {
_HOLY_RAIL_HTML: '<div class="holy-rail" style="margin-left: 0; width:9999%; margin-left: 0;"></div>',
init: function(opts) {
this.each(function() {
var $slides, $this, data, slides;
$this = $(this);
this.className += ' holycarousel';
data = $this.data('holycarousel');
$slides = $this.children();
$slides.wrapAll(HolyCarousel._HOLY_RAIL_HTML);
slides = $slides.tojqa();
$slides.width($this.width());
if (!data) {
$this.data('holycarousel', {
opts: $.extend({}, {
animationTime: 200,
altSlides: null,
responsive: true,
alterHeight: false,
pagerItemText: null,
altSlideWrapper: '<div class="alt-item"></div>'
}, opts),
slides: slides,
currentIndex: 0,
pagerItemSets: [],
altCarousels: []
});
}
data = $this.data('holycarousel');
opts = opts || data.opts;
if (opts.responsive) {
$(window).resize(function() {
return HolyCarousel.respond.apply($this, arguments);
});
if (opts.alterHeight) {
return $this.height(slides[0].outerHeight(true));
}
}
});
return this;
},
respond: function() {
var altCarousel, currentIndex, data, innerWidth, marginLeft, outerSpace, slide, slides, _i, _j, _k, _len, _len1, _len2, _ref, _ref1;
data = this.data('holycarousel');
slides = data.slides;
currentIndex = data.currentIndex;
outerSpace = slides[0].outerWidth(true) - slides[0].width();
innerWidth = this.width();
for (_i = 0, _len = slides.length; _i < _len; _i++) {
slide = slides[_i];
slide[0].style.width = "" + innerWidth + "px";
}
marginLeft = -Math.abs(slides[data.currentIndex].position().left);
$('.holy-rail', this).css('margin-left', "" + marginLeft + "px");
if (data.opts.alterHeight) {
this.height(slides[currentIndex].outerHeight(true));
}
_ref = data.altCarousels;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
altCarousel = _ref[_j];
innerWidth = altCarousel.container.width();
_ref1 = altCarousel.slides;
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
slide = _ref1[_k];
slide[0].style.width = innerWidth + 'px';
}
marginLeft = -Math.abs(altCarousel.slides[currentIndex].position().left);
altCarousel.rail.css('margin-left', "" + marginLeft + "px");
}
return this;
},
slideTo: function(targetIndex) {
var altCarousel, currentHeight, currentIndex, data, high, i, low, marginLeft, maxHeight, numPagerItems, opts, pagerItem, pagerItemSet, self, slides, _base, _i, _j, _k, _l, _len, _len1, _ref, _ref1, _ref2;
self = this;
data = this.data('holycarousel');
opts = data.opts;
slides = data.slides;
if (typeof (_base = data.opts).beforeSlide === "function") {
_base.beforeSlide(self, targetIndex);
}
currentIndex = data.currentIndex;
marginLeft = -Math.abs(slides[targetIndex].position().left);
if (data.opts.alterHeight) {
high = Math.max(currentIndex, targetIndex);
low = Math.min(currentIndex, targetIndex);
maxHeight = 0;
for (i = _i = low; _i <= high; i = _i += 1) {
currentHeight = slides[i].outerHeight(true);
if (currentHeight > maxHeight) {
maxHeight = currentHeight;
}
}
this.height(maxHeight);
}
$('.holy-rail', this).animate({
marginLeft: marginLeft
}, opts.animationTime, function() {
var _ref;
if (data != null) {
if ((_ref = data.opts) != null) {
if (typeof _ref.afterSlide === "function") {
_ref.afterSlide(self, data.currentIndex);
}
}
}
if (data.opts.alterHeight) {
return self.height(slides[targetIndex].outerHeight(true));
}
});
_ref = data.altCarousels;
for (_j = 0, _len = _ref.length; _j < _len; _j++) {
altCarousel = _ref[_j];
marginLeft = -Math.abs(altCarousel.slides[targetIndex].position().left);
altCarousel.rail.animate({
marginLeft: marginLeft
}, opts.animationTime);
}
if ((data.pagerItemSets != null) && data.pagerItemSets.length) {
numPagerItems = data.pagerItemSets[0].length;
_ref1 = data.pagerItemSets;
for (_k = 0, _len1 = _ref1.length; _k < _len1; _k++) {
pagerItemSet = _ref1[_k];
for (i = _l = 0, _ref2 = numPagerItems - 1; _l <= _ref2; i = _l += 1) {
pagerItem = pagerItemSet[i];
if (i === targetIndex) {
pagerItem.addClass('active');
} else {
pagerItem.removeClass('active');
}
}
}
}
data.currentIndex = targetIndex;
return this;
},
next: function() {
var data;
data = this.data('holycarousel');
HolyCarousel.slideTo.apply(this, [(data.currentIndex + 1) % data.slides.length]);
return this;
},
prev: function() {
var currentIndex, data, numSlides, targetIndex;
data = this.data('holycarousel');
currentIndex = data.currentIndex;
if (currentIndex === 0) {
numSlides = data.slides.length;
targetIndex = numSlides - 1;
} else {
currentIndex = data.currentIndex;
targetIndex = currentIndex - 1;
}
HolyCarousel.slideTo.apply(this, [targetIndex]);
return this;
},
generate: function(controlName) {
var control;
switch (controlName) {
case 'pager':
control = HolyCarousel._generatePager.apply(this, Array.prototype.slice.call(arguments, 1));
break;
case 'next-button':
control = HolyCarousel._generateNextButton.apply(this, Array.prototype.slice.call(arguments, 1));
break;
case 'prev-button':
control = HolyCarousel._generatePrevButton.apply(this, Array.prototype.slice.call(arguments, 1));
break;
case 'carousel':
control = HolyCarousel._generateAltCarousel.apply(this, Array.prototype.slice.call(arguments, 1));
}
return control;
},
_generatePager: function() {
var currentIndex, data, i, numSlides, opts, pager, pagerItem, pagerItems, self, _i, _ref;
self = this;
pager = $('<span class="holycarousel pager"></span>');
data = this.data('holycarousel');
opts = data.opts;
currentIndex = data.currentIndex;
numSlides = data.slides.length;
pagerItems = [];
for (i = _i = 0, _ref = numSlides - 1; _i <= _ref; i = _i += 1) {
pagerItems.push(pagerItem = $('<span class="holycarousel pager-item"></span>'));
if (i === currentIndex) {
pagerItem.addClass('active');
}
if (opts.pagerItemText === null) {
pagerItem.html("" + (i + 1));
} else {
pagerItem.html(opts.pagerItemText);
}
pagerItem.click({
i: i
}, function(e) {
return HolyCarousel.slideTo.apply(self, [e.data.i]);
});
pager.append(pagerItem);
}
data.pagerItemSets.push(pagerItems);
this.data('holycarousel', data);
return pager;
},
_generateAltCarousel: function(options) {
var $carousel, $holyRail, altCarousel, currentIndex, data, newSlide, newSlideContent, newSlideContents, newSlides, numSlides, opts, self, _i, _len;
self = this;
$carousel = $('<div class="holycarousel"></div>');
$holyRail = $(HolyCarousel._HOLY_RAIL_HTML);
data = this.data('holycarousel');
opts = $.extend({}, data.opts, options);
currentIndex = data.currentIndex;
newSlideContents = options.altSlides;
numSlides = newSlideContents.length;
newSlides = [];
for (_i = 0, _len = newSlideContents.length; _i < _len; _i++) {
newSlideContent = newSlideContents[_i];
newSlide = $(opts.altSlideWrapper).html(newSlideContent ? newSlideContent : '');
$holyRail.append(newSlide);
newSlides.push(newSlide);
}
$carousel.append($holyRail);
data.altCarousels.push(altCarousel = {
slides: newSlides,
container: $carousel,
rail: $holyRail
});
this.data('holycarousel', data);
return $carousel;
},
_generateNextButton: function() {
var nextBtn, self;
self = this;
nextBtn = $('<span class="holycarousel next"></span>');
return nextBtn.click(function() {
return HolyCarousel.next.apply(self, []);
});
},
_generatePrevButton: function() {
var prevBtn, self;
self = this;
prevBtn = $('<span class="holycarousel prev"></span>');
return prevBtn.click(function() {
return HolyCarousel.prev.apply(self, []);
});
}
};
jQuery.fn.holycarousel = jQuery.fn.holyCarousel = $.fn.holycarousel = $.fn.holyCarousel = function(method) {
if (HolyCarousel[method]) {
return HolyCarousel[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return HolyCarousel.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.holyCarousel');
}
return this;
};
}).call(this);
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M6 12c0-4.41 3.59-8 8-8 .34 0 .68.02 1.01.07C13.1 6.23 12 9.05 12 12s1.1 5.77 3.01 7.93c-.33.05-.67.07-1.01.07-4.41 0-8-3.59-8-8z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M14 12c0-3.7 2.01-6.92 5-8.65C17.53 2.5 15.82 2 14 2 8.48 2 4 6.48 4 12s4.48 10 10 10c1.82 0 3.53-.5 5-1.35-2.99-1.73-5-4.95-5-8.65zm1.01 7.93c-.33.05-.67.07-1.01.07-4.41 0-8-3.59-8-8s3.59-8 8-8c.34 0 .68.02 1.01.07C13.1 6.23 12 9.05 12 12s1.1 5.77 3.01 7.93z"
}, "1")], 'NightlightTwoTone');
exports.default = _default; |
module.exports = Set;
function Set(set) {
this.set = {};
this.infContains = function () { return true; };
if (typeof set == 'object') {
if (set instanceof Array)
for (var i = 0; i < set.length; i++)
this.set[set[i]] = true;
else
this.set = set;
} else if (typeof set == 'function') {
this.infContains = set;
} else if (typeof set != 'undefined')
throw new Error('set must be either an array or an object.');
}
Set.prototype.contains = function contains(val) {
return this.set[val] ? true : false && this.infContains(val);
};
Set.prototype.has = Set.prototype.contains;
Set.prototype.add = function add(val) {
if (arguments.length == 1)
this.set[val] = true;
else
for (var i = 0; i < arguments.length; i++)
this.set[arguments[i]] = true;
};
Set.prototype.addAll = function addAll(arr) {
if (typeof arr != 'object' && !(arr instanceof Array))
throw new Error('arr must be an array.');
for (var i = 0; i < arr.length; i++)
this.add(arr[i]);
}
Set.prototype.remove = function remove(val) {
if (arguments.length == 1)
delete this.set[val];
else
for (var i = 0; i < arguments.length; i++)
delete this.set[arguments[i]];
};
Set.prototype['delete'] = Set.prototype.remove;
Set.prototype.clear = function clear() {
this.set = {};
};
Set.prototype.size = function size() {
return Object.keys(this.set).length;
};
Set.prototype.toString = function toString() {
return '{'+Object.keys(this.set).toString()+'}';
};
Set.prototype.toArray = function toArray() {
if (typeof this.set == 'undefined')
return [];
return Object.keys(this.set);
};
Set.prototype['*values'] = Set.prototype.toArray;
|
/** @global {Jymfony.Component.DependencyInjection.ContainerBuilder} container */
const ChildDefinition = Jymfony.Component.DependencyInjection.ChildDefinition;
const Container = Jymfony.Component.DependencyInjection.Container;
const Reference = Jymfony.Component.DependencyInjection.Reference;
container.register(Jymfony.Component.HttpFoundation.Controller.ControllerResolverInterface, Jymfony.Component.HttpFoundation.Controller.ContainerControllerResolver)
.addArgument(new Reference('service_container'))
.addArgument(new Reference('logger', Container.IGNORE_ON_INVALID_REFERENCE))
;
container.register('argument_metadata_factory', Jymfony.Component.HttpServer.Controller.Metadata.ArgumentMetadataFactory);
container.register('argument_resolver', Jymfony.Component.HttpServer.Controller.ArgumentResolver)
.addArgument(new Reference('argument_metadata_factory'))
.addArgument([])
;
container.register('argument_resolver.request_attribute', Jymfony.Component.HttpServer.Controller.ArgumentResolvers.RequestAttributeValueResolver)
.addTag('controller.argument_value_resolver', { priority: 100 })
;
container.register('argument_resolver.request', Jymfony.Component.HttpServer.Controller.ArgumentResolvers.RequestValueResolver)
.addTag('controller.argument_value_resolver', { priority: 50 })
;
container.register('argument_resolver.session', Jymfony.Component.HttpServer.Controller.ArgumentResolvers.SessionValueResolver)
.addTag('controller.argument_value_resolver', { priority: 50 })
;
container.register('argument_resolver.service', Jymfony.Component.HttpServer.Controller.ArgumentResolvers.ServiceValueResolver)
.addArgument()
.addTag('controller.argument_value_resolver', { priority: -50 })
;
container.register('argument_resolver.default', Jymfony.Component.HttpServer.Controller.ArgumentResolvers.DefaultValueResolver)
.addTag('controller.argument_value_resolver', { priority: -100 })
;
container.register('argument_resolver.variadic', Jymfony.Component.HttpServer.Controller.ArgumentResolvers.VariadicValueResolver)
.addTag('controller.argument_value_resolver', { priority: -150 })
;
container.register(Jymfony.Component.HttpServer.RequestHandler)
.setAbstract(true)
.addArgument(new Reference('event_dispatcher'))
.addArgument(new Reference(Jymfony.Component.HttpFoundation.Controller.ControllerResolverInterface))
.addArgument(new Reference('argument_resolver'))
.addMethodCall('setLogger', [ new Reference('logger', Container.IGNORE_ON_INVALID_REFERENCE) ])
;
container.setDefinition(Jymfony.Component.HttpServer.HttpServer, new ChildDefinition(Jymfony.Component.HttpServer.RequestHandler))
.setClass(Jymfony.Component.HttpServer.HttpServer)
.setPublic(true)
;
container.register('kernel.exception_controller', Jymfony.Bundle.FrameworkBundle.Controller.ExceptionController)
.setPublic(true)
.addArgument('%kernel.debug%')
.addArgument(new Reference('error_handler.html'))
;
container.register(Jymfony.Component.HttpServer.EventListener.UnhandledRejectionListener)
.addTag('kernel.event_subscriber')
.addArgument(new Reference('logger', Container.IGNORE_ON_INVALID_REFERENCE))
.addArgument('%kernel.debug%')
;
container.register(Jymfony.Component.HttpServer.EventListener.ExceptionListener)
.addTag('kernel.event_subscriber')
.addArgument('kernel.exception_controller:showAction')
.addArgument(new Reference('logger', Container.IGNORE_ON_INVALID_REFERENCE))
.addArgument('%kernel.debug%')
;
container.register(Jymfony.Component.HttpServer.EventListener.RouterListener)
.addTag('kernel.event_subscriber')
.addTag('jymfony.logger', { channel: 'request' })
.addArgument(new Reference('router'))
.addArgument(new Reference('logger', Container.IGNORE_ON_INVALID_REFERENCE))
.addArgument('%kernel.project_dir%')
.addArgument('%kernel.debug%')
;
container.register(Jymfony.Component.HttpServer.Command.HttpServerRunCommand)
.addTag('console.command')
.addArgument(new Reference(Jymfony.Component.HttpServer.HttpServer))
;
container.register(Jymfony.Component.HttpServer.EventListener.WebsocketListener)
.addTag('kernel.event_subscriber')
;
container.setDefinition(Jymfony.Component.HttpServer.Serverless.AwsLambdaHandler, new ChildDefinition(Jymfony.Component.HttpServer.RequestHandler))
.setClass(Jymfony.Component.HttpServer.Serverless.AwsLambdaHandler)
.setPublic(true)
;
|
const $rdf = require('rdflib')
const SOLID = $rdf.Namespace('http://www.w3.org/ns/solid/terms#')
const VCARD = $rdf.Namespace('http://www.w3.org/2006/vcard/ns#')
module.exports.getName = getName
module.exports.getWebId = getWebId
module.exports.isValidUsername = isValidUsername
async function getName (webId, fetchGraph) {
const graph = await fetchGraph(webId)
const nameNode = graph.any($rdf.sym(webId), VCARD('fn'))
return nameNode.value
}
async function getWebId (accountDirectory, accountUrl, suffixMeta, fetchData) {
const metaFilePath = `${accountDirectory}/${suffixMeta}`
const metaFileUri = `${accountUrl}${suffixMeta}`
const metaData = await fetchData(metaFilePath)
const metaGraph = $rdf.graph()
$rdf.parse(metaData, metaGraph, metaFileUri, 'text/turtle')
const webIdNode = metaGraph.any(undefined, SOLID('account'), $rdf.sym(accountUrl))
return webIdNode.value
}
function isValidUsername (username) {
return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(username)
}
|
/**
* @author Ed Spencer
* TabBar is used internally by a {@link Ext.tab.Panel TabPanel} and typically should not need to be created manually.
* The tab bar automatically removes the default title provided by {@link Ext.panel.Header}
*/
Ext.define('Ext.tab.Bar', {
extend: 'Ext.panel.Header',
alias: 'widget.tabbar',
baseCls: Ext.baseCSSPrefix + 'tab-bar',
requires: ['Ext.tab.Tab'],
/**
* @property {Boolean} isTabBar
* `true` in this class to identify an objact as an instantiated Tab Bar, or subclass thereof.
*/
isTabBar: true,
/**
* @cfg {String} title @hide
*/
/**
* @cfg {String} iconCls @hide
*/
// @private
defaultType: 'tab',
/**
* @cfg {Boolean} plain
* True to not show the full background on the tabbar
*/
plain: false,
childEls: [
'body', 'strip'
],
// @private
renderTpl: [
'<div id="{id}-body" class="{baseCls}-body {bodyCls}<tpl if="ui"> {baseCls}-body-{ui}<tpl for="uiCls"> {parent.baseCls}-body-{parent.ui}-{.}</tpl></tpl>"<tpl if="bodyStyle"> style="{bodyStyle}"</tpl>>',
'{%this.renderContainer(out,values)%}',
'</div>',
'<div id="{id}-strip" class="{baseCls}-strip<tpl if="ui"> {baseCls}-strip-{ui}<tpl for="uiCls"> {parent.baseCls}-strip-{parent.ui}-{.}</tpl></tpl>"></div>'
],
/**
* @cfg {Number} minTabWidth
* The minimum width for a tab in this tab Bar. Defaults to the tab Panel's {@link Ext.tab.Panel#minTabWidth minTabWidth} value.
* @deprecated This config is deprecated. It is much easier to use the {@link Ext.tab.Panel#minTabWidth minTabWidth} config on the TabPanel.
*/
/**
* @cfg {Number} maxTabWidth
* The maximum width for a tab in this tab Bar. Defaults to the tab Panel's {@link Ext.tab.Panel#maxTabWidth maxTabWidth} value.
* @deprecated This config is deprecated. It is much easier to use the {@link Ext.tab.Panel#maxTabWidth maxTabWidth} config on the TabPanel.
*/
// @private
initComponent: function() {
var me = this;
if (me.plain) {
me.setUI(me.ui + '-plain');
}
me.addClsWithUI(me.dock);
me.addEvents(
/**
* @event change
* Fired when the currently-active tab has changed
* @param {Ext.tab.Bar} tabBar The TabBar
* @param {Ext.tab.Tab} tab The new Tab
* @param {Ext.Component} card The card that was just shown in the TabPanel
*/
'change'
);
// Element onClick listener added by Header base class
me.callParent(arguments);
Ext.merge(me.layout, me.initialConfig.layout);
// TabBar must override the Header's align setting.
me.layout.align = (me.orientation == 'vertical') ? 'left' : 'top';
me.layout.overflowHandler = new Ext.layout.container.boxOverflow.Scroller(me.layout);
me.remove(me.titleCmp);
delete me.titleCmp;
Ext.apply(me.renderData, {
bodyCls: me.bodyCls
});
},
getLayout: function() {
var me = this;
me.layout.type = (me.dock === 'top' || me.dock === 'bottom') ? 'hbox' : 'vbox';
return me.callParent(arguments);
},
// @private
onAdd: function(tab) {
tab.position = this.dock;
this.callParent(arguments);
},
onRemove: function(tab) {
var me = this;
if (tab === me.previousTab) {
me.previousTab = null;
}
me.callParent(arguments);
},
afterComponentLayout : function(width) {
var me = this,
needsScroll = me.needsScroll;
me.callParent(arguments);
me.strip.setWidth(width);
if (needsScroll) {
me.layout.overflowHandler.scrollToItem(me.activeTab);
}
delete me.needsScroll;
},
// @private
onClick: function(e, target) {
// The target might not be a valid tab el.
var me = this,
tabEl = e.getTarget('.' + Ext.tab.Tab.prototype.baseCls),
tab = tabEl && Ext.getCmp(tabEl.id),
tabPanel = me.tabPanel,
isCloseClick = tab && tab.closeEl && (target === tab.closeEl.dom);
if (isCloseClick) {
e.preventDefault();
}
if (tab && tab.isDisabled && !tab.isDisabled()) {
if (tab.closable && isCloseClick) {
tab.onCloseClick();
} else {
if (tabPanel) {
// TabPanel will card setActiveTab of the TabBar
tabPanel.setActiveTab(tab.card);
} else {
me.setActiveTab(tab);
}
tab.focus();
}
}
},
/**
* @private
* Closes the given tab by removing it from the TabBar and removing the corresponding card from the TabPanel
* @param {Ext.tab.Tab} toClose The tab to close
*/
closeTab: function(toClose) {
var me = this,
card = toClose.card,
tabPanel = me.tabPanel,
toActivate;
if (card && card.fireEvent('beforeclose', card) === false) {
return false;
}
// If we are closing the active tab, revert to the previously active tab (or the previous or next enabled sibling if
// there *is* no previously active tab, or the previously active tab is the one that's being closed or the previously
// active tab has since been disabled)
toActivate = me.findNextActivatable(toClose);
// We are going to remove the associated card, and then, if that was sucessful, remove the Tab,
// And then potentially activate another Tab. We should not layout for each of these operations.
Ext.suspendLayouts();
if (tabPanel && card) {
// Remove the ownerCt so the tab doesn't get destroyed if the remove is successful
// We need this so we can have the tab fire it's own close event.
delete toClose.ownerCt;
// we must fire 'close' before removing the card from panel, otherwise
// the event will no loger have any listener
card.fireEvent('close', card);
tabPanel.remove(card);
// Remove succeeded
if (!tabPanel.getComponent(card)) {
/*
* Force the close event to fire. By the time this function returns,
* the tab is already destroyed and all listeners have been purged
* so the tab can't fire itself.
*/
toClose.fireClose();
me.remove(toClose);
} else {
// Restore the ownerCt from above
toClose.ownerCt = me;
Ext.resumeLayouts(true);
return false;
}
}
// If we are closing the active tab, revert to the previously active tab (or the previous sibling or the nnext sibling)
if (toActivate) {
// Our owning TabPanel calls our setActiveTab method, so only call that if this Bar is being used
// in some other context (unlikely)
if (tabPanel) {
tabPanel.setActiveTab(toActivate.card);
} else {
me.setActiveTab(toActivate);
}
toActivate.focus();
}
Ext.resumeLayouts(true);
},
// private - used by TabPanel too.
// Works out the next tab to activate when one tab is closed.
findNextActivatable: function(toClose) {
var me = this;
if (toClose.active && me.items.getCount() > 1) {
return (me.previousTab && me.previousTab !== toClose && !me.previousTab.disabled) ? me.previousTab : (toClose.next('tab[disabled=false]') || toClose.prev('tab[disabled=false]'));
}
},
/**
* @private
* Marks the given tab as active
* @param {Ext.tab.Tab} tab The tab to mark active
*/
setActiveTab: function(tab) {
var me = this;
if (!tab.disabled && tab !== me.activeTab) {
if (me.activeTab) {
if (me.activeTab.isDestroyed) {
me.previousTab = null;
} else {
me.previousTab = me.activeTab;
me.activeTab.deactivate();
}
}
tab.activate();
me.activeTab = tab;
me.fireEvent('change', me, tab, tab.card);
// Ensure that after the currently in progress layout, the active tab is scrolled into view
me.needsScroll = true;
me.updateLayout();
}
}
});
|
// Change the select style drop down when a different style image is selected
$(document).on('click', "img[data-style]", function(e) {
var style = $(this).data('style');
$("select option").each(function() {
if ($(this).val() == style) {
$(this).attr('selected','selected');
}
});
}); |
frappe.provide('frappe.data_import');
frappe.data_import.DataExporter = class DataExporter {
constructor(doctype, exporting_for) {
this.doctype = doctype;
this.exporting_for = exporting_for;
frappe.model.with_doctype(doctype, () => {
this.make_dialog();
});
}
make_dialog() {
this.dialog = new frappe.ui.Dialog({
title: __('Export Data'),
fields: [
{
fieldtype: 'Select',
fieldname: 'export_records',
label: __('Export Type'),
options: [
{
label: __('All Records'),
value: 'all'
},
{
label: __('Filtered Records'),
value: 'by_filter'
},
{
label: __('5 Records'),
value: '5_records'
},
{
label: __('Blank Template'),
value: 'blank_template'
}
],
default: this.exporting_for === 'Insert New Records' ? 'blank_template' : 'all',
change: () => {
this.update_record_count_message();
}
},
{
fieldtype: 'HTML',
fieldname: 'filter_area',
depends_on: doc => doc.export_records === 'by_filter'
},
{
fieldtype: 'Select',
fieldname: 'file_type',
label: __('File Type'),
options: ['Excel', 'CSV'],
default: 'CSV'
},
{
fieldtype: 'Section Break'
},
{
fieldtype: 'HTML',
fieldname: 'select_all_buttons'
},
{
label: __(this.doctype),
fieldname: this.doctype,
fieldtype: 'MultiCheck',
columns: 2,
on_change: () => this.update_primary_action(),
options: this.get_multicheck_options(this.doctype)
},
...frappe.meta.get_table_fields(this.doctype).map(df => {
let doctype = df.options;
let child_fieldname = df.fieldname;
let label = df.reqd
? // prettier-ignore
__('{0} ({1}) (1 row mandatory)', [__(df.label || df.fieldname), __(doctype)])
: __('{0} ({1})', [__(df.label || df.fieldname), __(doctype)]);
return {
label,
fieldname: child_fieldname,
fieldtype: 'MultiCheck',
columns: 2,
on_change: () => this.update_primary_action(),
options: this.get_multicheck_options(doctype, child_fieldname)
};
})
],
primary_action_label: __('Export'),
primary_action: values => this.export_records(values),
on_page_show: () => this.select_mandatory()
});
this.make_filter_area();
this.make_select_all_buttons();
this.update_record_count_message();
this.dialog.show();
}
export_records() {
let method =
'/api/method/frappe.core.doctype.data_import.data_import.download_template';
let multicheck_fields = this.dialog.fields
.filter(df => df.fieldtype === 'MultiCheck')
.map(df => df.fieldname);
let values = this.dialog.get_values();
let doctype_field_map = Object.assign({}, values);
for (let key in doctype_field_map) {
if (!multicheck_fields.includes(key)) {
delete doctype_field_map[key];
}
}
let filters = null;
if (values.export_records === 'by_filter') {
filters = this.get_filters();
}
open_url_post(method, {
doctype: this.doctype,
file_type: values.file_type,
export_records: values.export_records,
export_fields: doctype_field_map,
export_filters: filters
});
}
make_filter_area() {
this.filter_group = new frappe.ui.FilterGroup({
parent: this.dialog.get_field('filter_area').$wrapper,
doctype: this.doctype,
on_change: () => {
this.update_record_count_message();
}
});
}
make_select_all_buttons() {
let for_insert = this.exporting_for === 'Insert New Records';
let section_title = for_insert ? __('Select Fields To Insert') : __('Select Fields To Update');
let $select_all_buttons = $(`
<div>
<h6 class="form-section-heading uppercase">${section_title}</h6>
<button class="btn btn-default btn-xs" data-action="select_all">
${__('Select All')}
</button>
${for_insert ? `<button class="btn btn-default btn-xs" data-action="select_mandatory">
${__('Select Mandatory')}
</button>`: ''}
<button class="btn btn-default btn-xs" data-action="unselect_all">
${__('Unselect All')}
</button>
</div>
`);
frappe.utils.bind_actions_with_object($select_all_buttons, this);
this.dialog
.get_field('select_all_buttons')
.$wrapper.html($select_all_buttons);
}
select_all() {
this.dialog.$wrapper
.find(':checkbox')
.prop('checked', true)
.trigger('change');
}
select_mandatory() {
let mandatory_table_fields = frappe.meta
.get_table_fields(this.doctype)
.filter(df => df.reqd)
.map(df => df.fieldname);
mandatory_table_fields.push(this.doctype);
let multicheck_fields = this.dialog.fields
.filter(df => df.fieldtype === 'MultiCheck')
.map(df => df.fieldname)
.filter(doctype => mandatory_table_fields.includes(doctype));
let checkboxes = [].concat(
...multicheck_fields.map(fieldname => {
let field = this.dialog.get_field(fieldname);
return field.options
.filter(option => option.danger)
.map(option => option.$checkbox.find('input').get(0));
})
);
this.unselect_all();
$(checkboxes)
.prop('checked', true)
.trigger('change');
}
unselect_all() {
let update_existing_records =
this.dialog.get_value('exporting_for') == 'Update Existing Records';
this.dialog.$wrapper
.find(
`:checkbox${update_existing_records ? ':not([data-unit=name])' : ''}`
)
.prop('checked', false)
.trigger('change');
}
update_record_count_message() {
let export_records = this.dialog.get_value('export_records');
let count_method = {
all: () => frappe.db.count(this.doctype),
by_filter: () =>
frappe.db.count(this.doctype, {
filters: this.get_filters()
}),
blank_template: () => Promise.resolve(0),
'5_records': () => Promise.resolve(5)
};
count_method[export_records]().then(value => {
let message = '';
value = parseInt(value, 10);
if (value === 0) {
message = __('No records will be exported');
} else if (value === 1) {
message = __('1 record will be exported');
} else {
message = __('{0} records will be exported', [value]);
}
this.dialog.set_df_property('export_records', 'description', message);
this.update_primary_action(value);
});
}
update_primary_action(no_of_records) {
let $primary_action = this.dialog.get_primary_btn();
if (no_of_records != null) {
let label = '';
if (no_of_records === 0) {
label = __('Export');
} else if (no_of_records === 1) {
label = __('Export 1 record');
} else {
label = __('Export {0} records', [no_of_records]);
}
$primary_action.html(label);
} else {
let parent_fields = this.dialog.get_value(this.doctype);
$primary_action.prop('disabled', parent_fields.length === 0);
}
}
get_filters() {
return this.filter_group.get_filters().map(filter => {
return filter.slice(0, 4);
});
}
get_multicheck_options(doctype, child_fieldname = null) {
if (!this.column_map) {
this.column_map = get_columns_for_picker(this.doctype);
}
let autoname_field = null;
let meta = frappe.get_meta(doctype);
if (meta.autoname && meta.autoname.startsWith('field:')) {
let fieldname = meta.autoname.slice('field:'.length);
autoname_field = frappe.meta.get_field(doctype, fieldname);
}
let fields = child_fieldname
? this.column_map[child_fieldname]
: this.column_map[doctype];
let is_field_mandatory = df => {
if (df.reqd && this.exporting_for == 'Insert New Records') {
return true;
}
if (autoname_field && df.fieldname == autoname_field.fieldname) {
return true;
}
if (df.fieldname === 'name') {
return true;
}
return false;
};
return fields
.filter(df => {
if (autoname_field && df.fieldname === 'name') {
return false;
}
return true;
})
.map(df => {
return {
label: __(df.label),
value: df.fieldname,
danger: is_field_mandatory(df),
checked: false,
description: `${df.fieldname} ${df.reqd ? __('(Mandatory)') : ''}`
};
});
}
};
export function get_columns_for_picker(doctype) {
let out = {};
const exportable_fields = df => {
let keep = true;
if (frappe.model.no_value_type.includes(df.fieldtype)) {
keep = false;
}
if (['lft', 'rgt'].includes(df.fieldname)) {
keep = false;
}
return keep;
};
// parent
let doctype_fields = frappe.meta
.get_docfields(doctype)
.filter(exportable_fields);
out[doctype] = [
{
label: __('ID'),
fieldname: 'name',
fieldtype: 'Data',
reqd: 1
}
].concat(doctype_fields);
// children
const table_fields = frappe.meta.get_table_fields(doctype);
table_fields.forEach(df => {
const cdt = df.options;
const child_table_fields = frappe.meta
.get_docfields(cdt)
.filter(exportable_fields);
out[df.fieldname] = [
{
label: __('ID'),
fieldname: 'name',
fieldtype: 'Data',
reqd: 1
}
].concat(child_table_fields);
});
return out;
}
|
"use strict";
describe("Test", function () {
it("test", function () {
// TODO : Test codes will be written
});
}); |
/**
* Session Configuration
* (sails.config.session)
*
* Sails session integration leans heavily on the great work already done by
* Express, but also unifies Socket.io with the Connect session store. It uses
* Connect's cookie parser to normalize configuration differences between Express
* and Socket.io and hooks into Sails' middleware interpreter to allow you to access
* and auto-save to `req.session` with Socket.io the same way you would with Express.
*
* For more information on configuring the session, check out:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html
*/
module.exports.session = {
/***************************************************************************
* *
* Session secret is automatically generated when your new app is created *
* Replace at your own risk in production-- you will invalidate the cookies *
* of your users, forcing them to log in again. *
* *
***************************************************************************/
secret: 'd4138f6c505bc7e32c30dbbab20b1d61',
/***************************************************************************
* *
* Set the session cookie expire time The maxAge is set by milliseconds, *
* the example below is for 24 hours *
* *
***************************************************************************/
// cookie: {
// maxAge: 24 * 60 * 60 * 1000
// }
/***************************************************************************
* *
* In production, uncomment the following lines to set up a shared redis *
* session store that can be shared across multiple Sails.js servers *
***************************************************************************/
// adapter: 'redis',
/***************************************************************************
* *
* The following values are optional, if no options are set a redis *
* instance running on localhost is expected. Read more about options at: *
* https://github.com/visionmedia/connect-redis *
* *
* *
***************************************************************************/
// host: 'localhost',
// port: 6379,
// ttl: <redis session TTL in seconds>,
// db: 0,
// pass: <redis auth password>
// prefix: 'sess:'
/***************************************************************************
* *
* Uncomment the following lines to use your Mongo adapter as a session *
* store *
* *
***************************************************************************/
// adapter: 'mongo',
// host: 'localhost',
// port: 27017,
// db: 'sails',
// collection: 'sessions',
/***************************************************************************
* *
* Optional Values: *
* *
* # Note: url will override other connection settings url: *
* 'mongodb://user:pass@host:port/database/collection', *
* *
***************************************************************************/
// username: '',
// password: '',
// auto_reconnect: false,
// ssl: false,
// stringify: true
};
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 2c-4 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zm5.66 3H6.43c.61-.52 2.06-1 5.57-1 3.71 0 5.12.46 5.66 1zM11 7v3H6V7h5zm2 0h5v3h-5V7zm3.5 10h-9c-.83 0-1.5-.67-1.5-1.5V12h12v3.5c0 .83-.67 1.5-1.5 1.5z"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "8.5",
cy: "14.5",
r: "1.5"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "15.5",
cy: "14.5",
r: "1.5"
}, "2")], 'DirectionsSubwayOutlined');
exports.default = _default; |
/**
* interact.js v1.1.2
*
* Copyright (c) 2012, 2013, 2014 Taye Adeyemi <dev@taye.me>
* Open source under the MIT License.
* https://raw.github.com/taye/interact.js/master/LICENSE
*/
(function () {
'use strict';
var document = window.document,
SVGElement = window.SVGElement || blank,
SVGSVGElement = window.SVGSVGElement || blank,
SVGElementInstance = window.SVGElementInstance || blank,
HTMLElement = window.HTMLElement || window.Element,
PointerEvent = (window.PointerEvent || window.MSPointerEvent),
pEventTypes,
hypot = Math.hypot || function (x, y) { return Math.sqrt(x * x + y * y); },
tmpXY = {}, // reduce object creation in getXY()
documents = [], // all documents being listened to
interactables = [], // all set interactables
interactions = [], // all interactions
dynamicDrop = false,
// {
// type: {
// selectors: ['selector', ...],
// contexts : [document, ...],
// listeners: [[listener, useCapture], ...]
// }
// }
delegatedEvents = {},
defaultOptions = {
draggable : false,
dragAxis : 'xy',
dropzone : false,
accept : null,
dropOverlap : 'pointer',
resizable : false,
squareResize: false,
resizeAxis : 'xy',
gesturable : false,
// no more than this number of actions can target the Interactable
dragMax : 1,
resizeMax : 1,
gestureMax: 1,
// no more than this number of actions can target the same
// element of this Interactable simultaneously
dragMaxPerElement : 1,
resizeMaxPerElement : 1,
gestureMaxPerElement: 1,
pointerMoveTolerance: 1,
actionChecker: null,
styleCursor: true,
preventDefault: 'auto',
// aww snap
snap: {
mode : 'grid',
endOnly : false,
actions : ['drag'],
range : Infinity,
grid : { x: 100, y: 100 },
gridOffset : { x: 0, y: 0 },
anchors : [],
paths : [],
elementOrigin: null,
arrayTypes : /^anchors$|^paths$|^actions$/,
objectTypes : /^grid$|^gridOffset$|^elementOrigin$/,
stringTypes : /^mode$/,
numberTypes : /^range$/,
boolTypes : /^endOnly$/
},
snapEnabled: false,
restrict: {
drag: null,
resize: null,
gesture: null,
endOnly: false
},
restrictEnabled: false,
autoScroll: {
container : null, // the item that is scrolled (Window or HTMLElement)
margin : 60,
speed : 300, // the scroll speed in pixels per second
numberTypes : /^margin$|^speed$/
},
autoScrollEnabled: false,
inertia: {
resistance : 10, // the lambda in exponential decay
minSpeed : 100, // target speed must be above this for inertia to start
endSpeed : 10, // the speed at which inertia is slow enough to stop
allowResume : true, // allow resuming an action in inertia phase
zeroResumeDelta : false, // if an action is resumed after launch, set dx/dy to 0
smoothEndDuration: 300, // animate to snap/restrict endOnly if there's no inertia
actions : ['drag', 'resize'], // allow inertia on these actions. gesture might not work
numberTypes: /^resistance$|^minSpeed$|^endSpeed$|^smoothEndDuration$/,
arrayTypes : /^actions$/,
boolTypes : /^(allowResume|zeroResumeDelta)$/
},
inertiaEnabled: false,
origin : { x: 0, y: 0 },
deltaSource : 'page',
},
// Things related to autoScroll
autoScroll = {
interaction: null,
i: null, // the handle returned by window.setInterval
x: 0, y: 0, // Direction each pulse is to scroll in
// scroll the window by the values in scroll.x/y
scroll: function () {
var options = autoScroll.interaction.target.options.autoScroll,
container = options.container || getWindow(autoScroll.interaction.element),
now = new Date().getTime(),
// change in time in seconds
dt = (now - autoScroll.prevTime) / 1000,
// displacement
s = options.speed * dt;
if (s >= 1) {
if (isWindow(container)) {
container.scrollBy(autoScroll.x * s, autoScroll.y * s);
}
else if (container) {
container.scrollLeft += autoScroll.x * s;
container.scrollTop += autoScroll.y * s;
}
autoScroll.prevTime = now;
}
if (autoScroll.isScrolling) {
cancelFrame(autoScroll.i);
autoScroll.i = reqFrame(autoScroll.scroll);
}
},
edgeMove: function (event) {
var interaction,
target,
doAutoscroll = false;
for (var i = 0; i < interactions.length; i++) {
interaction = interactions[i];
target = interaction.target;
if (target && target.options.autoScrollEnabled
&& (interaction.dragging || interaction.resizing)) {
doAutoscroll = true;
break;
}
}
if (!doAutoscroll) { return; }
var top,
right,
bottom,
left,
options = target.options.autoScroll,
container = options.container || getWindow(interaction.element);
if (isWindow(container)) {
left = event.clientX < autoScroll.margin;
top = event.clientY < autoScroll.margin;
right = event.clientX > container.innerWidth - autoScroll.margin;
bottom = event.clientY > container.innerHeight - autoScroll.margin;
}
else {
var rect = getElementRect(container);
left = event.clientX < rect.left + autoScroll.margin;
top = event.clientY < rect.top + autoScroll.margin;
right = event.clientX > rect.right - autoScroll.margin;
bottom = event.clientY > rect.bottom - autoScroll.margin;
}
autoScroll.x = (right ? 1: left? -1: 0);
autoScroll.y = (bottom? 1: top? -1: 0);
if (!autoScroll.isScrolling) {
// set the autoScroll properties to those of the target
autoScroll.margin = options.margin;
autoScroll.speed = options.speed;
autoScroll.start(interaction);
}
},
isScrolling: false,
prevTime: 0,
start: function (interaction) {
autoScroll.isScrolling = true;
cancelFrame(autoScroll.i);
autoScroll.interaction = interaction;
autoScroll.prevTime = new Date().getTime();
autoScroll.i = reqFrame(autoScroll.scroll);
},
stop: function () {
autoScroll.isScrolling = false;
cancelFrame(autoScroll.i);
}
},
// Does the browser support touch input?
supportsTouch = (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch),
// Does the browser support PointerEvents
supportsPointerEvent = !!PointerEvent,
// Less Precision with touch input
margin = supportsTouch || supportsPointerEvent? 20: 10,
// for ignoring browser's simulated mouse events
prevTouchTime = 0,
// Allow this many interactions to happen simultaneously
maxInteractions = 1,
actionCursors = {
drag : 'move',
resizex : 'e-resize',
resizey : 's-resize',
resizexy: 'se-resize',
gesture : ''
},
actionIsEnabled = {
drag : true,
resize : true,
gesture: true
},
// because Webkit and Opera still use 'mousewheel' event type
wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel',
eventTypes = [
'dragstart',
'dragmove',
'draginertiastart',
'dragend',
'dragenter',
'dragleave',
'dropactivate',
'dropdeactivate',
'dropmove',
'drop',
'resizestart',
'resizemove',
'resizeinertiastart',
'resizeend',
'gesturestart',
'gesturemove',
'gestureinertiastart',
'gestureend',
'down',
'move',
'up',
'cancel',
'tap',
'doubletap',
'hold'
],
globalEvents = {},
// Opera Mobile must be handled differently
isOperaMobile = navigator.appName == 'Opera' &&
supportsTouch &&
navigator.userAgent.match('Presto'),
// scrolling doesn't change the result of
// getBoundingClientRect/getClientRects on iOS <=7 but it does on iOS 8
isIOS7orLower = (/iP(hone|od|ad)/.test(navigator.platform)
&& /OS [1-7][^\d]/.test(navigator.appVersion)),
// prefix matchesSelector
prefixedMatchesSelector = 'matchesSelector' in Element.prototype?
'matchesSelector': 'webkitMatchesSelector' in Element.prototype?
'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype?
'mozMatchesSelector': 'oMatchesSelector' in Element.prototype?
'oMatchesSelector': 'msMatchesSelector',
// will be polyfill function if browser is IE8
ie8MatchesSelector,
// native requestAnimationFrame or polyfill
reqFrame = window.requestAnimationFrame,
cancelFrame = window.cancelAnimationFrame,
// Events wrapper
events = (function () {
var useAttachEvent = ('attachEvent' in window) && !('addEventListener' in window),
addEvent = useAttachEvent? 'attachEvent': 'addEventListener',
removeEvent = useAttachEvent? 'detachEvent': 'removeEventListener',
on = useAttachEvent? 'on': '',
elements = [],
targets = [],
attachedListeners = [];
function add (element, type, listener, useCapture) {
var elementIndex = indexOf(elements, element),
target = targets[elementIndex];
if (!target) {
target = {
events: {},
typeCount: 0
};
elementIndex = elements.push(element) - 1;
targets.push(target);
attachedListeners.push((useAttachEvent ? {
supplied: [],
wrapped : [],
useCount: []
} : null));
}
if (!target.events[type]) {
target.events[type] = [];
target.typeCount++;
}
if (!contains(target.events[type], listener)) {
var ret;
if (useAttachEvent) {
var listeners = attachedListeners[elementIndex],
listenerIndex = indexOf(listeners.supplied, listener);
var wrapped = listeners.wrapped[listenerIndex] || function (event) {
if (!event.immediatePropagationStopped) {
event.target = event.srcElement;
event.currentTarget = element;
event.preventDefault = event.preventDefault || preventDef;
event.stopPropagation = event.stopPropagation || stopProp;
event.stopImmediatePropagation = event.stopImmediatePropagation || stopImmProp;
if (/mouse|click/.test(event.type)) {
event.pageX = event.clientX + getWindow(element).document.documentElement.scrollLeft;
event.pageY = event.clientY + getWindow(element).document.documentElement.scrollTop;
}
listener(event);
}
};
ret = element[addEvent](on + type, wrapped, Boolean(useCapture));
if (listenerIndex === -1) {
listeners.supplied.push(listener);
listeners.wrapped.push(wrapped);
listeners.useCount.push(1);
}
else {
listeners.useCount[listenerIndex]++;
}
}
else {
ret = element[addEvent](type, listener, useCapture || false);
}
target.events[type].push(listener);
return ret;
}
}
function remove (element, type, listener, useCapture) {
var i,
elementIndex = indexOf(elements, element),
target = targets[elementIndex],
listeners,
listenerIndex,
wrapped = listener;
if (!target || !target.events) {
return;
}
if (useAttachEvent) {
listeners = attachedListeners[elementIndex];
listenerIndex = indexOf(listeners.supplied, listener);
wrapped = listeners.wrapped[listenerIndex];
}
if (type === 'all') {
for (type in target.events) {
if (target.events.hasOwnProperty(type)) {
remove(element, type, 'all');
}
}
return;
}
if (target.events[type]) {
var len = target.events[type].length;
if (listener === 'all') {
for (i = 0; i < len; i++) {
remove(element, type, target.events[type][i], Boolean(useCapture));
}
} else {
for (i = 0; i < len; i++) {
if (target.events[type][i] === listener) {
element[removeEvent](on + type, wrapped, useCapture || false);
target.events[type].splice(i, 1);
if (useAttachEvent && listeners) {
listeners.useCount[listenerIndex]--;
if (listeners.useCount[listenerIndex] === 0) {
listeners.supplied.splice(listenerIndex, 1);
listeners.wrapped.splice(listenerIndex, 1);
listeners.useCount.splice(listenerIndex, 1);
}
}
break;
}
}
}
if (target.events[type] && target.events[type].length === 0) {
target.events[type] = null;
target.typeCount--;
}
}
if (!target.typeCount) {
targets.splice(elementIndex);
elements.splice(elementIndex);
attachedListeners.splice(elementIndex);
}
}
function preventDef () {
this.returnValue = false;
}
function stopProp () {
this.cancelBubble = true;
}
function stopImmProp () {
this.cancelBubble = true;
this.immediatePropagationStopped = true;
}
return {
add: add,
remove: remove,
useAttachEvent: useAttachEvent,
_elements: elements,
_targets: targets,
_attachedListeners: attachedListeners
};
}());
function blank () {}
function isElement (o) {
if (!o || (typeof o !== 'object')) { return false; }
var _window = getWindow(o) || window;
return (/object|function/.test(typeof _window.Element)
? o instanceof _window.Element //DOM2
: o.nodeType === 1 && typeof o.nodeName === "string");
}
function isWindow (thing) { return !!(thing && thing.Window) && (thing instanceof thing.Window); }
function isArray (thing) {
return isObject(thing)
&& (typeof thing.length !== undefined)
&& isFunction(thing.splice);
}
function isObject (thing) { return !!thing && (typeof thing === 'object'); }
function isFunction (thing) { return typeof thing === 'function'; }
function isNumber (thing) { return typeof thing === 'number' ; }
function isBool (thing) { return typeof thing === 'boolean' ; }
function isString (thing) { return typeof thing === 'string' ; }
function trySelector (value) {
if (!isString(value)) { return false; }
// an exception will be raised if it is invalid
document.querySelector(value);
return true;
}
function extend (dest, source) {
for (var prop in source) {
dest[prop] = source[prop];
}
return dest;
}
function copyCoords (dest, src) {
dest.page = dest.page || {};
dest.page.x = src.page.x;
dest.page.y = src.page.y;
dest.client = dest.client || {};
dest.client.x = src.client.x;
dest.client.y = src.client.y;
dest.timeStamp = src.timeStamp;
}
function setEventXY (targetObj, pointer, interaction) {
if (!pointer) {
if (interaction.pointerIds.length > 1) {
pointer = touchAverage(interaction.pointers);
}
else {
pointer = interaction.pointers[0];
}
}
getPageXY(pointer, tmpXY, interaction);
targetObj.page.x = tmpXY.x;
targetObj.page.y = tmpXY.y;
getClientXY(pointer, tmpXY, interaction);
targetObj.client.x = tmpXY.x;
targetObj.client.y = tmpXY.y;
targetObj.timeStamp = new Date().getTime();
}
function setEventDeltas (targetObj, prev, cur) {
targetObj.page.x = cur.page.x - prev.page.x;
targetObj.page.y = cur.page.y - prev.page.y;
targetObj.client.x = cur.client.x - prev.client.x;
targetObj.client.y = cur.client.y - prev.client.y;
targetObj.timeStamp = new Date().getTime() - prev.timeStamp;
// set pointer velocity
var dt = Math.max(targetObj.timeStamp / 1000, 0.001);
targetObj.page.speed = hypot(targetObj.page.x, targetObj.page.y) / dt;
targetObj.page.vx = targetObj.page.x / dt;
targetObj.page.vy = targetObj.page.y / dt;
targetObj.client.speed = hypot(targetObj.client.x, targetObj.page.y) / dt;
targetObj.client.vx = targetObj.client.x / dt;
targetObj.client.vy = targetObj.client.y / dt;
}
// Get specified X/Y coords for mouse or event.touches[0]
function getXY (type, pointer, xy) {
xy = xy || {};
type = type || 'page';
xy.x = pointer[type + 'X'];
xy.y = pointer[type + 'Y'];
return xy;
}
function getPageXY (pointer, page, interaction) {
page = page || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
interaction = interaction || pointer.interaction;
extend(page, interaction.inertiaStatus.upCoords.page);
page.x += interaction.inertiaStatus.sx;
page.y += interaction.inertiaStatus.sy;
}
else {
page.x = pointer.pageX;
page.y = pointer.pageY;
}
}
// Opera Mobile handles the viewport and scrolling oddly
else if (isOperaMobile) {
getXY('screen', pointer, page);
page.x += window.scrollX;
page.y += window.scrollY;
}
else {
getXY('page', pointer, page);
}
return page;
}
function getClientXY (pointer, client, interaction) {
client = client || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
extend(client, interaction.inertiaStatus.upCoords.client);
client.x += interaction.inertiaStatus.sx;
client.y += interaction.inertiaStatus.sy;
}
else {
client.x = pointer.clientX;
client.y = pointer.clientY;
}
}
else {
// Opera Mobile handles the viewport and scrolling oddly
getXY(isOperaMobile? 'screen': 'client', pointer, client);
}
return client;
}
function getScrollXY (win) {
win = win || window;
return {
x: win.scrollX || win.document.documentElement.scrollLeft,
y: win.scrollY || win.document.documentElement.scrollTop
};
}
function getPointerId (pointer) {
return isNumber(pointer.pointerId)? pointer.pointerId : pointer.identifier;
}
function getActualElement (element) {
return (element instanceof SVGElementInstance
? element.correspondingUseElement
: element);
}
function getWindow (node) {
if (isWindow(node)) {
return node;
}
var rootNode = (node.ownerDocument || node);
return rootNode.defaultView || rootNode.parentWindow;
}
function getElementRect (element) {
var scroll = isIOS7orLower
? { x: 0, y: 0 }
: getScrollXY(getWindow(element)),
clientRect = (element instanceof SVGElement)?
element.getBoundingClientRect():
element.getClientRects()[0];
return clientRect && {
left : clientRect.left + scroll.x,
right : clientRect.right + scroll.x,
top : clientRect.top + scroll.y,
bottom: clientRect.bottom + scroll.y,
width : clientRect.width || clientRect.right - clientRect.left,
height: clientRect.heigh || clientRect.bottom - clientRect.top
};
}
function getTouchPair (event) {
var touches = [];
// array of touches is supplied
if (isArray(event)) {
touches[0] = event[0];
touches[1] = event[1];
}
// an event
else {
if (event.type === 'touchend') {
if (event.touches.length === 1) {
touches[0] = event.touches[0];
touches[1] = event.changedTouches[0];
}
else if (event.touches.length === 0) {
touches[0] = event.changedTouches[0];
touches[1] = event.changedTouches[1];
}
}
else {
touches[0] = event.touches[0];
touches[1] = event.touches[1];
}
}
return touches;
}
function touchAverage (event) {
var touches = getTouchPair(event);
return {
pageX: (touches[0].pageX + touches[1].pageX) / 2,
pageY: (touches[0].pageY + touches[1].pageY) / 2,
clientX: (touches[0].clientX + touches[1].clientX) / 2,
clientY: (touches[0].clientY + touches[1].clientY) / 2
};
}
function touchBBox (event) {
if (!event.length && !(event.touches && event.touches.length > 1)) {
return;
}
var touches = getTouchPair(event),
minX = Math.min(touches[0].pageX, touches[1].pageX),
minY = Math.min(touches[0].pageY, touches[1].pageY),
maxX = Math.max(touches[0].pageX, touches[1].pageX),
maxY = Math.max(touches[0].pageY, touches[1].pageY);
return {
x: minX,
y: minY,
left: minX,
top: minY,
width: maxX - minX,
height: maxY - minY
};
}
function touchDistance (event, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event);
var dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY];
return hypot(dx, dy);
}
function touchAngle (event, prevAngle, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event),
dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY],
angle = 180 * Math.atan(dy / dx) / Math.PI;
if (isNumber(prevAngle)) {
var dr = angle - prevAngle,
drClamped = dr % 360;
if (drClamped > 315) {
angle -= 360 + (angle / 360)|0 * 360;
}
else if (drClamped > 135) {
angle -= 180 + (angle / 360)|0 * 360;
}
else if (drClamped < -315) {
angle += 360 + (angle / 360)|0 * 360;
}
else if (drClamped < -135) {
angle += 180 + (angle / 360)|0 * 360;
}
}
return angle;
}
function getOriginXY (interactable, element) {
var origin = interactable
? interactable.options.origin
: defaultOptions.origin;
if (origin === 'parent') {
origin = element.parentNode;
}
else if (origin === 'self') {
origin = interactable.getRect(element);
}
else if (trySelector(origin)) {
origin = closest(element, origin) || { x: 0, y: 0 };
}
if (isFunction(origin)) {
origin = origin(interactable && element);
}
if (isElement(origin)) {
origin = getElementRect(origin);
}
origin.x = ('x' in origin)? origin.x : origin.left;
origin.y = ('y' in origin)? origin.y : origin.top;
return origin;
}
// http://stackoverflow.com/a/5634528/2280888
function _getQBezierValue(t, p1, p2, p3) {
var iT = 1 - t;
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
}
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
return {
x: _getQBezierValue(position, startX, cpX, endX),
y: _getQBezierValue(position, startY, cpY, endY)
};
}
// http://gizma.com/easing/
function easeOutQuad (t, b, c, d) {
t /= d;
return -c * t*(t-2) + b;
}
function nodeContains (parent, child) {
while ((child = child.parentNode)) {
if (child === parent) {
return true;
}
}
return false;
}
function closest (child, selector) {
var parent = child.parentNode;
while (isElement(parent)) {
if (matchesSelector(parent, selector)) { return parent; }
parent = parent.parentNode;
}
return null;
}
function inContext (interactable, element) {
return interactable._context === element.ownerDocument
|| nodeContains(interactable._context, element);
}
function testIgnore (interactable, interactableElement, element) {
var ignoreFrom = interactable.options.ignoreFrom;
if (!ignoreFrom
// limit test to the interactable's element and its children
|| !isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(ignoreFrom)) {
return matchesSelector(element, ignoreFrom) || testIgnore(interactable, element.parentNode);
}
else if (isElement(ignoreFrom)) {
return element === ignoreFrom || nodeContains(ignoreFrom, element);
}
return false;
}
function testAllow (interactable, interactableElement, element) {
var allowFrom = interactable.options.allowFrom;
if (!allowFrom) { return true; }
// limit test to the interactable's element and its children
if (!isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(allowFrom)) {
return matchesSelector(element, allowFrom) || testAllow(interactable, element.parentNode);
}
else if (isElement(allowFrom)) {
return element === allowFrom || nodeContains(allowFrom, element);
}
return false;
}
function checkAxis (axis, interactable) {
if (!interactable) { return false; }
var thisAxis = interactable.options.dragAxis;
return (axis === 'xy' || thisAxis === 'xy' || thisAxis === axis);
}
function checkSnap (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return action !== 'gesture' && options.snapEnabled && contains(options.snap.actions, action);
}
function checkRestrict (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return options.restrictEnabled && options.restrict[action];
}
function withinInteractionLimit (interactable, element, action) {
action = /resize/.test(action)? 'resize': action;
var options = interactable.options,
maxActions = options[action + 'Max'],
maxPerElement = options[action + 'MaxPerElement'],
activeInteractions = 0,
targetCount = 0,
targetElementCount = 0;
for (var i = 0, len = interactions.length; i < len; i++) {
var interaction = interactions[i],
otherAction = /resize/.test(interaction.prepared)? 'resize': interaction.prepared,
active = interaction.interacting();
if (!active) { continue; }
activeInteractions++;
if (activeInteractions >= maxInteractions) {
return false;
}
if (interaction.target !== interactable) { continue; }
targetCount += (otherAction === action)|0;
if (targetCount >= maxActions) {
return false;
}
if (interaction.element === element) {
targetElementCount++;
if (otherAction !== action || targetElementCount >= maxPerElement) {
return false;
}
}
}
return maxInteractions > 0;
}
// Test for the element that's "above" all other qualifiers
function indexOfDeepestElement (elements) {
var dropzone,
deepestZone = elements[0],
index = deepestZone? 0: -1,
parent,
deepestZoneParents = [],
dropzoneParents = [],
child,
i,
n;
for (i = 1; i < elements.length; i++) {
dropzone = elements[i];
// an element might belong to multiple selector dropzones
if (!dropzone || dropzone === deepestZone) {
continue;
}
if (!deepestZone) {
deepestZone = dropzone;
index = i;
continue;
}
// check if the deepest or current are document.documentElement or document.rootElement
// - if the current dropzone is, do nothing and continue
if (dropzone.parentNode === dropzone.ownerDocument) {
continue;
}
// - if deepest is, update with the current dropzone and continue to next
else if (deepestZone.parentNode === dropzone.ownerDocument) {
deepestZone = dropzone;
index = i;
continue;
}
if (!deepestZoneParents.length) {
parent = deepestZone;
while (parent.parentNode && parent.parentNode !== parent.ownerDocument) {
deepestZoneParents.unshift(parent);
parent = parent.parentNode;
}
}
// if this element is an svg element and the current deepest is
// an HTMLElement
if (deepestZone instanceof HTMLElement
&& dropzone instanceof SVGElement
&& !(dropzone instanceof SVGSVGElement)) {
if (dropzone === deepestZone.parentNode) {
continue;
}
parent = dropzone.ownerSVGElement;
}
else {
parent = dropzone;
}
dropzoneParents = [];
while (parent.parentNode !== parent.ownerDocument) {
dropzoneParents.unshift(parent);
parent = parent.parentNode;
}
n = 0;
// get (position of last common ancestor) + 1
while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) {
n++;
}
var parents = [
dropzoneParents[n - 1],
dropzoneParents[n],
deepestZoneParents[n]
];
child = parents[0].lastChild;
while (child) {
if (child === parents[1]) {
deepestZone = dropzone;
index = i;
deepestZoneParents = [];
break;
}
else if (child === parents[2]) {
break;
}
child = child.previousSibling;
}
}
return index;
}
function Interaction () {
this.target = null; // current interactable being interacted with
this.element = null; // the target element of the interactable
this.dropTarget = null; // the dropzone a drag target might be dropped into
this.dropElement = null; // the element at the time of checking
this.prevDropTarget = null; // the dropzone that was recently dragged away from
this.prevDropElement = null; // the element at the time of checking
this.prepared = null; // Action that's ready to be fired on next move event
this.matches = []; // all selectors that are matched by target element
this.matchElements = []; // corresponding elements
this.inertiaStatus = {
active : false,
smoothEnd : false,
startEvent: null,
upCoords: {},
xe: 0, ye: 0,
sx: 0, sy: 0,
t0: 0,
vx0: 0, vys: 0,
duration: 0,
resumeDx: 0,
resumeDy: 0,
lambda_v0: 0,
one_ve_v0: 0,
i : null
};
if (isFunction(Function.prototype.bind)) {
this.boundInertiaFrame = this.inertiaFrame.bind(this);
this.boundSmoothEndFrame = this.smoothEndFrame.bind(this);
}
else {
var that = this;
this.boundInertiaFrame = function () { return that.inertiaFrame(); };
this.boundSmoothEndFrame = function () { return that.smoothEndFrame(); };
}
this.activeDrops = {
dropzones: [], // the dropzones that are mentioned below
elements : [], // elements of dropzones that accept the target draggable
rects : [] // the rects of the elements mentioned above
};
// keep track of added pointers
this.pointers = [];
this.pointerIds = [];
this.downTargets = [];
this.downTimes = [];
this.holdTimers = [];
// Previous native pointer move event coordinates
this.prevCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// current native pointer move event coordinates
this.curCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Starting InteractEvent pointer coordinates
this.startCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Change in coordinates and time of the pointer
this.pointerDelta = {
page : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
client : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
timeStamp: 0
};
this.downEvent = null; // pointerdown/mousedown/touchstart event
this.downPointer = {};
this.prevEvent = null; // previous action event
this.tapTime = 0; // time of the most recent tap event
this.prevTap = null;
this.startOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.restrictOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.snapOffset = { x: 0, y: 0};
this.gesture = {
start: { x: 0, y: 0 },
startDistance: 0, // distance between two touches of touchStart
prevDistance : 0,
distance : 0,
scale: 1, // gesture.distance / gesture.startDistance
startAngle: 0, // angle of line joining two touches
prevAngle : 0 // angle of the previous gesture event
};
this.snapStatus = {
x : 0, y : 0,
dx : 0, dy : 0,
realX : 0, realY : 0,
snappedX: 0, snappedY: 0,
anchors : [],
paths : [],
locked : false,
changed : false
};
this.restrictStatus = {
dx : 0, dy : 0,
restrictedX: 0, restrictedY: 0,
snap : null,
restricted : false,
changed : false
};
this.restrictStatus.snap = this.snapStatus;
this.pointerIsDown = false;
this.pointerWasMoved = false;
this.gesturing = false;
this.dragging = false;
this.resizing = false;
this.resizeAxes = 'xy';
this.mouse = false;
interactions.push(this);
}
Interaction.prototype = {
getPageXY : function (pointer, xy) { return getPageXY(pointer, xy, this); },
getClientXY: function (pointer, xy) { return getClientXY(pointer, xy, this); },
setEventXY : function (target, ptr) { return setEventXY(target, ptr, this); },
pointerOver: function (pointer, event, eventTarget) {
if (this.prepared || !this.mouse) { return; }
var curMatches = [],
curMatchElements = [],
prevTargetElement = this.element;
this.addPointer(pointer);
if (this.target
&& (testIgnore(this.target, this.element, eventTarget)
|| !testAllow(this.target, this.element, eventTarget)
|| !withinInteractionLimit(this.target, this.element, this.prepared))) {
// if the eventTarget should be ignored or shouldn't be allowed
// clear the previous target
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
var elementInteractable = interactables.get(eventTarget),
elementAction = (elementInteractable
&& !testIgnore(elementInteractable, eventTarget, eventTarget)
&& testAllow(elementInteractable, eventTarget, eventTarget)
&& validateAction(
elementInteractable.getAction(pointer, this, eventTarget),
elementInteractable));
elementAction = elementInteractable && withinInteractionLimit(elementInteractable, eventTarget, elementAction)
? elementAction
: null;
function pushCurMatches (interactable, selector) {
if (interactable
&& inContext(interactable, eventTarget)
&& !testIgnore(interactable, eventTarget, eventTarget)
&& testAllow(interactable, eventTarget, eventTarget)
&& matchesSelector(eventTarget, selector)) {
curMatches.push(interactable);
curMatchElements.push(eventTarget);
}
}
if (elementAction) {
this.target = elementInteractable;
this.element = eventTarget;
this.matches = [];
this.matchElements = [];
}
else {
interactables.forEachSelector(pushCurMatches);
if (this.validateSelector(pointer, curMatches, curMatchElements)) {
this.matches = curMatches;
this.matchElements = curMatchElements;
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else if (this.target) {
if (nodeContains(prevTargetElement, eventTarget)) {
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(this.element,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else {
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
}
}
},
// Check what action would be performed on pointerMove target if a mouse
// button were pressed and change the cursor accordingly
pointerHover: function (pointer, event, eventTarget, curEventTarget, matches, matchElements) {
var target = this.target;
if (!this.prepared && this.mouse) {
var action;
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (matches) {
action = this.validateSelector(pointer, matches, matchElements);
}
else if (target) {
action = validateAction(target.getAction(this.pointers[0], this, this.element), this.target);
}
if (target && target.options.styleCursor) {
if (action) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
else {
target._doc.documentElement.style.cursor = '';
}
}
}
else if (this.prepared) {
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerOut: function (pointer, event, eventTarget) {
if (this.prepared) { return; }
// Remove temporary event listeners for selector Interactables
if (!interactables.get(eventTarget)) {
events.remove(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
if (this.target && this.target.options.styleCursor && !this.interacting()) {
this.target._doc.documentElement.style.cursor = '';
}
},
selectorDown: function (pointer, event, eventTarget, curEventTarget) {
var that = this,
element = eventTarget,
pointerIndex = this.addPointer(pointer),
action;
this.collectEventTargets(pointer, event, eventTarget, 'down');
this.holdTimers[pointerIndex] = window.setTimeout(function () {
that.pointerHold(pointer, event, eventTarget, curEventTarget);
}, 600);
this.pointerIsDown = true;
// Check if the down event hits the current inertia target
if (this.inertiaStatus.active && this.target.selector) {
// climb up the DOM tree from the event target
while (element && element !== element.ownerDocument) {
// if this element is the current inertia target element
if (element === this.element
// and the prospective action is the same as the ongoing one
&& validateAction(this.target.getAction(pointer, this, this.element), this.target) === this.prepared) {
// stop inertia so that the next move will be a normal one
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
return;
}
element = element.parentNode;
}
}
// do nothing if interacting
if (this.interacting()) {
return;
}
function pushMatches (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)) {
that.matches.push(interactable);
that.matchElements.push(element);
}
}
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (this.matches.length && this.mouse) {
action = this.validateSelector(pointer, this.matches, this.matchElements);
}
else {
while (element && element !== element.ownerDocument && !action) {
this.matches = [];
this.matchElements = [];
interactables.forEachSelector(pushMatches);
action = this.validateSelector(pointer, this.matches, this.matchElements);
element = element.parentNode;
}
}
if (action) {
this.prepared = action;
return this.pointerDown(pointer, event, eventTarget, curEventTarget, action);
}
else {
// do these now since pointerDown isn't being called from here
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
copyCoords(this.prevCoords, this.curCoords);
this.pointerWasMoved = false;
}
},
// Determine action to be performed on next pointerMove and add appropriate
// style and event Listeners
pointerDown: function (pointer, event, eventTarget, curEventTarget, forceAction) {
if (!forceAction && !this.inertiaStatus.active && this.pointerWasMoved && this.prepared) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
this.pointerIsDown = true;
var pointerIndex = this.addPointer(pointer),
action;
// If it is the second touch of a multi-touch gesture, keep the target
// the same if a target was set by the first touch
// Otherwise, set the target if there is no action prepared
if ((this.pointerIds.length < 2 && !this.target) || !this.prepared) {
var interactable = interactables.get(curEventTarget);
if (interactable
&& !testIgnore(interactable, curEventTarget, eventTarget)
&& testAllow(interactable, curEventTarget, eventTarget)
&& (action = validateAction(forceAction || interactable.getAction(pointer, this), interactable, eventTarget))
&& withinInteractionLimit(interactable, curEventTarget, action)) {
this.target = interactable;
this.element = curEventTarget;
}
}
var target = this.target,
options = target && target.options;
if (target && !this.interacting()) {
action = action || validateAction(forceAction || target.getAction(pointer, this), target, this.element);
this.setEventXY(this.startCoords);
if (!action) { return; }
if (options.styleCursor) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
this.resizeAxes = action === 'resizexy'?
'xy':
action === 'resizex'?
'x':
action === 'resizey'?
'y':
'';
if (action === 'gesture' && this.pointerIds.length < 2) {
action = null;
}
this.prepared = action;
this.snapStatus.snappedX = this.snapStatus.snappedY =
this.restrictStatus.restrictedX = this.restrictStatus.restrictedY = NaN;
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
this.setEventXY(this.prevCoords);
this.pointerWasMoved = false;
this.checkAndPreventDefault(event, target, this.element);
}
// if inertia is active try to resume action
else if (this.inertiaStatus.active
&& curEventTarget === this.element
&& validateAction(target.getAction(pointer, this, this.element), target) === this.prepared) {
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerMove: function (pointer, event, eventTarget, curEventTarget, preEnd) {
this.recordPointer(pointer);
this.setEventXY(this.curCoords, (pointer instanceof InteractEvent)
? this.inertiaStatus.startEvent
: undefined);
var duplicateMove = (this.curCoords.page.x === this.prevCoords.page.x
&& this.curCoords.page.y === this.prevCoords.page.y
&& this.curCoords.client.x === this.prevCoords.client.x
&& this.curCoords.client.y === this.prevCoords.client.y);
var dx, dy,
pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// register movement greater than pointerMoveTolerance
if (this.pointerIsDown && !this.pointerWasMoved) {
dx = this.curCoords.client.x - this.startCoords.client.x;
dy = this.curCoords.client.y - this.startCoords.client.y;
this.pointerWasMoved = hypot(dx, dy) > defaultOptions.pointerMoveTolerance;
}
if (!duplicateMove && (!this.pointerIsDown || this.pointerWasMoved)) {
if (this.pointerIsDown) {
window.clearTimeout(this.holdTimers[pointerIndex]);
}
this.collectEventTargets(pointer, event, eventTarget, 'move');
}
if (!this.pointerIsDown) { return; }
if (duplicateMove && this.pointerWasMoved && !preEnd) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
// set pointer coordinate, time changes and speeds
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
if (!this.prepared) { return; }
if (this.pointerWasMoved
// ignore movement while inertia is active
&& (!this.inertiaStatus.active || (pointer instanceof InteractEvent && /inertiastart/.test(pointer.type)))) {
// if just starting an action, calculate the pointer speed now
if (!this.interacting()) {
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
// check if a drag is in the correct axis
if (this.prepared === 'drag') {
var absX = Math.abs(dx),
absY = Math.abs(dy),
targetAxis = this.target.options.dragAxis,
axis = (absX > absY ? 'x' : absX < absY ? 'y' : 'xy');
// if the movement isn't in the axis of the interactable
if (axis !== 'xy' && targetAxis !== 'xy' && targetAxis !== axis) {
// cancel the prepared action
this.prepared = null;
// then try to get a drag from another ineractable
var element = eventTarget;
// check element interactables
while (element && element !== element.ownerDocument) {
var elementInteractable = interactables.get(element);
if (elementInteractable
&& elementInteractable !== this.target
&& elementInteractable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, elementInteractable)) {
this.prepared = 'drag';
this.target = elementInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
// if there's no drag from element interactables,
// check the selector interactables
if (!this.prepared) {
var getDraggable = function (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable === this.target) { return; }
if (inContext(interactable, eventTarget)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)
&& interactable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, interactable)
&& withinInteractionLimit(interactable, element, 'drag')) {
return interactable;
}
};
element = eventTarget;
while (element && element !== element.ownerDocument) {
var selectorInteractable = interactables.forEachSelector(getDraggable);
if (selectorInteractable) {
this.prepared = 'drag';
this.target = selectorInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
}
}
}
}
var starting = !!this.prepared && !this.interacting();
if (starting && !withinInteractionLimit(this.target, this.element, this.prepared)) {
this.stop();
return;
}
if (this.prepared && this.target) {
var target = this.target,
shouldMove = true,
shouldSnap = checkSnap(target, this.prepared) && (!target.options.snap.endOnly || preEnd),
shouldRestrict = checkRestrict(target, this.prepared) && (!target.options.restrict.endOnly || preEnd);
if (starting) {
var rect = target.getRect(this.element),
snap = target.options.snap,
restrict = target.options.restrict,
width, height;
if (rect) {
this.startOffset.left = this.startCoords.page.x - rect.left;
this.startOffset.top = this.startCoords.page.y - rect.top;
this.startOffset.right = rect.right - this.startCoords.page.x;
this.startOffset.bottom = rect.bottom - this.startCoords.page.y;
if ('width' in rect) { width = rect.width; }
else { width = rect.right - rect.left; }
if ('height' in rect) { height = rect.height; }
else { height = rect.bottom - rect.top; }
}
else {
this.startOffset.left = this.startOffset.top = this.startOffset.right = this.startOffset.bottom = 0;
}
if (rect && snap.elementOrigin) {
this.snapOffset.x = this.startOffset.left - (width * snap.elementOrigin.x);
this.snapOffset.y = this.startOffset.top - (height * snap.elementOrigin.y);
}
else {
this.snapOffset.x = this.snapOffset.y = 0;
}
if (rect && restrict.elementRect) {
this.restrictOffset.left = this.startOffset.left - (width * restrict.elementRect.left);
this.restrictOffset.top = this.startOffset.top - (height * restrict.elementRect.top);
this.restrictOffset.right = this.startOffset.right - (width * (1 - restrict.elementRect.right));
this.restrictOffset.bottom = this.startOffset.bottom - (height * (1 - restrict.elementRect.bottom));
}
else {
this.restrictOffset.left = this.restrictOffset.top = this.restrictOffset.right = this.restrictOffset.bottom = 0;
}
}
var snapCoords = starting? this.startCoords.page : this.curCoords.page;
if (shouldSnap ) { this.setSnapping (snapCoords); } else { this.snapStatus .locked = false; }
if (shouldRestrict) { this.setRestriction(snapCoords); } else { this.restrictStatus.restricted = false; }
if (shouldSnap && this.snapStatus.locked && !this.snapStatus.changed) {
shouldMove = shouldRestrict && this.restrictStatus.restricted && this.restrictStatus.changed;
}
else if (shouldRestrict && this.restrictStatus.restricted && !this.restrictStatus.changed) {
shouldMove = false;
}
// move if snapping or restriction doesn't prevent it
if (shouldMove) {
var action = /resize/.test(this.prepared)? 'resize': this.prepared;
if (starting) {
var dragStartEvent = this[action + 'Start'](this.downEvent);
this.prevEvent = dragStartEvent;
// reset active dropzones
this.activeDrops.dropzones = [];
this.activeDrops.elements = [];
this.activeDrops.rects = [];
if (!this.dynamicDrop) {
this.setActiveDrops(this.element);
}
var dropEvents = this.getDropEvents(event, dragStartEvent);
if (dropEvents.activate) {
this.fireActiveDrops(dropEvents.activate);
}
snapCoords = this.curCoords.page;
// set snapping and restriction for the move event
if (shouldSnap ) { this.setSnapping (snapCoords); }
if (shouldRestrict) { this.setRestriction(snapCoords); }
}
this.prevEvent = this[action + 'Move'](event);
}
this.checkAndPreventDefault(event, this.target, this.element);
}
}
copyCoords(this.prevCoords, this.curCoords);
if (this.dragging || this.resizing) {
autoScroll.edgeMove(event);
}
},
dragStart: function (event) {
var dragEvent = new InteractEvent(this, event, 'drag', 'start', this.element);
this.dragging = true;
this.target.fire(dragEvent);
return dragEvent;
},
dragMove: function (event) {
var target = this.target,
dragEvent = new InteractEvent(this, event, 'drag', 'move', this.element),
draggableElement = this.element,
drop = this.getDrop(dragEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, dragEvent);
target.fire(dragEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.move ) { this.dropTarget.fire(dropEvents.move ); }
this.prevDropTarget = this.dropTarget;
this.prevDropElement = this.dropElement;
return dragEvent;
},
resizeStart: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'start', this.element);
this.target.fire(resizeEvent);
this.resizing = true;
return resizeEvent;
},
resizeMove: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'move', this.element);
this.target.fire(resizeEvent);
return resizeEvent;
},
gestureStart: function (event) {
var gestureEvent = new InteractEvent(this, event, 'gesture', 'start', this.element);
gestureEvent.ds = 0;
this.gesture.startDistance = this.gesture.prevDistance = gestureEvent.distance;
this.gesture.startAngle = this.gesture.prevAngle = gestureEvent.angle;
this.gesture.scale = 1;
this.gesturing = true;
this.target.fire(gestureEvent);
return gestureEvent;
},
gestureMove: function (event) {
if (!this.pointerIds.length) {
return this.prevEvent;
}
var gestureEvent;
gestureEvent = new InteractEvent(this, event, 'gesture', 'move', this.element);
gestureEvent.ds = gestureEvent.scale - this.gesture.scale;
this.target.fire(gestureEvent);
this.gesture.prevAngle = gestureEvent.angle;
this.gesture.prevDistance = gestureEvent.distance;
if (gestureEvent.scale !== Infinity &&
gestureEvent.scale !== null &&
gestureEvent.scale !== undefined &&
!isNaN(gestureEvent.scale)) {
this.gesture.scale = gestureEvent.scale;
}
return gestureEvent;
},
pointerHold: function (pointer, event, eventTarget) {
this.collectEventTargets(pointer, event, eventTarget, 'hold');
},
pointerUp: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'up' );
this.collectEventTargets(pointer, event, eventTarget, 'tap');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
this.removePointer(pointer);
},
pointerCancel: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'cancel');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
},
// End interact move events and stop auto-scroll unless inertia is enabled
pointerEnd: function (pointer, event, eventTarget, curEventTarget) {
var endEvent,
target = this.target,
options = target && target.options,
inertiaOptions = options && options.inertia,
inertiaStatus = this.inertiaStatus;
if (this.interacting()) {
if (inertiaStatus.active) { return; }
var pointerSpeed,
now = new Date().getTime(),
inertiaPossible = false,
inertia = false,
smoothEnd = false,
endSnap = checkSnap(target, this.prepared) && options.snap.endOnly,
endRestrict = checkRestrict(target, this.prepared) && options.restrict.endOnly,
dx = 0,
dy = 0,
startEvent;
if (this.dragging) {
if (options.dragAxis === 'x' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vx); }
else if (options.dragAxis === 'y' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vy); }
else /*options.dragAxis === 'xy'*/{ pointerSpeed = this.pointerDelta.client.speed; }
}
// check if inertia should be started
inertiaPossible = (options.inertiaEnabled
&& this.prepared !== 'gesture'
&& contains(inertiaOptions.actions, this.prepared)
&& event !== inertiaStatus.startEvent);
inertia = (inertiaPossible
&& (now - this.curCoords.timeStamp) < 50
&& pointerSpeed > inertiaOptions.minSpeed
&& pointerSpeed > inertiaOptions.endSpeed);
if (inertiaPossible && !inertia && (endSnap || endRestrict)) {
var snapRestrict = {};
snapRestrict.snap = snapRestrict.restrict = snapRestrict;
if (endSnap) {
this.setSnapping(this.curCoords.page, snapRestrict);
if (snapRestrict.locked) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (endRestrict) {
this.setRestriction(this.curCoords.page, snapRestrict);
if (snapRestrict.restricted) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (dx || dy) {
smoothEnd = true;
}
}
if (inertia || smoothEnd) {
copyCoords(inertiaStatus.upCoords, this.curCoords);
this.pointers[0] = inertiaStatus.startEvent = startEvent =
new InteractEvent(this, event, this.prepared, 'inertiastart', this.element);
inertiaStatus.t0 = now;
target.fire(inertiaStatus.startEvent);
if (inertia) {
inertiaStatus.vx0 = this.pointerDelta.client.vx;
inertiaStatus.vy0 = this.pointerDelta.client.vy;
inertiaStatus.v0 = pointerSpeed;
this.calcInertia(inertiaStatus);
var page = extend({}, this.curCoords.page),
origin = getOriginXY(target, this.element),
statusObject;
page.x = page.x + inertiaStatus.xe - origin.x;
page.y = page.y + inertiaStatus.ye - origin.y;
statusObject = {
useStatusXY: true,
x: page.x,
y: page.y,
dx: 0,
dy: 0,
snap: null
};
statusObject.snap = statusObject;
dx = dy = 0;
if (endSnap) {
var snap = this.setSnapping(this.curCoords.page, statusObject);
if (snap.locked) {
dx += snap.dx;
dy += snap.dy;
}
}
if (endRestrict) {
var restrict = this.setRestriction(this.curCoords.page, statusObject);
if (restrict.restricted) {
dx += restrict.dx;
dy += restrict.dy;
}
}
inertiaStatus.modifiedXe += dx;
inertiaStatus.modifiedYe += dy;
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.smoothEnd = true;
inertiaStatus.xe = dx;
inertiaStatus.ye = dy;
inertiaStatus.sx = inertiaStatus.sy = 0;
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
inertiaStatus.active = true;
return;
}
if (endSnap || endRestrict) {
// fire a move event at the snapped coordinates
this.pointerMove(pointer, event, eventTarget, curEventTarget, true);
}
}
if (this.dragging) {
endEvent = new InteractEvent(this, event, 'drag', 'end', this.element);
var draggableElement = this.element,
drop = this.getDrop(endEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, endEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.drop ) { this.dropTarget.fire(dropEvents.drop ); }
if (dropEvents.deactivate) {
this.fireActiveDrops(dropEvents.deactivate);
}
target.fire(endEvent);
}
else if (this.resizing) {
endEvent = new InteractEvent(this, event, 'resize', 'end', this.element);
target.fire(endEvent);
}
else if (this.gesturing) {
endEvent = new InteractEvent(this, event, 'gesture', 'end', this.element);
target.fire(endEvent);
}
this.stop(event);
},
collectDrops: function (element) {
var drops = [],
elements = [],
i;
element = element || this.element;
// collect all dropzones and their elements which qualify for a drop
for (i = 0; i < interactables.length; i++) {
if (!interactables[i].options.dropzone) { continue; }
var current = interactables[i];
// test the draggable element against the dropzone's accept setting
if ((isElement(current.options.accept) && current.options.accept !== element)
|| (isString(current.options.accept)
&& !matchesSelector(element, current.options.accept))) {
continue;
}
// query for new elements if necessary
var dropElements = current.selector? current._context.querySelectorAll(current.selector) : [current._element];
for (var j = 0, len = dropElements.length; j < len; j++) {
var currentElement = dropElements[j];
if (currentElement === element) {
continue;
}
drops.push(current);
elements.push(currentElement);
}
}
return {
dropzones: drops,
elements: elements
};
},
fireActiveDrops: function (event) {
var i,
current,
currentElement,
prevElement;
// loop through all active dropzones and trigger event
for (i = 0; i < this.activeDrops.dropzones.length; i++) {
current = this.activeDrops.dropzones[i];
currentElement = this.activeDrops.elements [i];
// prevent trigger of duplicate events on same element
if (currentElement !== prevElement) {
// set current element as event target
event.target = currentElement;
current.fire(event);
}
prevElement = currentElement;
}
},
// Collect a new set of possible drops and save them in activeDrops.
// setActiveDrops should always be called when a drag has just started or a
// drag event happens while dynamicDrop is true
setActiveDrops: function (dragElement) {
// get dropzones and their elements that could receive the draggable
var possibleDrops = this.collectDrops(dragElement, true);
this.activeDrops.dropzones = possibleDrops.dropzones;
this.activeDrops.elements = possibleDrops.elements;
this.activeDrops.rects = [];
for (var i = 0; i < this.activeDrops.dropzones.length; i++) {
this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]);
}
},
getDrop: function (event, dragElement) {
var validDrops = [];
if (dynamicDrop) {
this.setActiveDrops(dragElement);
}
// collect all dropzones and their elements which qualify for a drop
for (var j = 0; j < this.activeDrops.dropzones.length; j++) {
var current = this.activeDrops.dropzones[j],
currentElement = this.activeDrops.elements [j],
rect = this.activeDrops.rects [j];
validDrops.push(current.dropCheck(this.pointers[0], this.target, dragElement, currentElement, rect)
? currentElement
: null);
}
// get the most appropriate dropzone based on DOM depth and order
var dropIndex = indexOfDeepestElement(validDrops),
dropzone = this.activeDrops.dropzones[dropIndex] || null,
element = this.activeDrops.elements [dropIndex] || null;
return {
dropzone: dropzone,
element: element
};
},
getDropEvents: function (pointerEvent, dragEvent) {
var dragLeaveEvent = null,
dragEnterEvent = null,
dropActivateEvent = null,
dropDeactivateEvent = null,
dropMoveEvent = null,
dropEvent = null;
if (this.dropElement !== this.prevDropElement) {
// if there was a prevDropTarget, create a dragleave event
if (this.prevDropTarget) {
dragLeaveEvent = new InteractEvent(this, pointerEvent, 'drag', 'leave', this.prevDropElement, dragEvent.target);
dragLeaveEvent.draggable = dragEvent.interactable;
dragEvent.dragLeave = this.prevDropElement;
dragEvent.prevDropzone = this.prevDropTarget;
}
// if the dropTarget is not null, create a dragenter event
if (this.dropTarget) {
dragEnterEvent = new InteractEvent(this, pointerEvent, 'drag', 'enter', this.dropElement, dragEvent.target);
dragEnterEvent.draggable = dragEvent.interactable;
dragEvent.dragEnter = this.dropElement;
dragEvent.dropzone = this.dropTarget;
}
}
if (dragEvent.type === 'dragend' && this.dropTarget) {
dropEvent = new InteractEvent(this, pointerEvent, 'drop', null, this.dropElement, dragEvent.target);
dropEvent.draggable = dragEvent.interactable;
dragEvent.dropzone = this.dropTarget;
}
if (dragEvent.type === 'dragstart') {
dropActivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'activate', this.element, dragEvent.target);
dropActivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragend') {
dropDeactivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'deactivate', this.element, dragEvent.target);
dropDeactivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragmove' && this.dropTarget) {
dropMoveEvent = {
target : this.dropElement,
relatedTarget: dragEvent.target,
draggable : dragEvent.interactable,
dragmove : dragEvent,
type : 'dropmove',
timeStamp : dragEvent.timeStamp
};
dragEvent.dropzone = this.dropTarget;
}
return {
enter : dragEnterEvent,
leave : dragLeaveEvent,
activate : dropActivateEvent,
deactivate : dropDeactivateEvent,
move : dropMoveEvent,
drop : dropEvent
};
},
currentAction: function () {
return (this.dragging && 'drag') || (this.resizing && 'resize') || (this.gesturing && 'gesture') || null;
},
interacting: function () {
return this.dragging || this.resizing || this.gesturing;
},
clearTargets: function () {
if (this.target && !this.target.selector) {
this.target = this.element = null;
}
this.dropTarget = this.dropElement = this.prevDropTarget = this.prevDropElement = null;
},
stop: function (event) {
if (this.interacting()) {
autoScroll.stop();
this.matches = [];
this.matchElements = [];
var target = this.target;
if (target.options.styleCursor) {
target._doc.documentElement.style.cursor = '';
}
// prevent Default only if were previously interacting
if (event && isFunction(event.preventDefault)) {
this.checkAndPreventDefault(event, target, this.element);
}
if (this.dragging) {
this.activeDrops.dropzones = this.activeDrops.elements = this.activeDrops.rects = null;
}
this.clearTargets();
}
this.pointerIsDown = this.snapStatus.locked = this.dragging = this.resizing = this.gesturing = false;
this.prepared = this.prevEvent = null;
this.inertiaStatus.resumeDx = this.inertiaStatus.resumeDy = 0;
this.pointerIds .splice(0);
this.pointers .splice(0);
this.downTargets.splice(0);
this.downTimes .splice(0);
this.holdTimers .splice(0);
// delete interaction if it's not the only one
if (interactions.length > 1) {
interactions.splice(indexOf(interactions, this), 1);
}
},
inertiaFrame: function () {
var inertiaStatus = this.inertiaStatus,
options = this.target.options.inertia,
lambda = options.resistance,
t = new Date().getTime() / 1000 - inertiaStatus.t0;
if (t < inertiaStatus.te) {
var progress = 1 - (Math.exp(-lambda * t) - inertiaStatus.lambda_v0) / inertiaStatus.one_ve_v0;
if (inertiaStatus.modifiedXe === inertiaStatus.xe && inertiaStatus.modifiedYe === inertiaStatus.ye) {
inertiaStatus.sx = inertiaStatus.xe * progress;
inertiaStatus.sy = inertiaStatus.ye * progress;
}
else {
var quadPoint = getQuadraticCurvePoint(
0, 0,
inertiaStatus.xe, inertiaStatus.ye,
inertiaStatus.modifiedXe, inertiaStatus.modifiedYe,
progress);
inertiaStatus.sx = quadPoint.x;
inertiaStatus.sy = quadPoint.y;
}
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.sx = inertiaStatus.modifiedXe;
inertiaStatus.sy = inertiaStatus.modifiedYe;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
smoothEndFrame: function () {
var inertiaStatus = this.inertiaStatus,
t = new Date().getTime() - inertiaStatus.t0,
duration = this.target.options.inertia.smoothEndDuration;
if (t < duration) {
inertiaStatus.sx = easeOutQuad(t, 0, inertiaStatus.xe, duration);
inertiaStatus.sy = easeOutQuad(t, 0, inertiaStatus.ye, duration);
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
else {
inertiaStatus.sx = inertiaStatus.xe;
inertiaStatus.sy = inertiaStatus.ye;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
inertiaStatus.smoothEnd = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
addPointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) {
index = this.pointerIds.length;
this.pointerIds.push(id);
}
this.pointers[index] = pointer;
return index;
},
removePointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) { return; }
this.pointerIds .splice(index, 1);
this.pointers .splice(index, 1);
this.downTargets.splice(index, 1);
this.downTimes .splice(index, 1);
this.holdTimers .splice(index, 1);
},
recordPointer: function (pointer) {
// Do not update pointers while inertia is active.
// The inertia start event should be this.pointers[0]
if (this.inertiaStatus.active) { return; }
var index = this.mouse? 0: indexOf(this.pointerIds, getPointerId(pointer));
if (index === -1) { return; }
this.pointers[index] = pointer;
},
collectEventTargets: function (pointer, event, eventTarget, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// do not fire a tap event if the pointer was moved before being lifted
if (eventType === 'tap' && (this.pointerWasMoved
// or if the pointerup target is different to the pointerdown target
|| !(this.downTargets[pointerIndex] && this.downTargets[pointerIndex] === eventTarget))) {
return;
}
var targets = [],
elements = [],
element = eventTarget;
function collectSelectors (interactable, selector, context) {
var els = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable._iEvents[eventType]
&& isElement(element)
&& inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, els)) {
targets.push(interactable);
elements.push(element);
}
}
while (element) {
if (interact.isSet(element) && interact(element)._iEvents[eventType]) {
targets.push(interact(element));
elements.push(element);
}
interactables.forEachSelector(collectSelectors);
element = element.parentNode;
}
if (targets.length) {
this.firePointers(pointer, event, targets, elements, eventType);
}
},
firePointers: function (pointer, event, targets, elements, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(getPointerId(pointer)),
pointerEvent = {},
i,
// for tap events
interval, dbl;
extend(pointerEvent, event);
if (event !== pointer) {
extend(pointerEvent, pointer);
}
pointerEvent.preventDefault = preventOriginalDefault;
pointerEvent.stopPropagation = InteractEvent.prototype.stopPropagation;
pointerEvent.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation;
pointerEvent.interaction = this;
pointerEvent.timeStamp = new Date().getTime();
pointerEvent.originalEvent = event;
pointerEvent.type = eventType;
pointerEvent.pointerId = getPointerId(pointer);
pointerEvent.pointerType = this.mouse? 'mouse' : !supportsPointerEvent? 'touch'
: isString(pointer.pointerType)
? pointer.pointerType
: [,,'touch', 'pen', 'mouse'][pointer.pointerType];
if (eventType === 'tap') {
pointerEvent.dt = pointerEvent.timeStamp - this.downTimes[pointerIndex];
interval = pointerEvent.timeStamp - this.tapTime;
dbl = (this.prevTap && this.prevTap.type !== 'doubletap'
&& this.prevTap.target === pointerEvent.target
&& interval < 500);
this.tapTime = pointerEvent.timeStamp;
}
for (i = 0; i < targets.length; i++) {
pointerEvent.currentTarget = elements[i];
pointerEvent.interactable = targets[i];
targets[i].fire(pointerEvent);
if (pointerEvent.immediatePropagationStopped
||(pointerEvent.propagationStopped && elements[i + 1] !== pointerEvent.currentTarget)) {
break;
}
}
if (dbl) {
var doubleTap = {};
extend(doubleTap, pointerEvent);
doubleTap.dt = interval;
doubleTap.type = 'doubletap';
for (i = 0; i < targets.length; i++) {
doubleTap.currentTarget = elements[i];
doubleTap.interactable = targets[i];
targets[i].fire(doubleTap);
if (doubleTap.immediatePropagationStopped
||(doubleTap.propagationStopped && elements[i + 1] !== doubleTap.currentTarget)) {
break;
}
}
this.prevTap = doubleTap;
}
else if (eventType === 'tap') {
this.prevTap = pointerEvent;
}
},
validateSelector: function (pointer, matches, matchElements) {
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i],
matchElement = matchElements[i],
action = validateAction(match.getAction(pointer, this, matchElement), match);
if (action && withinInteractionLimit(match, matchElement, action)) {
this.target = match;
this.element = matchElement;
return action;
}
}
},
setSnapping: function (pageCoords, status) {
var snap = this.target.options.snap,
anchors = snap.anchors,
page,
closest,
range,
inRange,
snapChanged,
dx,
dy,
distance,
i, len;
status = status || this.snapStatus;
if (status.useStatusXY) {
page = { x: status.x, y: status.y };
}
else {
var origin = getOriginXY(this.target, this.element);
page = extend({}, pageCoords);
page.x -= origin.x;
page.y -= origin.y;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.realX = page.x;
status.realY = page.y;
// change to infinite range when range is negative
if (snap.range < 0) { snap.range = Infinity; }
// create an anchor representative for each path's returned point
if (snap.mode === 'path') {
anchors = [];
for (i = 0, len = snap.paths.length; i < len; i++) {
var path = snap.paths[i];
if (isFunction(path)) {
path = path(page.x, page.y);
}
anchors.push({
x: isNumber(path.x) ? path.x : page.x,
y: isNumber(path.y) ? path.y : page.y,
range: isNumber(path.range)? path.range: snap.range
});
}
}
if ((snap.mode === 'anchor' || snap.mode === 'path') && anchors.length) {
closest = {
anchor: null,
distance: 0,
range: 0,
dx: 0,
dy: 0
};
for (i = 0, len = anchors.length; i < len; i++) {
var anchor = anchors[i];
range = isNumber(anchor.range)? anchor.range: snap.range;
dx = anchor.x - page.x + this.snapOffset.x;
dy = anchor.y - page.y + this.snapOffset.y;
distance = hypot(dx, dy);
inRange = distance < range;
// Infinite anchors count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.inRange && closest.range !== Infinity) {
inRange = false;
}
if (!closest.anchor || (inRange?
// is the closest anchor in range?
(closest.inRange && range !== Infinity)?
// the pointer is relatively deeper in this anchor
distance / range < closest.distance / closest.range:
//the pointer is closer to this anchor
distance < closest.distance:
// The other is not in range and the pointer is closer to this anchor
(!closest.inRange && distance < closest.distance))) {
if (range === Infinity) {
inRange = true;
}
closest.anchor = anchor;
closest.distance = distance;
closest.range = range;
closest.inRange = inRange;
closest.dx = dx;
closest.dy = dy;
status.range = range;
}
}
inRange = closest.inRange;
snapChanged = (closest.anchor.x !== status.x || closest.anchor.y !== status.y);
status.snappedX = closest.anchor.x;
status.snappedY = closest.anchor.y;
status.dx = closest.dx;
status.dy = closest.dy;
}
else if (snap.mode === 'grid') {
var gridx = Math.round((page.x - snap.gridOffset.x - this.snapOffset.x) / snap.grid.x),
gridy = Math.round((page.y - snap.gridOffset.y - this.snapOffset.y) / snap.grid.y),
newX = gridx * snap.grid.x + snap.gridOffset.x + this.snapOffset.x,
newY = gridy * snap.grid.y + snap.gridOffset.y + this.snapOffset.y;
dx = newX - page.x;
dy = newY - page.y;
distance = hypot(dx, dy);
inRange = distance < snap.range;
snapChanged = (newX !== status.snappedX || newY !== status.snappedY);
status.snappedX = newX;
status.snappedY = newY;
status.dx = dx;
status.dy = dy;
status.range = snap.range;
}
status.changed = (snapChanged || (inRange && !status.locked));
status.locked = inRange;
return status;
},
setRestriction: function (pageCoords, status) {
var target = this.target,
action = /resize/.test(this.prepared)? 'resize' : this.prepared,
restrict = target && target.options.restrict,
restriction = restrict && restrict[action],
page;
if (!restriction) {
return status;
}
status = status || this.restrictStatus;
page = status.useStatusXY
? page = { x: status.x, y: status.y }
: page = extend({}, pageCoords);
if (status.snap && status.snap.locked) {
page.x += status.snap.dx || 0;
page.y += status.snap.dy || 0;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.dx = 0;
status.dy = 0;
status.restricted = false;
var rect, restrictedX, restrictedY;
if (isString(restriction)) {
if (restriction === 'parent') {
restriction = this.element.parentNode;
}
else if (restriction === 'self') {
restriction = target.getRect(this.element);
}
else {
restriction = closest(this.element, restriction);
}
if (!restriction) { return status; }
}
if (isFunction(restriction)) {
restriction = restriction(page.x, page.y, this.element);
}
if (isElement(restriction)) {
restriction = getElementRect(restriction);
}
rect = restriction;
// object is assumed to have
// x, y, width, height or
// left, top, right, bottom
if ('x' in restriction && 'y' in restriction) {
restrictedX = Math.max(Math.min(rect.x + rect.width - this.restrictOffset.right , page.x), rect.x + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.y + rect.height - this.restrictOffset.bottom, page.y), rect.y + this.restrictOffset.top );
}
else {
restrictedX = Math.max(Math.min(rect.right - this.restrictOffset.right , page.x), rect.left + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.bottom - this.restrictOffset.bottom, page.y), rect.top + this.restrictOffset.top );
}
status.dx = restrictedX - page.x;
status.dy = restrictedY - page.y;
status.changed = status.restrictedX !== restrictedX || status.restrictedY !== restrictedY;
status.restricted = !!(status.dx || status.dy);
status.restrictedX = restrictedX;
status.restrictedY = restrictedY;
return status;
},
checkAndPreventDefault: function (event, interactable, element) {
if (!(interactable = interactable || this.target)) { return; }
var options = interactable.options,
prevent = options.preventDefault;
if (prevent === 'auto' && element && !/^input$|^textarea$/i.test(element.nodeName)) {
// do not preventDefault on pointerdown if the prepared action is a drag
// and dragging can only start from a certain direction - this allows
// a touch to pan the viewport if a drag isn't in the right direction
if (/down|start/i.test(event.type)
&& this.prepared === 'drag' && options.dragAxis !== 'xy') {
return;
}
event.preventDefault();
return;
}
if (prevent === true) {
event.preventDefault();
return;
}
},
calcInertia: function (status) {
var inertiaOptions = this.target.options.inertia,
lambda = inertiaOptions.resistance,
inertiaDur = -Math.log(inertiaOptions.endSpeed / status.v0) / lambda;
status.x0 = this.prevEvent.pageX;
status.y0 = this.prevEvent.pageY;
status.t0 = status.startEvent.timeStamp / 1000;
status.sx = status.sy = 0;
status.modifiedXe = status.xe = (status.vx0 - inertiaDur) / lambda;
status.modifiedYe = status.ye = (status.vy0 - inertiaDur) / lambda;
status.te = inertiaDur;
status.lambda_v0 = lambda / status.v0;
status.one_ve_v0 = 1 - inertiaOptions.endSpeed / status.v0;
}
};
function getInteractionFromPointer (pointer, eventType, eventTarget) {
var i = 0, len = interactions.length,
mouseEvent = (/mouse/i.test(pointer.pointerType || eventType)
// MSPointerEvent.MSPOINTER_TYPE_MOUSE
|| pointer.pointerType === 4),
interaction;
var id = getPointerId(pointer);
// try to resume inertia with a new pointer
if (/down|start/i.test(eventType)) {
for (i = 0; i < len; i++) {
interaction = interactions[i];
var element = eventTarget;
if (interaction.inertiaStatus.active && interaction.target.options.inertia.allowResume
&& (interaction.mouse === mouseEvent)) {
while (element) {
// if the element is the interaction element
if (element === interaction.element) {
// update the interaction's pointer
if (interaction.pointers[0]) {
interaction.removePointer(interaction.pointers[0]);
}
interaction.addPointer(pointer);
return interaction;
}
element = element.parentNode;
}
}
}
}
// if it's a mouse interaction
if (mouseEvent || !(supportsTouch || supportsPointerEvent)) {
// find a mouse interaction that's not in inertia phase
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !interactions[i].inertiaStatus.active) {
return interactions[i];
}
}
// find any interaction specifically for mouse.
// if the eventType is a mousedown, and inertia is active
// ignore the interaction
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !(/down/.test(eventType) && interactions[i].inertiaStatus.active)) {
return interaction;
}
}
// create a new interaction for mouse
interaction = new Interaction();
interaction.mouse = true;
return interaction;
}
// get interaction that has this pointer
for (i = 0; i < len; i++) {
if (contains(interactions[i].pointerIds, id)) {
return interactions[i];
}
}
// at this stage, a pointerUp should not return an interaction
if (/up|end|out/i.test(eventType)) {
return null;
}
// get first idle interaction
for (i = 0; i < len; i++) {
interaction = interactions[i];
if ((!interaction.prepared || (interaction.target.gesturable()))
&& !interaction.interacting()
&& !(!mouseEvent && interaction.mouse)) {
interaction.addPointer(pointer);
return interaction;
}
}
return new Interaction();
}
function doOnInteractions (method) {
return (function (event) {
var interaction,
eventTarget = getActualElement(event.target),
curEventTarget = getActualElement(event.currentTarget),
i;
if (supportsTouch && /touch/.test(event.type)) {
prevTouchTime = new Date().getTime();
for (i = 0; i < event.changedTouches.length; i++) {
var pointer = event.changedTouches[i];
interaction = getInteractionFromPointer(pointer, event.type, eventTarget);
if (!interaction) { continue; }
interaction[method](pointer, event, eventTarget, curEventTarget);
}
}
else {
if (!supportsPointerEvent && /mouse/.test(event.type)) {
// ignore mouse events while touch interactions are active
for (i = 0; i < interactions.length; i++) {
if (!interactions[i].mouse && interactions[i].pointerIsDown) {
return;
}
}
// try to ignore mouse events that are simulated by the browser
// after a touch event
if (new Date().getTime() - prevTouchTime < 500) {
return;
}
}
interaction = getInteractionFromPointer(event, event.type, eventTarget);
if (!interaction) { return; }
interaction[method](event, event, eventTarget, curEventTarget);
}
});
}
function InteractEvent (interaction, event, action, phase, element, related) {
var client,
page,
target = interaction.target,
snapStatus = interaction.snapStatus,
restrictStatus = interaction.restrictStatus,
pointers = interaction.pointers,
deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
options = target? target.options: defaultOptions,
origin = getOriginXY(target, element),
starting = phase === 'start',
ending = phase === 'end',
coords = starting? interaction.startCoords : interaction.curCoords;
element = element || interaction.element;
page = extend({}, coords.page);
client = extend({}, coords.client);
page.x -= origin.x;
page.y -= origin.y;
client.x -= origin.x;
client.y -= origin.y;
if (checkSnap(target, action) && !(starting && options.snap.elementOrigin)) {
this.snap = {
range : snapStatus.range,
locked : snapStatus.locked,
x : snapStatus.snappedX,
y : snapStatus.snappedY,
realX : snapStatus.realX,
realY : snapStatus.realY,
dx : snapStatus.dx,
dy : snapStatus.dy
};
if (snapStatus.locked) {
page.x += snapStatus.dx;
page.y += snapStatus.dy;
client.x += snapStatus.dx;
client.y += snapStatus.dy;
}
}
if (checkRestrict(target, action) && !(starting && options.restrict.elementRect) && restrictStatus.restricted) {
page.x += restrictStatus.dx;
page.y += restrictStatus.dy;
client.x += restrictStatus.dx;
client.y += restrictStatus.dy;
this.restrict = {
dx: restrictStatus.dx,
dy: restrictStatus.dy
};
}
this.pageX = page.x;
this.pageY = page.y;
this.clientX = client.x;
this.clientY = client.y;
this.x0 = interaction.startCoords.page.x;
this.y0 = interaction.startCoords.page.y;
this.clientX0 = interaction.startCoords.client.x;
this.clientY0 = interaction.startCoords.client.y;
this.ctrlKey = event.ctrlKey;
this.altKey = event.altKey;
this.shiftKey = event.shiftKey;
this.metaKey = event.metaKey;
this.button = event.button;
this.target = element;
this.t0 = interaction.downTimes[0];
this.type = action + (phase || '');
this.interaction = interaction;
this.interactable = target;
var inertiaStatus = interaction.inertiaStatus;
if (inertiaStatus.active) {
this.detail = 'inertia';
}
if (related) {
this.relatedTarget = related;
}
// end event dx, dy is difference between start and end points
if (ending || action === 'drop') {
if (deltaSource === 'client') {
this.dx = client.x - interaction.startCoords.client.x;
this.dy = client.y - interaction.startCoords.client.y;
}
else {
this.dx = page.x - interaction.startCoords.page.x;
this.dy = page.y - interaction.startCoords.page.y;
}
}
else if (starting) {
this.dx = 0;
this.dy = 0;
}
// copy properties from previousmove if starting inertia
else if (phase === 'inertiastart') {
this.dx = interaction.prevEvent.dx;
this.dy = interaction.prevEvent.dy;
}
else {
if (deltaSource === 'client') {
this.dx = client.x - interaction.prevEvent.clientX;
this.dy = client.y - interaction.prevEvent.clientY;
}
else {
this.dx = page.x - interaction.prevEvent.pageX;
this.dy = page.y - interaction.prevEvent.pageY;
}
}
if (interaction.prevEvent && interaction.prevEvent.detail === 'inertia'
&& !inertiaStatus.active && options.inertia.zeroResumeDelta) {
inertiaStatus.resumeDx += this.dx;
inertiaStatus.resumeDy += this.dy;
this.dx = this.dy = 0;
}
if (action === 'resize') {
if (options.squareResize || event.shiftKey) {
if (interaction.resizeAxes === 'y') {
this.dx = this.dy;
}
else {
this.dy = this.dx;
}
this.axes = 'xy';
}
else {
this.axes = interaction.resizeAxes;
if (interaction.resizeAxes === 'x') {
this.dy = 0;
}
else if (interaction.resizeAxes === 'y') {
this.dx = 0;
}
}
}
else if (action === 'gesture') {
this.touches = [pointers[0], pointers[1]];
if (starting) {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = 1;
this.ds = 0;
this.angle = touchAngle(pointers, undefined, deltaSource);
this.da = 0;
}
else if (ending || event instanceof InteractEvent) {
this.distance = interaction.prevEvent.distance;
this.box = interaction.prevEvent.box;
this.scale = interaction.prevEvent.scale;
this.ds = this.scale - 1;
this.angle = interaction.prevEvent.angle;
this.da = this.angle - interaction.gesture.startAngle;
}
else {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = this.distance / interaction.gesture.startDistance;
this.angle = touchAngle(pointers, interaction.gesture.prevAngle, deltaSource);
this.ds = this.scale - interaction.gesture.prevScale;
this.da = this.angle - interaction.gesture.prevAngle;
}
}
if (starting) {
this.timeStamp = interaction.downTimes[0];
this.dt = 0;
this.duration = 0;
this.speed = 0;
this.velocityX = 0;
this.velocityY = 0;
}
else if (phase === 'inertiastart') {
this.timeStamp = interaction.prevEvent.timeStamp;
this.dt = interaction.prevEvent.dt;
this.duration = interaction.prevEvent.duration;
this.speed = interaction.prevEvent.speed;
this.velocityX = interaction.prevEvent.velocityX;
this.velocityY = interaction.prevEvent.velocityY;
}
else {
this.timeStamp = new Date().getTime();
this.dt = this.timeStamp - interaction.prevEvent.timeStamp;
this.duration = this.timeStamp - interaction.downTimes[0];
if (event instanceof InteractEvent) {
var dx = this[sourceX] - interaction.prevEvent[sourceX],
dy = this[sourceY] - interaction.prevEvent[sourceY],
dt = this.dt / 1000;
this.speed = hypot(dx, dy) / dt;
this.velocityX = dx / dt;
this.velocityY = dy / dt;
}
// if normal move or end event, use previous user event coords
else {
// speed and velocity in pixels per second
this.speed = interaction.pointerDelta[deltaSource].speed;
this.velocityX = interaction.pointerDelta[deltaSource].vx;
this.velocityY = interaction.pointerDelta[deltaSource].vy;
}
}
if ((ending || phase === 'inertiastart')
&& interaction.prevEvent.speed > 600 && this.timeStamp - interaction.prevEvent.timeStamp < 150) {
var angle = 180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX) / Math.PI,
overlap = 22.5;
if (angle < 0) {
angle += 360;
}
var left = 135 - overlap <= angle && angle < 225 + overlap,
up = 225 - overlap <= angle && angle < 315 + overlap,
right = !left && (315 - overlap <= angle || angle < 45 + overlap),
down = !up && 45 - overlap <= angle && angle < 135 + overlap;
this.swipe = {
up : up,
down : down,
left : left,
right: right,
angle: angle,
speed: interaction.prevEvent.speed,
velocity: {
x: interaction.prevEvent.velocityX,
y: interaction.prevEvent.velocityY
}
};
}
}
InteractEvent.prototype = {
preventDefault: blank,
stopImmediatePropagation: function () {
this.immediatePropagationStopped = this.propagationStopped = true;
},
stopPropagation: function () {
this.propagationStopped = true;
}
};
function preventOriginalDefault () {
this.originalEvent.preventDefault();
}
function defaultActionChecker (pointer, interaction, element) {
var rect = this.getRect(element),
right,
bottom,
action = null,
page = extend({}, interaction.curCoords.page),
options = this.options;
if (!rect) { return null; }
if (actionIsEnabled.resize && options.resizable) {
right = options.resizeAxis !== 'y' && page.x > (rect.right - margin);
bottom = options.resizeAxis !== 'x' && page.y > (rect.bottom - margin);
}
interaction.resizeAxes = (right?'x': '') + (bottom?'y': '');
action = (interaction.resizeAxes)?
'resize' + interaction.resizeAxes:
actionIsEnabled.drag && options.draggable?
'drag':
null;
if (actionIsEnabled.gesture
&& interaction.pointerIds.length >=2
&& !(interaction.dragging || interaction.resizing)) {
action = 'gesture';
}
return action;
}
// Check if action is enabled globally and the current target supports it
// If so, return the validated action. Otherwise, return null
function validateAction (action, interactable) {
if (!isString(action)) { return null; }
var actionType = action.search('resize') !== -1? 'resize': action,
options = interactable;
if (( (actionType === 'resize' && options.resizable )
|| (action === 'drag' && options.draggable )
|| (action === 'gesture' && options.gesturable))
&& actionIsEnabled[actionType]) {
if (action === 'resize' || action === 'resizeyx') {
action = 'resizexy';
}
return action;
}
return null;
}
var listeners = {},
interactionListeners = [
'dragStart', 'dragMove', 'resizeStart', 'resizeMove', 'gestureStart', 'gestureMove',
'pointerOver', 'pointerOut', 'pointerHover', 'selectorDown',
'pointerDown', 'pointerMove', 'pointerUp', 'pointerCancel', 'pointerEnd',
'addPointer', 'removePointer', 'recordPointer',
];
for (var i = 0, len = interactionListeners.length; i < len; i++) {
var name = interactionListeners[i];
listeners[name] = doOnInteractions(name);
}
// bound to the interactable context when a DOM event
// listener is added to a selector interactable
function delegateListener (event, useCapture) {
var fakeEvent = {},
delegated = delegatedEvents[event.type],
element = event.target;
useCapture = useCapture? true: false;
// duplicate the event so that currentTarget can be changed
for (var prop in event) {
fakeEvent[prop] = event[prop];
}
fakeEvent.originalEvent = event;
fakeEvent.preventDefault = preventOriginalDefault;
// climb up document tree looking for selector matches
while (element && (element.ownerDocument && element !== element.ownerDocument)) {
for (var i = 0; i < delegated.selectors.length; i++) {
var selector = delegated.selectors[i],
context = delegated.contexts[i];
if (matchesSelector(element, selector)
&& nodeContains(context, event.target)
&& nodeContains(context, element)) {
var listeners = delegated.listeners[i];
fakeEvent.currentTarget = element;
for (var j = 0; j < listeners.length; j++) {
if (listeners[j][1] === useCapture) {
listeners[j][0](fakeEvent);
}
}
}
}
element = element.parentNode;
}
}
function delegateUseCapture (event) {
return delegateListener.call(this, event, true);
}
interactables.indexOfElement = function indexOfElement (element, context) {
context = context || document;
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if ((interactable.selector === element
&& (interactable._context === context))
|| (!interactable.selector && interactable._element === element)) {
return i;
}
}
return -1;
};
interactables.get = function interactableGet (element, options) {
return this[this.indexOfElement(element, options && options.context)];
};
interactables.forEachSelector = function (callback) {
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if (!interactable.selector) {
continue;
}
var ret = callback(interactable, interactable.selector, interactable._context, i, this);
if (ret !== undefined) {
return ret;
}
}
};
/*\
* interact
[ method ]
*
* The methods of this variable can be used to set elements as
* interactables and also to change various default settings.
*
* Calling it as a function and passing an element or a valid CSS selector
* string returns an Interactable object which has various methods to
* configure it.
*
- element (Element | string) The HTML or SVG Element to interact with or CSS selector
= (object) An @Interactable
*
> Usage
| interact(document.getElementById('draggable')).draggable(true);
|
| var rectables = interact('rect');
| rectables
| .gesturable(true)
| .on('gesturemove', function (event) {
| // something cool...
| })
| .autoScroll(true);
\*/
function interact (element, options) {
return interactables.get(element, options) || new Interactable(element, options);
}
// A class for easy inheritance and setting of an Interactable's options
function IOptions (options) {
for (var option in defaultOptions) {
if (options.hasOwnProperty(option)
&& typeof options[option] === typeof defaultOptions[option]) {
this[option] = options[option];
}
}
}
IOptions.prototype = defaultOptions;
/*\
* Interactable
[ property ]
**
* Object type returned by @interact
\*/
function Interactable (element, options) {
this._element = element;
this._iEvents = this._iEvents || {};
var _window;
if (trySelector(element)) {
this.selector = element;
var context = options && options.context;
_window = context? getWindow(context) : window;
if (context && (_window.Node
? context instanceof _window.Node
: (isElement(context) || context === _window.document))) {
this._context = context;
}
}
else {
_window = getWindow(element);
if (isElement(element, _window)) {
if (PointerEvent) {
events.add(this._element, pEventTypes.down, listeners.pointerDown );
events.add(this._element, pEventTypes.move, listeners.pointerHover);
}
else {
events.add(this._element, 'mousedown' , listeners.pointerDown );
events.add(this._element, 'mousemove' , listeners.pointerHover);
events.add(this._element, 'touchstart', listeners.pointerDown );
events.add(this._element, 'touchmove' , listeners.pointerHover);
}
}
}
this._doc = _window.document;
if (!contains(documents, this._doc)) {
listenToDocument(this._doc);
}
interactables.push(this);
this.set(options);
}
Interactable.prototype = {
setOnEvents: function (action, phases) {
if (action === 'drop') {
var drop = phases.ondrop || phases.onDrop || phases.drop,
dropactivate = phases.ondropactivate || phases.onDropActivate || phases.dropactivate
|| phases.onactivate || phases.onActivate || phases.activate,
dropdeactivate = phases.ondropdeactivate || phases.onDropDeactivate || phases.dropdeactivate
|| phases.ondeactivate || phases.onDeactivate || phases.deactivate,
dragenter = phases.ondragenter || phases.onDropEnter || phases.dragenter
|| phases.onenter || phases.onEnter || phases.enter,
dragleave = phases.ondragleave || phases.onDropLeave || phases.dragleave
|| phases.onleave || phases.onLeave || phases.leave,
dropmove = phases.ondropmove || phases.onDropMove || phases.dropmove
|| phases.onmove || phases.onMove || phases.move;
if (isFunction(drop) ) { this.ondrop = drop ; }
if (isFunction(dropactivate) ) { this.ondropactivate = dropactivate ; }
if (isFunction(dropdeactivate)) { this.ondropdeactivate = dropdeactivate; }
if (isFunction(dragenter) ) { this.ondragenter = dragenter ; }
if (isFunction(dragleave) ) { this.ondragleave = dragleave ; }
if (isFunction(dropmove) ) { this.ondropmove = dropmove ; }
}
else {
var start = phases.onstart || phases.onStart || phases.start,
move = phases.onmove || phases.onMove || phases.move,
end = phases.onend || phases.onEnd || phases.end,
inertiastart = phases.oninertiastart || phases.onInertiaStart || phases.inertiastart;
action = 'on' + action;
if (isFunction(start) ) { this[action + 'start' ] = start ; }
if (isFunction(move) ) { this[action + 'move' ] = move ; }
if (isFunction(end) ) { this[action + 'end' ] = end ; }
if (isFunction(inertiastart)) { this[action + 'inertiastart' ] = inertiastart ; }
}
return this;
},
/*\
* Interactable.draggable
[ method ]
*
* Gets or sets whether drag actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of drag events
| var isDraggable = interact('ul li').draggable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable)
= (object) This Interactable
| interact(element).draggable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // the axis in which the first movement must be
| // for the drag sequence to start
| // 'xy' by default - any direction
| axis: 'x' || 'y' || 'xy',
|
| // max number of drags that can happen concurrently
| // with elements of this Interactable. 1 by default
| max: Infinity,
|
| // max number of drags that can target the same element
| // 1 by default
| maxPerElement: 2
| });
\*/
draggable: function (options) {
if (isObject(options)) {
this.options.draggable = true;
this.setOnEvents('drag', options);
if (isNumber(options.max)) {
this.options.dragMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.dragMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.dragAxis = options.axis;
}
else if (options.axis === null) {
delete this.options.dragAxis;
}
return this;
}
if (isBool(options)) {
this.options.draggable = options;
return this;
}
if (options === null) {
delete this.options.draggable;
return this;
}
return this.options.draggable;
},
/*\
* Interactable.dropzone
[ method ]
*
* Returns or sets whether elements can be dropped onto this
* Interactable to trigger drop events
*
* Dropzones can receive the following events:
* - `dragactivate` and `dragdeactivate` when an acceptable drag starts and ends
* - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone
* - `drop` when a draggable is dropped into this dropzone
*
* Use the `accept` option to allow only elements that match the given CSS selector or element.
*
* Use the `overlap` option to set how drops are checked for. The allowed values are:
* - `'pointer'`, the pointer must be over the dropzone (default)
* - `'center'`, the draggable element's center must be over the dropzone
* - a number from 0-1 which is the `(intersection area) / (draggable area)`.
* e.g. `0.5` for drop to happen when half of the area of the
* draggable is over the dropzone
*
- options (boolean | object | null) #optional The new value to be set.
| interact('.drop').dropzone({
| accept: '.can-drop' || document.getElementById('single-drop'),
| overlap: 'pointer' || 'center' || zeroToOne
| }
= (boolean | object) The current setting or this Interactable
\*/
dropzone: function (options) {
if (isObject(options)) {
this.options.dropzone = true;
this.setOnEvents('drop', options);
this.accept(options.accept);
if (/^(pointer|center)$/.test(options.overlap)) {
this.options.dropOverlap = options.overlap;
}
else if (isNumber(options.overlap)) {
this.options.dropOverlap = Math.max(Math.min(1, options.overlap), 0);
}
return this;
}
if (isBool(options)) {
this.options.dropzone = options;
return this;
}
if (options === null) {
delete this.options.dropzone;
return this;
}
return this.options.dropzone;
},
/*\
* Interactable.dropCheck
[ method ]
*
* The default function to determine if a dragend event occured over
* this Interactable's element. Can be overridden using
* @Interactable.dropChecker.
*
- pointer (MouseEvent | PointerEvent | Touch) The event that ends a drag
- draggable (Interactable) The Interactable being dragged
- draggableElement (Element) The actual element that's being dragged
- dropElement (Element) The dropzone element
- rect (object) #optional The rect of dropElement
= (boolean) whether the pointer was over this Interactable
\*/
dropCheck: function (pointer, draggable, draggableElement, dropElement, rect) {
if (!(rect = rect || this.getRect(dropElement))) {
return false;
}
var dropOverlap = this.options.dropOverlap;
if (dropOverlap === 'pointer') {
var page = getPageXY(pointer),
origin = getOriginXY(draggable, draggableElement),
horizontal,
vertical;
page.x += origin.x;
page.y += origin.y;
horizontal = (page.x > rect.left) && (page.x < rect.right);
vertical = (page.y > rect.top ) && (page.y < rect.bottom);
return horizontal && vertical;
}
var dragRect = draggable.getRect(draggableElement);
if (dropOverlap === 'center') {
var cx = dragRect.left + dragRect.width / 2,
cy = dragRect.top + dragRect.height / 2;
return cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom;
}
if (isNumber(dropOverlap)) {
var overlapArea = (Math.max(0, Math.min(rect.right , dragRect.right ) - Math.max(rect.left, dragRect.left))
* Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top , dragRect.top ))),
overlapRatio = overlapArea / (dragRect.width * dragRect.height);
return overlapRatio >= dropOverlap;
}
},
/*\
* Interactable.dropChecker
[ method ]
*
* Gets or sets the function used to check if a dragged element is
* over this Interactable. See @Interactable.dropCheck.
*
- checker (function) #optional
* The checker is a function which takes a mouseUp/touchEnd event as a
* parameter and returns true or false to indicate if the the current
* draggable can be dropped into this Interactable
*
= (Function | Interactable) The checker function or this Interactable
\*/
dropChecker: function (checker) {
if (isFunction(checker)) {
this.dropCheck = checker;
return this;
}
return this.dropCheck;
},
/*\
* Interactable.accept
[ method ]
*
* Gets or sets the Element or CSS selector match that this
* Interactable accepts if it is a dropzone.
*
- newValue (Element | string | null) #optional
* If it is an Element, then only that element can be dropped into this dropzone.
* If it is a string, the element being dragged must match it as a selector.
* If it is null, the accept options is cleared - it accepts any element.
*
= (string | Element | null | Interactable) The current accept option if given `undefined` or this Interactable
\*/
accept: function (newValue) {
if (isElement(newValue)) {
this.options.accept = newValue;
return this;
}
// test if it is a valid CSS selector
if (trySelector(newValue)) {
this.options.accept = newValue;
return this;
}
if (newValue === null) {
delete this.options.accept;
return this;
}
return this.options.accept;
},
/*\
* Interactable.resizable
[ method ]
*
* Gets or sets whether resize actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of resize elements
| var isResizeable = interact('input[type=text]').resizable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable)
= (object) This Interactable
| interact(element).resizable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| axis : 'x' || 'y' || 'xy' // default is 'xy',
|
| // limit multiple resizes.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
resizable: function (options) {
if (isObject(options)) {
this.options.resizable = true;
this.setOnEvents('resize', options);
if (isNumber(options.max)) {
this.options.resizeMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.resizeMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.resizeAxis = options.axis;
}
else if (options.axis === null) {
this.options.resizeAxis = defaultOptions.resizeAxis;
}
return this;
}
if (isBool(options)) {
this.options.resizable = options;
return this;
}
return this.options.resizable;
},
// misspelled alias
resizeable: blank,
/*\
* Interactable.squareResize
[ method ]
*
* Gets or sets whether resizing is forced 1:1 aspect
*
= (boolean) Current setting
*
* or
*
- newValue (boolean) #optional
= (object) this Interactable
\*/
squareResize: function (newValue) {
if (isBool(newValue)) {
this.options.squareResize = newValue;
return this;
}
if (newValue === null) {
delete this.options.squareResize;
return this;
}
return this.options.squareResize;
},
/*\
* Interactable.gesturable
[ method ]
*
* Gets or sets whether multitouch gestures can be performed on the
* Interactable's element
*
= (boolean) Indicates if this can be the target of gesture events
| var isGestureable = interact(element).gesturable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable)
= (object) this Interactable
| interact(element).gesturable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // limit multiple gestures.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
gesturable: function (options) {
if (isObject(options)) {
this.options.gesturable = true;
this.setOnEvents('gesture', options);
if (isNumber(options.max)) {
this.options.gestureMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.gestureMaxPerElement = options.maxPerElement;
}
return this;
}
if (isBool(options)) {
this.options.gesturable = options;
return this;
}
if (options === null) {
delete this.options.gesturable;
return this;
}
return this.options.gesturable;
},
// misspelled alias
gestureable: blank,
/*\
* Interactable.autoScroll
[ method ]
*
* Returns or sets whether or not any actions near the edges of the
* window/container trigger autoScroll for this Interactable
*
= (boolean | object)
* `false` if autoScroll is disabled; object with autoScroll properties
* if autoScroll is enabled
*
* or
*
- options (object | boolean | null) #optional
* options can be:
* - an object with margin, distance and interval properties,
* - true or false to enable or disable autoScroll or
* - null to use default settings
= (Interactable) this Interactable
\*/
autoScroll: function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
var autoScroll = this.options.autoScroll;
if (autoScroll === defaults) {
autoScroll = this.options.autoScroll = {
margin : defaults.margin,
distance : defaults.distance,
interval : defaults.interval,
container: defaults.container
};
}
autoScroll.margin = this.validateSetting('autoScroll', 'margin', options.margin);
autoScroll.speed = this.validateSetting('autoScroll', 'speed' , options.speed);
autoScroll.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
this.options.autoScrollEnabled = true;
this.options.autoScroll = autoScroll;
return this;
}
if (isBool(options)) {
this.options.autoScrollEnabled = options;
return this;
}
if (options === null) {
delete this.options.autoScrollEnabled;
delete this.options.autoScroll;
return this;
}
return (this.options.autoScrollEnabled
? this.options.autoScroll
: false);
},
/*\
* Interactable.snap
[ method ]
**
* Returns or sets if and how action coordinates are snapped. By
* default, snapping is relative to the pointer coordinates. You can
* change this by setting the
* [`elementOrigin`](https://github.com/taye/interact.js/pull/72).
**
= (boolean | object) `false` if snap is disabled; object with snap properties if snap is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| interact('.handle').snap({
| mode : 'grid', // event coords should snap to the corners of a grid
| range : Infinity, // the effective distance of snap points
| grid : { x: 100, y: 100 }, // the x and y spacing of the grid points
| gridOffset : { x: 0, y: 0 }, // the offset of the grid points
| });
|
| interact('.handle').snap({
| mode : 'anchor', // snap to specified points
| anchors : [
| { x: 100, y: 100, range: 25 }, // a point with x, y and a specific range
| { x: 200, y: 200 } // a point with x and y. it uses the default range
| ]
| });
|
| interact(document.querySelector('#thing')).snap({
| mode : 'path',
| paths: [
| { // snap to points on these x and y axes
| x: 100,
| y: 100,
| range: 25
| },
| // give this function the x and y page coords and snap to the object returned
| function (x, y) {
| return {
| x: x,
| y: (75 + 50 * Math.sin(x * 0.04)),
| range: 40
| };
| }]
| })
|
| interact(element).snap({
| // do not snap during normal movement.
| // Instead, trigger only one snapped move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementOrigin: { x: 0, y: 0 }
| });
\*/
snap: function (options) {
var defaults = defaultOptions.snap;
if (isObject(options)) {
var snap = this.options.snap;
if (snap === defaults) {
snap = {};
}
snap.mode = this.validateSetting('snap', 'mode' , options.mode);
snap.endOnly = this.validateSetting('snap', 'endOnly' , options.endOnly);
snap.actions = this.validateSetting('snap', 'actions' , options.actions);
snap.range = this.validateSetting('snap', 'range' , options.range);
snap.paths = this.validateSetting('snap', 'paths' , options.paths);
snap.grid = this.validateSetting('snap', 'grid' , options.grid);
snap.gridOffset = this.validateSetting('snap', 'gridOffset' , options.gridOffset);
snap.anchors = this.validateSetting('snap', 'anchors' , options.anchors);
snap.elementOrigin = this.validateSetting('snap', 'elementOrigin', options.elementOrigin);
this.options.snapEnabled = true;
this.options.snap = snap;
return this;
}
if (isBool(options)) {
this.options.snapEnabled = options;
return this;
}
if (options === null) {
delete this.options.snapEnabled;
delete this.options.snap;
return this;
}
return (this.options.snapEnabled
? this.options.snap
: false);
},
/*\
* Interactable.inertia
[ method ]
**
* Returns or sets if and how events continue to run after the pointer is released
**
= (boolean | object) `false` if inertia is disabled; `object` with inertia properties if inertia is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| // enable and use default settings
| interact(element).inertia(true);
|
| // enable and use custom settings
| interact(element).inertia({
| // value greater than 0
| // high values slow the object down more quickly
| resistance : 16,
|
| // the minimum launch speed (pixels per second) that results in inertia start
| minSpeed : 200,
|
| // inertia will stop when the object slows down to this speed
| endSpeed : 20,
|
| // boolean; should actions be resumed when the pointer goes down during inertia
| allowResume : true,
|
| // boolean; should the jump when resuming from inertia be ignored in event.dx/dy
| zeroResumeDelta: false,
|
| // if snap/restrict are set to be endOnly and inertia is enabled, releasing
| // the pointer without triggering inertia will animate from the release
| // point to the snaped/restricted point in the given amount of time (ms)
| smoothEndDuration: 300,
|
| // an array of action types that can have inertia (no gesture)
| actions : ['drag', 'resize']
| });
|
| // reset custom settings and use all defaults
| interact(element).inertia(null);
\*/
inertia: function (options) {
var defaults = defaultOptions.inertia;
if (isObject(options)) {
var inertia = this.options.inertia;
if (inertia === defaults) {
inertia = this.options.inertia = {
resistance : defaults.resistance,
minSpeed : defaults.minSpeed,
endSpeed : defaults.endSpeed,
actions : defaults.actions,
allowResume : defaults.allowResume,
zeroResumeDelta : defaults.zeroResumeDelta,
smoothEndDuration: defaults.smoothEndDuration
};
}
inertia.resistance = this.validateSetting('inertia', 'resistance' , options.resistance);
inertia.minSpeed = this.validateSetting('inertia', 'minSpeed' , options.minSpeed);
inertia.endSpeed = this.validateSetting('inertia', 'endSpeed' , options.endSpeed);
inertia.actions = this.validateSetting('inertia', 'actions' , options.actions);
inertia.allowResume = this.validateSetting('inertia', 'allowResume' , options.allowResume);
inertia.zeroResumeDelta = this.validateSetting('inertia', 'zeroResumeDelta' , options.zeroResumeDelta);
inertia.smoothEndDuration = this.validateSetting('inertia', 'smoothEndDuration', options.smoothEndDuration);
this.options.inertiaEnabled = true;
this.options.inertia = inertia;
return this;
}
if (isBool(options)) {
this.options.inertiaEnabled = options;
return this;
}
if (options === null) {
delete this.options.inertiaEnabled;
delete this.options.inertia;
return this;
}
return (this.options.inertiaEnabled
? this.options.inertia
: false);
},
getAction: function (pointer, interaction, element) {
var action = this.defaultActionChecker(pointer, interaction, element);
if (this.options.actionChecker) {
action = this.options.actionChecker(pointer, action, this, element, interaction);
}
return action;
},
defaultActionChecker: defaultActionChecker,
/*\
* Interactable.actionChecker
[ method ]
*
* Gets or sets the function used to check action to be performed on
* pointerDown
*
- checker (function | null) #optional A function which takes a pointer event, defaultAction string and an interactable as parameters and returns 'drag' 'resize[axes]' or 'gesture' or null.
= (Function | Interactable) The checker function or this Interactable
\*/
actionChecker: function (newValue) {
if (isFunction(newValue)) {
this.options.actionChecker = newValue;
return this;
}
if (newValue === null) {
delete this.options.actionChecker;
return this;
}
return this.options.actionChecker;
},
/*\
* Interactable.getRect
[ method ]
*
* The default function to get an Interactables bounding rect. Can be
* overridden using @Interactable.rectChecker.
*
- element (Element) #optional The element to measure. Meant to be used for selector Interactables which don't have a specific element.
= (object) The object's bounding rectangle.
o {
o top : 0,
o left : 0,
o bottom: 0,
o right : 0,
o width : 0,
o height: 0
o }
\*/
getRect: function rectCheck (element) {
element = element || this._element;
if (this.selector && !(isElement(element))) {
element = this._context.querySelector(this.selector);
}
return getElementRect(element);
},
/*\
* Interactable.rectChecker
[ method ]
*
* Returns or sets the function used to calculate the interactable's
* element's rectangle
*
- checker (function) #optional A function which returns this Interactable's bounding rectangle. See @Interactable.getRect
= (function | object) The checker function or this Interactable
\*/
rectChecker: function (checker) {
if (isFunction(checker)) {
this.getRect = checker;
return this;
}
if (checker === null) {
delete this.options.getRect;
return this;
}
return this.getRect;
},
/*\
* Interactable.styleCursor
[ method ]
*
* Returns or sets whether the action that would be performed when the
* mouse on the element are checked on `mousemove` so that the cursor
* may be styled appropriately
*
- newValue (boolean) #optional
= (boolean | Interactable) The current setting or this Interactable
\*/
styleCursor: function (newValue) {
if (isBool(newValue)) {
this.options.styleCursor = newValue;
return this;
}
if (newValue === null) {
delete this.options.styleCursor;
return this;
}
return this.options.styleCursor;
},
/*\
* Interactable.preventDefault
[ method ]
*
* Returns or sets whether to prevent the browser's default behaviour
* in response to pointer events. Can be set to
* - `true` to always prevent
* - `false` to never prevent
* - `'auto'` to allow interact.js to try to guess what would be best
* - `null` to set to the default ('auto')
*
- newValue (boolean | string | null) #optional `true`, `false` or `'auto'`
= (boolean | string | Interactable) The current setting or this Interactable
\*/
preventDefault: function (newValue) {
if (isBool(newValue) || newValue === 'auto') {
this.options.preventDefault = newValue;
return this;
}
if (newValue === null) {
delete this.options.preventDefault;
return this;
}
return this.options.preventDefault;
},
/*\
* Interactable.origin
[ method ]
*
* Gets or sets the origin of the Interactable's element. The x and y
* of the origin will be subtracted from action event coordinates.
*
- origin (object | string) #optional An object eg. { x: 0, y: 0 } or string 'parent', 'self' or any CSS selector
* OR
- origin (Element) #optional An HTML or SVG Element whose rect will be used
**
= (object) The current origin or this Interactable
\*/
origin: function (newValue) {
if (trySelector(newValue)) {
this.options.origin = newValue;
return this;
}
else if (isObject(newValue)) {
this.options.origin = newValue;
return this;
}
if (newValue === null) {
delete this.options.origin;
return this;
}
return this.options.origin;
},
/*\
* Interactable.deltaSource
[ method ]
*
* Returns or sets the mouse coordinate types used to calculate the
* movement of the pointer.
*
- newValue (string) #optional Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work
= (string | object) The current deltaSource or this Interactable
\*/
deltaSource: function (newValue) {
if (newValue === 'page' || newValue === 'client') {
this.options.deltaSource = newValue;
return this;
}
if (newValue === null) {
delete this.options.deltaSource;
return this;
}
return this.options.deltaSource;
},
/*\
* Interactable.restrict
[ method ]
**
* Returns or sets the rectangles within which actions on this
* interactable (after snap calculations) are restricted. By default,
* restricting is relative to the pointer coordinates. You can change
* this by setting the
* [`elementRect`](https://github.com/taye/interact.js/pull/72).
**
- newValue (object) #optional an object with keys drag, resize, and/or gesture whose values are rects, Elements, CSS selectors, or 'parent' or 'self'
= (object) The current restrictions object or this Interactable
**
| interact(element).restrict({
| // the rect will be `interact.getElementRect(element.parentNode)`
| drag: element.parentNode,
|
| // x and y are relative to the the interactable's origin
| resize: { x: 100, y: 100, width: 200, height: 200 }
| })
|
| interact('.draggable').restrict({
| // the rect will be the selected element's parent
| drag: 'parent',
|
| // do not restrict during normal movement.
| // Instead, trigger only one restricted move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
| });
\*/
restrict: function (newValue) {
if (newValue === undefined) {
return this.options.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
var newRestrictions = {};
if (isObject(newValue.drag) || trySelector(newValue.drag)) {
newRestrictions.drag = newValue.drag;
}
if (isObject(newValue.resize) || trySelector(newValue.resize)) {
newRestrictions.resize = newValue.resize;
}
if (isObject(newValue.gesture) || trySelector(newValue.gesture)) {
newRestrictions.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
newRestrictions.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
newRestrictions.elementRect = newValue.elementRect;
}
this.options.restrictEnabled = true;
this.options.restrict = newRestrictions;
}
else if (newValue === null) {
delete this.options.restrict;
delete this.options.restrictEnabled;
}
return this;
},
/*\
* Interactable.context
[ method ]
*
* Get's the selector context Node of the Interactable. The default is `window.document`.
*
= (Node) The context Node of this Interactable
**
\*/
context: function () {
return this._context;
},
_context: document,
/*\
* Interactable.ignoreFrom
[ method ]
*
* If the target of the `mousedown`, `pointerdown` or `touchstart`
* event or any of it's parents match the given CSS selector or
* Element, no drag/resize/gesture is started.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to not ignore any elements
= (string | Element | object) The current ignoreFrom value or this Interactable
**
| interact(element, { ignoreFrom: document.getElementById('no-action') });
| // or
| interact(element).ignoreFrom('input, textarea, a');
\*/
ignoreFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.ignoreFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.ignoreFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.ignoreFrom;
return this;
}
return this.options.ignoreFrom;
},
/*\
* Interactable.allowFrom
[ method ]
*
* A drag/resize/gesture is started only If the target of the
* `mousedown`, `pointerdown` or `touchstart` event or any of it's
* parents match the given CSS selector or Element.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to allow from any element
= (string | Element | object) The current allowFrom value or this Interactable
**
| interact(element, { allowFrom: document.getElementById('drag-handle') });
| // or
| interact(element).allowFrom('.handle');
\*/
allowFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.allowFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.allowFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.allowFrom;
return this;
}
return this.options.allowFrom;
},
/*\
* Interactable.validateSetting
[ method ]
*
- context (string) eg. 'snap', 'autoScroll'
- option (string) The name of the value being set
- value (any type) The value being validated
*
= (typeof value) A valid value for the give context-option pair
* - null if defaultOptions[context][value] is undefined
* - value if it is the same type as defaultOptions[context][value],
* - this.options[context][value] if it is the same type as defaultOptions[context][value],
* - or defaultOptions[context][value]
\*/
validateSetting: function (context, option, value) {
var defaults = defaultOptions[context],
current = this.options[context];
if (defaults !== undefined && defaults[option] !== undefined) {
if ('objectTypes' in defaults && defaults.objectTypes.test(option)) {
if (isObject(value)) { return value; }
else {
return (option in current && isObject(current[option])
? current [option]
: defaults[option]);
}
}
if ('arrayTypes' in defaults && defaults.arrayTypes.test(option)) {
if (isArray(value)) { return value; }
else {
return (option in current && isArray(current[option])
? current[option]
: defaults[option]);
}
}
if ('stringTypes' in defaults && defaults.stringTypes.test(option)) {
if (isString(value)) { return value; }
else {
return (option in current && isString(current[option])
? current[option]
: defaults[option]);
}
}
if ('numberTypes' in defaults && defaults.numberTypes.test(option)) {
if (isNumber(value)) { return value; }
else {
return (option in current && isNumber(current[option])
? current[option]
: defaults[option]);
}
}
if ('boolTypes' in defaults && defaults.boolTypes.test(option)) {
if (isBool(value)) { return value; }
else {
return (option in current && isBool(current[option])
? current[option]
: defaults[option]);
}
}
if ('elementTypes' in defaults && defaults.elementTypes.test(option)) {
if (isElement(value)) { return value; }
else {
return (option in current && isElement(current[option])
? current[option]
: defaults[option]);
}
}
}
return null;
},
/*\
* Interactable.element
[ method ]
*
* If this is not a selector Interactable, it returns the element this
* interactable represents
*
= (Element) HTML / SVG Element
\*/
element: function () {
return this._element;
},
/*\
* Interactable.fire
[ method ]
*
* Calls listeners for the given InteractEvent type bound globally
* and directly to this Interactable
*
- iEvent (InteractEvent) The InteractEvent object to be fired on this Interactable
= (Interactable) this Interactable
\*/
fire: function (iEvent) {
if (!(iEvent && iEvent.type) || !contains(eventTypes, iEvent.type)) {
return this;
}
var listeners,
i,
len,
onEvent = 'on' + iEvent.type,
funcName = '';
// Interactable#on() listeners
if (iEvent.type in this._iEvents) {
listeners = this._iEvents[iEvent.type];
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
// interactable.onevent listener
if (isFunction(this[onEvent])) {
funcName = this[onEvent].name;
this[onEvent](iEvent);
}
// interact.on() listeners
if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) {
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
return this;
},
/*\
* Interactable.on
[ method ]
*
* Binds a listener for an InteractEvent or DOM event.
*
- eventType (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) This Interactable
\*/
on: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.on(eventType[i], listener, useCapture);
}
return this;
}
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// convert to boolean
useCapture = useCapture? true: false;
if (contains(eventTypes, eventType)) {
// if this type of event was never bound to this Interactable
if (!(eventType in this._iEvents)) {
this._iEvents[eventType] = [listener];
}
else {
this._iEvents[eventType].push(listener);
}
}
// delegated event for selector
else if (this.selector) {
if (!delegatedEvents[eventType]) {
delegatedEvents[eventType] = {
selectors: [],
contexts : [],
listeners: []
};
// add delegate listener functions
for (i = 0; i < documents.length; i++) {
events.add(documents[i], eventType, delegateListener);
events.add(documents[i], eventType, delegateUseCapture, true);
}
}
var delegated = delegatedEvents[eventType],
index;
for (index = delegated.selectors.length - 1; index >= 0; index--) {
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
break;
}
}
if (index === -1) {
index = delegated.selectors.length;
delegated.selectors.push(this.selector);
delegated.contexts .push(this._context);
delegated.listeners.push([]);
}
// keep listener and useCapture flag
delegated.listeners[index].push([listener, useCapture]);
}
else {
events.add(this._element, eventType, listener, useCapture);
}
return this;
},
/*\
* Interactable.off
[ method ]
*
* Removes an InteractEvent or DOM event listener
*
- eventType (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) This Interactable
\*/
off: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.off(eventType[i], listener, useCapture);
}
return this;
}
var eventList,
index = -1;
// convert to boolean
useCapture = useCapture? true: false;
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// if it is an action event type
if (contains(eventTypes, eventType)) {
eventList = this._iEvents[eventType];
if (eventList && (index = indexOf(eventList, listener)) !== -1) {
this._iEvents[eventType].splice(index, 1);
}
}
// delegated event
else if (this.selector) {
var delegated = delegatedEvents[eventType],
matchFound = false;
if (!delegated) { return this; }
// count from last index of delegated to 0
for (index = delegated.selectors.length - 1; index >= 0; index--) {
// look for matching selector and context Node
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
var listeners = delegated.listeners[index];
// each item of the listeners array is an array: [function, useCaptureFlag]
for (i = listeners.length - 1; i >= 0; i--) {
var fn = listeners[i][0],
useCap = listeners[i][1];
// check if the listener functions and useCapture flags match
if (fn === listener && useCap === useCapture) {
// remove the listener from the array of listeners
listeners.splice(i, 1);
// if all listeners for this interactable have been removed
// remove the interactable from the delegated arrays
if (!listeners.length) {
delegated.selectors.splice(index, 1);
delegated.contexts .splice(index, 1);
delegated.listeners.splice(index, 1);
// remove delegate function from context
events.remove(this._context, eventType, delegateListener);
events.remove(this._context, eventType, delegateUseCapture, true);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[eventType] = null;
}
}
// only remove one listener
matchFound = true;
break;
}
}
if (matchFound) { break; }
}
}
}
// remove listener from this Interatable's element
else {
events.remove(this, listener, useCapture);
}
return this;
},
/*\
* Interactable.set
[ method ]
*
* Reset the options of this Interactable
- options (object) The new settings to apply
= (object) This Interactablw
\*/
set: function (options) {
if (!options || !isObject(options)) {
options = {};
}
this.options = new IOptions(options);
this.draggable ('draggable' in options? options.draggable : this.options.draggable );
this.dropzone ('dropzone' in options? options.dropzone : this.options.dropzone );
this.resizable ('resizable' in options? options.resizable : this.options.resizable );
this.gesturable('gesturable' in options? options.gesturable: this.options.gesturable);
var settings = [
'accept', 'actionChecker', 'allowFrom', 'autoScroll', 'deltaSource',
'dropChecker', 'ignoreFrom', 'inertia', 'origin', 'preventDefault',
'rectChecker', 'restrict', 'snap', 'styleCursor'
];
for (var i = 0, len = settings.length; i < len; i++) {
var setting = settings[i];
if (setting in options) {
this[setting](options[setting]);
}
}
return this;
},
/*\
* Interactable.unset
[ method ]
*
* Remove this interactable from the list of interactables and remove
* it's drag, drop, resize and gesture capabilities
*
= (object) @interact
\*/
unset: function () {
events.remove(this, 'all');
if (!isString(this.selector)) {
events.remove(this, 'all');
if (this.options.styleCursor) {
this._element.style.cursor = '';
}
}
else {
// remove delegated events
for (var type in delegatedEvents) {
var delegated = delegatedEvents[type];
for (var i = 0; i < delegated.selectors.length; i++) {
if (delegated.selectors[i] === this.selector
&& delegated.contexts[i] === this._context) {
delegated.selectors.splice(i, 1);
delegated.contexts .splice(i, 1);
delegated.listeners.splice(i, 1);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[type] = null;
}
}
events.remove(this._context, type, delegateListener);
events.remove(this._context, type, delegateUseCapture, true);
break;
}
}
}
this.dropzone(false);
interactables.splice(indexOf(interactables, this), 1);
return interact;
}
};
Interactable.prototype.gestureable = Interactable.prototype.gesturable;
Interactable.prototype.resizeable = Interactable.prototype.resizable;
/*\
* interact.isSet
[ method ]
*
* Check if an element has been set
- element (Element) The Element being searched for
= (boolean) Indicates if the element or CSS selector was previously passed to interact
\*/
interact.isSet = function(element, options) {
return interactables.indexOfElement(element, options && options.context) !== -1;
};
/*\
* interact.on
[ method ]
*
* Adds a global listener for an InteractEvent or adds a DOM event to
* `document`
*
- type (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) interact
\*/
interact.on = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.on(type[i], listener, useCapture);
}
return interact;
}
// if it is an InteractEvent type, add listener to globalEvents
if (contains(eventTypes, type)) {
// if this type of event was never bound
if (!globalEvents[type]) {
globalEvents[type] = [listener];
}
else {
globalEvents[type].push(listener);
}
}
// If non InteractEvent type, addEventListener to document
else {
events.add(document, type, listener, useCapture);
}
return interact;
};
/*\
* interact.off
[ method ]
*
* Removes a global InteractEvent listener or DOM event from `document`
*
- type (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) interact
\*/
interact.off = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.off(type[i], listener, useCapture);
}
return interact;
}
if (!contains(eventTypes, type)) {
events.remove(document, type, listener, useCapture);
}
else {
var index;
if (type in globalEvents
&& (index = indexOf(globalEvents[type], listener)) !== -1) {
globalEvents[type].splice(index, 1);
}
}
return interact;
};
/*\
* interact.simulate
[ method ]
*
* Simulate pointer down to begin to interact with an interactable element
- action (string) The action to be performed - drag, resize, etc.
- element (Element) The DOM Element to resize/drag
- pointerEvent (object) #optional Pointer event whose pageX/Y coordinates will be the starting point of the interact drag/resize
= (object) interact
\*/
interact.simulate = function (action, element, pointerEvent) {
var event = {},
clientRect;
if (action === 'resize') {
action = 'resizexy';
}
// return if the action is not recognised
if (!/^(drag|resizexy|resizex|resizey)$/.test(action)) {
return interact;
}
if (pointerEvent) {
extend(event, pointerEvent);
}
else {
clientRect = (element instanceof SVGElement)
? element.getBoundingClientRect()
: clientRect = element.getClientRects()[0];
if (action === 'drag') {
event.pageX = clientRect.left + clientRect.width / 2;
event.pageY = clientRect.top + clientRect.height / 2;
}
else {
event.pageX = clientRect.right;
event.pageY = clientRect.bottom;
}
}
event.target = event.currentTarget = element;
event.preventDefault = event.stopPropagation = blank;
listeners.pointerDown(event, action);
return interact;
};
/*\
* interact.enableDragging
[ method ]
*
* Returns or sets whether dragging is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableDragging = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.drag = newValue;
return interact;
}
return actionIsEnabled.drag;
};
/*\
* interact.enableResizing
[ method ]
*
* Returns or sets whether resizing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableResizing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.resize = newValue;
return interact;
}
return actionIsEnabled.resize;
};
/*\
* interact.enableGesturing
[ method ]
*
* Returns or sets whether gesturing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableGesturing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.gesture = newValue;
return interact;
}
return actionIsEnabled.gesture;
};
interact.eventTypes = eventTypes;
/*\
* interact.debug
[ method ]
*
* Returns debugging data
= (object) An object with properties that outline the current state and expose internal functions and variables
\*/
interact.debug = function () {
var interaction = interactions[0] || new Interaction();
return {
interactions : interactions,
target : interaction.target,
dragging : interaction.dragging,
resizing : interaction.resizing,
gesturing : interaction.gesturing,
prepared : interaction.prepared,
matches : interaction.matches,
matchElements : interaction.matchElements,
prevCoords : interaction.prevCoords,
startCoords : interaction.startCoords,
pointerIds : interaction.pointerIds,
pointers : interaction.pointers,
addPointer : listeners.addPointer,
removePointer : listeners.removePointer,
recordPointer : listeners.recordPointer,
snap : interaction.snapStatus,
restrict : interaction.restrictStatus,
inertia : interaction.inertiaStatus,
downTime : interaction.downTimes[0],
downEvent : interaction.downEvent,
downPointer : interaction.downPointer,
prevEvent : interaction.prevEvent,
Interactable : Interactable,
IOptions : IOptions,
interactables : interactables,
pointerIsDown : interaction.pointerIsDown,
defaultOptions : defaultOptions,
defaultActionChecker : defaultActionChecker,
actionCursors : actionCursors,
dragMove : listeners.dragMove,
resizeMove : listeners.resizeMove,
gestureMove : listeners.gestureMove,
pointerUp : listeners.pointerUp,
pointerDown : listeners.pointerDown,
pointerMove : listeners.pointerMove,
pointerHover : listeners.pointerHover,
events : events,
globalEvents : globalEvents,
delegatedEvents : delegatedEvents
};
};
// expose the functions used to calculate multi-touch properties
interact.getTouchAverage = touchAverage;
interact.getTouchBBox = touchBBox;
interact.getTouchDistance = touchDistance;
interact.getTouchAngle = touchAngle;
interact.getElementRect = getElementRect;
interact.matchesSelector = matchesSelector;
interact.closest = closest;
/*\
* interact.margin
[ method ]
*
* Returns or sets the margin for autocheck resizing used in
* @Interactable.getAction. That is the distance from the bottom and right
* edges of an element clicking in which will start resizing
*
- newValue (number) #optional
= (number | interact) The current margin value or interact
\*/
interact.margin = function (newvalue) {
if (isNumber(newvalue)) {
margin = newvalue;
return interact;
}
return margin;
};
/*\
* interact.styleCursor
[ styleCursor ]
*
* Returns or sets whether the cursor style of the document is changed
* depending on what action is being performed
*
- newValue (boolean) #optional
= (boolean | interact) The current setting of interact
\*/
interact.styleCursor = function (newValue) {
if (isBool(newValue)) {
defaultOptions.styleCursor = newValue;
return interact;
}
return defaultOptions.styleCursor;
};
/*\
* interact.autoScroll
[ method ]
*
* Returns or sets whether or not actions near the edges of the window or
* specified container element trigger autoScroll by default
*
- options (boolean | object) true or false to simply enable or disable or an object with margin, distance, container and interval properties
= (object) interact
* or
= (boolean | object) `false` if autoscroll is disabled and the default autoScroll settings if it is enabled
\*/
interact.autoScroll = function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
defaultOptions.autoScrollEnabled = true;
if (isNumber(options.margin)) { defaults.margin = options.margin;}
if (isNumber(options.speed) ) { defaults.speed = options.speed ;}
defaults.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
return interact;
}
if (isBool(options)) {
defaultOptions.autoScrollEnabled = options;
return interact;
}
// return the autoScroll settings if autoScroll is enabled
// otherwise, return false
return defaultOptions.autoScrollEnabled? defaults: false;
};
/*\
* interact.snap
[ method ]
*
* Returns or sets whether actions are constrained to a grid or a
* collection of coordinates
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object with some of the following properties
o {
o mode : 'grid', 'anchor' or 'path',
o range : the distance within which snapping to a point occurs,
o actions: ['drag', 'resizex', 'resizey', 'resizexy'], an array of action types that can snapped (['drag'] by default) (no gesture)
o grid : {
o x, y: the distances between the grid lines,
o },
o gridOffset: {
o x, y: the x/y-axis values of the grid origin
o },
o anchors: [
o {
o x: x coordinate to snap to,
o y: y coordinate to snap to,
o range: optional range for this anchor
o }
o {
o another anchor
o }
o ]
o }
*
= (object | interact) The default snap settings object or interact
\*/
interact.snap = function (options) {
var snap = defaultOptions.snap;
if (isObject(options)) {
defaultOptions.snapEnabled = true;
if (isString(options.mode) ) { snap.mode = options.mode; }
if (isBool (options.endOnly) ) { snap.endOnly = options.endOnly; }
if (isNumber(options.range) ) { snap.range = options.range; }
if (isArray (options.actions) ) { snap.actions = options.actions; }
if (isArray (options.anchors) ) { snap.anchors = options.anchors; }
if (isObject(options.grid) ) { snap.grid = options.grid; }
if (isObject(options.gridOffset) ) { snap.gridOffset = options.gridOffset; }
if (isObject(options.elementOrigin)) { snap.elementOrigin = options.elementOrigin; }
return interact;
}
if (isBool(options)) {
defaultOptions.snapEnabled = options;
return interact;
}
return defaultOptions.snapEnabled;
};
/*\
* interact.inertia
[ method ]
*
* Returns or sets inertia settings.
*
* See @Interactable.inertia
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object of inertia options
= (object | interact) The default inertia settings object or interact
\*/
interact.inertia = function (options) {
var inertia = defaultOptions.inertia;
if (isObject(options)) {
defaultOptions.inertiaEnabled = true;
if (isNumber(options.resistance) ) { inertia.resistance = options.resistance ; }
if (isNumber(options.minSpeed) ) { inertia.minSpeed = options.minSpeed ; }
if (isNumber(options.endSpeed) ) { inertia.endSpeed = options.endSpeed ; }
if (isNumber(options.smoothEndDuration)) { inertia.smoothEndDuration = options.smoothEndDuration; }
if (isBool (options.allowResume) ) { inertia.allowResume = options.allowResume ; }
if (isBool (options.zeroResumeDelta) ) { inertia.zeroResumeDelta = options.zeroResumeDelta ; }
if (isArray (options.actions) ) { inertia.actions = options.actions ; }
return interact;
}
if (isBool(options)) {
defaultOptions.inertiaEnabled = options;
return interact;
}
return {
enabled: defaultOptions.inertiaEnabled,
resistance: inertia.resistance,
minSpeed: inertia.minSpeed,
endSpeed: inertia.endSpeed,
actions: inertia.actions,
allowResume: inertia.allowResume,
zeroResumeDelta: inertia.zeroResumeDelta
};
};
/*\
* interact.supportsTouch
[ method ]
*
= (boolean) Whether or not the browser supports touch input
\*/
interact.supportsTouch = function () {
return supportsTouch;
};
/*\
* interact.supportsPointerEvent
[ method ]
*
= (boolean) Whether or not the browser supports PointerEvents
\*/
interact.supportsPointerEvent = function () {
return supportsPointerEvent;
};
/*\
* interact.currentAction
[ method ]
*
= (string) What action is currently being performed
\*/
interact.currentAction = function () {
for (var i = 0, len = interactions.length; i < len; i++) {
var action = interactions[i].currentAction();
if (action) { return action; }
}
return null;
};
/*\
* interact.stop
[ method ]
*
* Cancels the current interaction
*
- event (Event) An event on which to call preventDefault()
= (object) interact
\*/
interact.stop = function (event) {
for (var i = interactions.length - 1; i > 0; i--) {
interactions[i].stop(event);
}
return interact;
};
/*\
* interact.dynamicDrop
[ method ]
*
* Returns or sets whether the dimensions of dropzone elements are
* calculated on every dragmove or only on dragstart for the default
* dropChecker
*
- newValue (boolean) #optional True to check on each move. False to check only before start
= (boolean | interact) The current setting or interact
\*/
interact.dynamicDrop = function (newValue) {
if (isBool(newValue)) {
//if (dragging && dynamicDrop !== newValue && !newValue) {
//calcRects(dropzones);
//}
dynamicDrop = newValue;
return interact;
}
return dynamicDrop;
};
/*\
* interact.deltaSource
[ method ]
* Returns or sets weather pageX/Y or clientX/Y is used to calculate dx/dy.
*
* See @Interactable.deltaSource
*
- newValue (string) #optional 'page' or 'client'
= (string | Interactable) The current setting or interact
\*/
interact.deltaSource = function (newValue) {
if (newValue === 'page' || newValue === 'client') {
defaultOptions.deltaSource = newValue;
return this;
}
return defaultOptions.deltaSource;
};
/*\
* interact.restrict
[ method ]
*
* Returns or sets the default rectangles within which actions (after snap
* calculations) are restricted.
*
* See @Interactable.restrict
*
- newValue (object) #optional an object with keys drag, resize, and/or gesture and rects or Elements as values
= (object) The current restrictions object or interact
\*/
interact.restrict = function (newValue) {
var defaults = defaultOptions.restrict;
if (newValue === undefined) {
return defaultOptions.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
if (isObject(newValue.drag) || /^parent$|^self$/.test(newValue.drag)) {
defaults.drag = newValue.drag;
}
if (isObject(newValue.resize) || /^parent$|^self$/.test(newValue.resize)) {
defaults.resize = newValue.resize;
}
if (isObject(newValue.gesture) || /^parent$|^self$/.test(newValue.gesture)) {
defaults.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
defaults.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
defaults.elementRect = newValue.elementRect;
}
defaultOptions.restrictEnabled = true;
}
else if (newValue === null) {
defaults.drag = defaults.resize = defaults.gesture = null;
defaults.endOnly = false;
}
return this;
};
/*\
* interact.pointerMoveTolerance
[ method ]
* Returns or sets the distance the pointer must be moved before an action
* sequence occurs. This also affects tolerance for tap events.
*
- newValue (number) #optional The movement from the start position must be greater than this value
= (number | Interactable) The current setting or interact
\*/
interact.pointerMoveTolerance = function (newValue) {
if (isNumber(newValue)) {
defaultOptions.pointerMoveTolerance = newValue;
return this;
}
return defaultOptions.pointerMoveTolerance;
};
/*\
* interact.maxInteractions
[ method ]
**
* Returns or sets the maximum number of concurrent interactions allowed.
* By default only 1 interaction is allowed at a time (for backwards
* compatibility). To allow multiple interactions on the same Interactables
* and elements, you need to enable it in the draggable, resizable and
* gesturable `'max'` and `'maxPerElement'` options.
**
- newValue (number) #optional Any number. newValue <= 0 means no interactions.
\*/
interact.maxInteractions = function (newValue) {
if (isNumber(newValue)) {
maxInteractions = newValue;
return this;
}
return maxInteractions;
};
function endAllInteractions (event) {
for (var i = 0; i < interactions.length; i++) {
interactions[i].pointerEnd(event, event);
}
}
function listenToDocument (doc) {
if (contains(documents, doc)) { return; }
var win = doc.defaultView || doc.parentWindow;
// add delegate event listener
for (var eventType in delegatedEvents) {
events.add(doc, eventType, delegateListener);
events.add(doc, eventType, delegateUseCapture, true);
}
if (PointerEvent) {
if (PointerEvent === win.MSPointerEvent) {
pEventTypes = {
up: 'MSPointerUp', down: 'MSPointerDown', over: 'mouseover',
out: 'mouseout', move: 'MSPointerMove', cancel: 'MSPointerCancel' };
}
else {
pEventTypes = {
up: 'pointerup', down: 'pointerdown', over: 'pointerover',
out: 'pointerout', move: 'pointermove', cancel: 'pointercancel' };
}
events.add(doc, pEventTypes.down , listeners.selectorDown );
events.add(doc, pEventTypes.move , listeners.pointerMove );
events.add(doc, pEventTypes.over , listeners.pointerOver );
events.add(doc, pEventTypes.out , listeners.pointerOut );
events.add(doc, pEventTypes.up , listeners.pointerUp );
events.add(doc, pEventTypes.cancel, listeners.pointerCancel);
// autoscroll
events.add(doc, pEventTypes.move, autoScroll.edgeMove);
}
else {
events.add(doc, 'mousedown', listeners.selectorDown);
events.add(doc, 'mousemove', listeners.pointerMove );
events.add(doc, 'mouseup' , listeners.pointerUp );
events.add(doc, 'mouseover', listeners.pointerOver );
events.add(doc, 'mouseout' , listeners.pointerOut );
events.add(doc, 'touchstart' , listeners.selectorDown );
events.add(doc, 'touchmove' , listeners.pointerMove );
events.add(doc, 'touchend' , listeners.pointerUp );
events.add(doc, 'touchcancel', listeners.pointerCancel);
// autoscroll
events.add(doc, 'mousemove', autoScroll.edgeMove);
events.add(doc, 'touchmove', autoScroll.edgeMove);
}
events.add(win, 'blur', endAllInteractions);
try {
if (win.frameElement) {
var parentDoc = win.frameElement.ownerDocument,
parentWindow = parentDoc.defaultView;
events.add(parentDoc , 'mouseup' , listeners.pointerEnd);
events.add(parentDoc , 'touchend' , listeners.pointerEnd);
events.add(parentDoc , 'touchcancel' , listeners.pointerEnd);
events.add(parentDoc , 'pointerup' , listeners.pointerEnd);
events.add(parentDoc , 'MSPointerUp' , listeners.pointerEnd);
events.add(parentWindow, 'blur' , endAllInteractions );
}
}
catch (error) {
interact.windowParentError = error;
}
// For IE's lack of Event#preventDefault
if (events.useAttachEvent) {
events.add(doc, 'selectstart', function (event) {
var interaction = interactions[0];
if (interaction.currentAction()) {
interaction.checkAndPreventDefault(event);
}
});
}
documents.push(doc);
}
listenToDocument(document);
function indexOf (array, target) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
function contains (array, target) {
return indexOf(array, target) !== -1;
}
function matchesSelector (element, selector, nodeList) {
if (ie8MatchesSelector) {
return ie8MatchesSelector(element, selector, nodeList);
}
return element[prefixedMatchesSelector](selector);
}
// For IE8's lack of an Element#matchesSelector
// taken from http://tanalin.com/en/blog/2012/12/matches-selector-ie8/ and modified
if (!(prefixedMatchesSelector in Element.prototype) || !isFunction(Element.prototype[prefixedMatchesSelector])) {
ie8MatchesSelector = function (element, selector, elems) {
elems = elems || element.parentNode.querySelectorAll(selector);
for (var i = 0, len = elems.length; i < len; i++) {
if (elems[i] === element) {
return true;
}
}
return false;
};
}
// requestAnimationFrame polyfill
(function() {
var lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
reqFrame = window[vendors[x]+'RequestAnimationFrame'];
cancelFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!reqFrame) {
reqFrame = function(callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!cancelFrame) {
cancelFrame = function(id) {
clearTimeout(id);
};
}
}());
/* global exports: true, module, define */
// http://documentcloud.github.io/underscore/docs/underscore.html#section-11
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = interact;
}
exports.interact = interact;
}
// AMD
else if (typeof define === 'function' && define.amd) {
define('interact', function() {
return interact;
});
}
else {
window.interact = interact;
}
} ());
|
/*
Based on:
Copyright (c) 2016 Wilson Page wilsonpage@me.com
https://github.com/wilsonpage/fastdom
*/
import { requestAnimationFrame } from './index';
export const fastdom = {
reads: [],
writes: [],
measure: function(task) {
this.reads.push(task);
scheduleFlush(this);
return task;
},
mutate: function(task) {
this.writes.push(task);
scheduleFlush(this);
return task;
},
clear: function(task) {
return remove(this.reads, task) || remove(this.writes, task);
}
};
function scheduleFlush(fastdom) {
if (!fastdom.scheduled) {
fastdom.scheduled = true;
requestAnimationFrame(flush.bind(null, fastdom));
}
}
function flush(fastdom) {
runTasks(fastdom.reads);
runTasks(fastdom.writes.splice(0, fastdom.writes.length));
fastdom.scheduled = false;
if (fastdom.reads.length || fastdom.writes.length) {
scheduleFlush(fastdom);
}
}
function runTasks(tasks) {
var task;
while (task = tasks.shift()) {
task();
}
}
function remove(array, item) {
var index = array.indexOf(item);
return !!~index && !!array.splice(index, 1);
}
|
export const SET_SORT = 'SET_SORT';
export const SORT_ASC = 'ASC';
export const SORT_DESC = 'DESC';
export const SET_PAGE = 'SET_PAGE';
export const SET_FILTER = 'SET_FILTER';
const oppositeOrder = direction =>
direction === SORT_DESC ? SORT_ASC : SORT_DESC;
/**
* This reducer is for the react-router query string, NOT for redux.
*/
export default (previousState, { type, payload }) => {
switch (type) {
case SET_SORT:
if (payload === previousState.sort) {
return {
...previousState,
order: oppositeOrder(previousState.order),
page: 1,
};
}
return {
...previousState,
sort: payload,
order: SORT_ASC,
page: 1,
};
case SET_PAGE:
return { ...previousState, page: payload };
case SET_FILTER: {
return { ...previousState, page: 1, filter: payload };
}
default:
return previousState;
}
};
|
(function () {
'use strict';
// Processes overloads for a set of arguments. Should be called as
// via overload(arguments). You can pass it an array of arguments, but just using
// the built in arguments object is the intended use.
var Overload = function (args, expectedType) {
var _overload = this;
var result;
var hasResult = false;
if (!expectedType) {
expectedType = 'ANY';
}
// Instructs function to expect a particular return type, regardless of which
// overload is called. Default is any. Can alse be provided through the constructor.
this.expect = function (expected) {
expectedType = expected;
};
// When...do functions describle the the conditions for overloads.
// Example: .when(String, String).do(function(s1, s2){...})
this.when = function () {
var _when = this;
var types = [];
var lastAsArray = false;
for (var i in arguments) {
if (Array.isArray(arguments[i])) {
types.push(arguments[i][0]);
lastAsArray = true;
} else {
types.push(arguments[i]);
}
}
// The function to call if the when function's types are met. Will pass in the
// original arguments and be called in the context of the overload statement.
this.do = function (callback) {
if (hasResult) return _overload;
if (matchTypes(types, args, lastAsArray)) {
var argArray = [];
var paramArray = [];
for (var i in args) {
if (lastAsArray && i >= types.length -1) {
paramArray.push(args[i]);
} else {
argArray.push(args[i]);
}
}
if (paramArray.length > 0) {
argArray.push(paramArray);
}
result = callback.apply(args.caller, argArray);
hasResult = true;
}
return _overload;
};
return _when;
};
// Function called if no overload has been found..
this.otherwise = function (callback) {
if (hasResult) return _overload;
result = callback.apply(args.caller, args);
hasResult = true;
return _overload;
};
// Returns the result of the matching overload.
this.result = function () {
if (!hasResult) {
throw new Error('No overload matching the supplied parameters: ' + args);
}
if (!matchType(result, expectedType)) {
throw new TypeError('Unexpected type of return: ' + typeof result);
}
return result;
};
function matchTypes(types, test, extend) {
if (!extend && types.length !== test.length) {
return false;
}
if (types.length > test.length) {
return false;
}
for (var i in test) {
if (extend && i >= types.length) {
if (!matchType(test[i], types[types.length - 1])) {
return false;
}
} else {
if (!matchType(test[i], types[i])) {
return false;
}
}
}
return true;
}
function matchType(obj, typ) {
if (typeof typ === 'string' &&
typ.toUpperCase() === 'ANY') {
return true;
}
if (typeof typ === 'function' &&
(obj.constructor === typ || obj instanceof typ)) {
return true;
}
return false;
}
};
function overload(args, expectedType) {
return new Overload(args, expectedType);
}
if (typeof window !== 'undefined') {
window.overload = overload;
} else {
module.exports = overload;
}
})(); |
/**
* 商品数量加减插件
* wll-2013/03/29
* jquery.goodnums.js
*
*
*/
jQuery(function(){
/**
* 删除商品
*
* 使用说明:
* 元素必须具备以下属性
* 必须:zid 总价ID
* 必须:xclass 每个商品小计的 class
* 必须:ValId input:text 当前改变商品数量的ID
*
* Demo:
* jQuery(".shop_good_delete").goodDelete({zid:'good_zongjia',xclass:'good_xiaojis'});
*/
jQuery.fn.goodDelete = function(options){
var defaults = {
Event : "click",
zid : 'goods_zongjia',
xclass : 'xclass'
};
var options = jQuery.extend(defaults,options);
var obj = jQuery(this);
obj.live(options.Event,function(e){
if(confirm('确认删除该商品吗?')){
jQuery(this).closest('tr').hide('1000').remove();
goods_zongjia(options.zid,options.xclass);
}
});
};
/**
* 购物车数量加减
*
* 使用说明:
* 元素必须具备以下属性
* 必须:zid 总价ID
* 必须:xclass 每个商品小计的 class
* 必须:ValId input:text 当前改变商品数量的ID
* 必须:ty 进行的运算类型 可选值: '+'或'-'
* 可选:max 允许最大商品数量 注:也可在调用时批量定义
* 可选:min 允许最少商品数量 注:也可在调用时批量定义
*
* Demo:
* jQuery(".this_good_nums").goodnums({zid:'good_zongjia',xclass:'good_xiaojis',max:5,min:1,typ:'+'});
*/
jQuery.fn.goodnums = function(options){
var defaults = {
Event : "click",
zid : 'goods_zongjia',
xclass : 'xclass',
type : '+',
max : 9999,
min : 1
};
var options = jQuery.extend(defaults,options);
var obj = jQuery(this);
obj.live(options.Event,function(e){
var valId = jQuery(this).attr('valId');
var did = jQuery(this).attr('did');
var xid = jQuery(this).attr('xid');
var type = jQuery(this).attr('ty') ? jQuery(this).attr('ty') : options.type;
var max = jQuery(this).attr('max') ? jQuery(this).attr('max') : options.max;
var min = jQuery(this).attr('min') ? jQuery(this).attr('min') : options.min;
//var max = options.max;
//var min = options.min;
//判断 Value 对象是否存在
if( !jQuery("#"+valId) ){
alert('参数错误');
return false;
}
if( !jQuery("#"+did) ){
alert('参数错误');
return false;
}
if( !jQuery("#"+xid) ){
alert('参数错误');
return false;
}
// 获取当前 Value 对象
var num_obj = jQuery("#"+valId);
var danjia_obj = jQuery("#"+did);
var xiaoji_obj = jQuery("#"+xid);
// 获取 选购数量,及单价
var nums = num_obj.val();
var danjia = danjia_obj.text();
// 将需要处理的 数据全部转换为 Int
nums = parseInt(nums);
max = parseInt(max);
min = parseInt(min);
danjia = parseFloat(danjia);
if(type == '+'){
if(nums < max){
nums += 1;
num_obj.val(nums);
var xiaoji = danjia*nums;
xiaoji_obj.text(xiaoji.toFixed(2));
goods_zongjia(options.zid,options.xclass);
}
}
else if( type == '-'){
if(nums > min){
nums -= 1;
num_obj.val(nums);
var xiaoji = danjia*nums;
xiaoji_obj.text(xiaoji.toFixed(2));
goods_zongjia(options.zid,options.xclass);
}
}
});
}
/**
* Public Function
*/
/**
* 计算购物车总价
*
* zid: 总价ID
* xclass 单个商品小计class
*
* Demo: goods_zongjia(options.zid,options.xclass);
*/
function goods_zongjia(zid,xclass){
var zongjia = 0.00;
jQuery('.'+xclass).each(function(){
zongjia += parseFloat(jQuery(this).text());
});
jQuery('#'+zid).text(zongjia.toFixed(2));
}
}); |
module.exports = {
mode: "production",
entry: "./index",
stats: {
colors: true,
hash: false,
entrypoints: true
},
performance: {
hints: false
}
};
|
/**
* Blueprint API Configuration
* (sails.config.blueprints)
*
* These settings are for the global configuration of blueprint routes and
* request options (which impact the behavior of blueprint actions).
*
* You may also override any of these settings on a per-controller basis
* by defining a '_config' key in your controller defintion, and assigning it
* a configuration object with overrides for the settings in this file.
* A lot of the configuration options below affect so-called "CRUD methods",
* or your controllers' `find`, `create`, `update`, and `destroy` actions.
*
* It's important to realize that, even if you haven't defined these yourself, as long as
* a model exists with the same name as the controller, Sails will respond with built-in CRUD
* logic in the form of a JSON API, including support for sort, pagination, and filtering.
*
* For more information on the blueprint API, check out:
* http://sailsjs.org/#/documentation/reference/blueprint-api
*
* For more information on the settings in this file, see:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
*
*/
module.exports.blueprints = {
/***************************************************************************
* *
* Action routes speed up the backend development workflow by *
* eliminating the need to manually bind routes. When enabled, GET, POST, *
* PUT, and DELETE routes will be generated for every one of a controller's *
* actions. *
* *
* If an `index` action exists, additional naked routes will be created for *
* it. Finally, all `actions` blueprints support an optional path *
* parameter, `id`, for convenience. *
* *
* `actions` are enabled by default, and can be OK for production-- *
* however, if you'd like to continue to use controller/action autorouting *
* in a production deployment, you must take great care not to *
* inadvertently expose unsafe/unintentional controller logic to GET *
* requests. *
* *
***************************************************************************/
actions: false,
/***************************************************************************
* *
* RESTful routes (`sails.config.blueprints.rest`) *
* *
* REST blueprints are the automatically generated routes Sails uses to *
* expose a conventional REST API on top of a controller's `find`, *
* `create`, `update`, and `destroy` actions. *
* *
* For example, a BoatController with `rest` enabled generates the *
* following routes: *
* ::::::::::::::::::::::::::::::::::::::::::::::::::::::: *
* GET /boat -> BoatController.find *
* GET /boat/:id -> BoatController.findOne *
* POST /boat -> BoatController.create *
* PUT /boat/:id -> BoatController.update *
* DELETE /boat/:id -> BoatController.destroy *
* *
* `rest` blueprint routes are enabled by default, and are suitable for use *
* in a production scenario, as long you take standard security precautions *
* (combine w/ policies, etc.) *
* *
***************************************************************************/
rest: false,
/***************************************************************************
* *
* Shortcut routes are simple helpers to provide access to a *
* controller's CRUD methods from your browser's URL bar. When enabled, *
* GET, POST, PUT, and DELETE routes will be generated for the *
* controller's`find`, `create`, `update`, and `destroy` actions. *
* *
* `shortcuts` are enabled by default, but should be disabled in *
* production. *
* *
***************************************************************************/
shortcuts: false,
/***************************************************************************
* *
* An optional mount path for all blueprint routes on a controller, *
* including `rest`, `actions`, and `shortcuts`. This allows you to take *
* advantage of blueprint routing, even if you need to namespace your API *
* methods. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
***************************************************************************/
// prefix: '',
/***************************************************************************
* *
* Whether to pluralize controller names in blueprint routes. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
* For example, REST blueprints for `FooController` with `pluralize` *
* enabled: *
* GET /foos/:id? *
* POST /foos *
* PUT /foos/:id? *
* DELETE /foos/:id? *
* *
***************************************************************************/
// pluralize: false,
/***************************************************************************
* *
* Whether the blueprint controllers should populate model fetches with *
* data from other models which are linked by associations *
* *
* If you have a lot of data in one-to-many associations, leaving this on *
* may result in very heavy api calls *
* *
***************************************************************************/
// populate: true,
/****************************************************************************
* *
* Whether to run Model.watch() in the find and findOne blueprint actions. *
* Can be overridden on a per-model basis. *
* *
****************************************************************************/
// autoWatch: true,
/****************************************************************************
* *
* The default number of records to show in the response from a "find" *
* action. Doubles as the default size of populated arrays if populate is *
* true. *
* *
****************************************************************************/
// defaultLimit: 30
};
|
/**
* Used by InPlaceEdit and Uneditable fields
* @module inputex-visus
*/
var lang = Y.Lang,
inputEx = Y.inputEx;
/**
* Contains the various visualization methods
* @class inputEx.visus
* @static
*/
inputEx.visus = {
/**
* Use a rendering function
* options = {visuType: 'func', func: function(data) { ...code here...} }
* @method func
*/
"func": function(options, data) {
return options.func(data);
},
/**
* Use Y.Lang.dump
* options = {visuType: 'dump'}
* @method dump
*/
dump: function(options, data) {
return Y.dump(data);
}
};
/**
* Render 'data' using a visualization function described by 'visuOptions'
* @method renderVisu
* @static
* @param {Object} visuOptions The visu parameters object with: visuType: 'myType', ...args...
* @param {Object} data The input data to send to the template
* @param {HTMLElement || String} parentEl optional Set the result as content of parentEl
* @return {HTMLElement || String} Either the inserted HTMLElement or the String set to parentEl.innerHTML
*/
inputEx.renderVisu = function(visuOptions,data, parentEl) {
var opts = visuOptions || {};
var visuType = opts.visuType || 'dump';
if( !inputEx.visus.hasOwnProperty(visuType) ) {
throw new Error("inputEx: no visu for visuType: "+visuType);
}
var f = inputEx.visus[visuType];
if( !lang.isFunction(f) ) {
throw new Error("inputEx: no visu for visuType: "+visuType);
}
var v = null;
try {
v = f(opts,data);
}
catch(ex) {
throw new Error("inputEx: error while running visu "+visuType+" : "+ex.message);
}
// Get the node
var node = null;
if(parentEl) {
if(lang.isString(parentEl)) {
node = Y.one(parentEl);
}
else {
node = parentEl;
}
}
// Insert it
if(node) {
if(Y.Lang.isObject(v) && v.tagName ) {
node.innerHTML = "";
node.appendChild(v);
}
else {
node.innerHTML = v;
}
}
return v;
};
|
module.exports = {
"_data": {
"FY2013": {
"_startDate": "20130101",
"_endDate": "20131231",
"_closed": true
},
"FY2014": {
"_startDate": "20140101",
"_endDate": "20141231",
"_closed": false
},
"_status": "active",
"_lastModifiedDate": "2014-02-05T10:37:45Z"
},
"_links": {
"_self": "/5v4080jn/settings/fiscal-years"
}
};
|
'use strict';
var should = require('should');
var app = require('../../app');
var request = require('supertest');
describe('GET /api/organizations', function() {
it('should respond with JSON array', function(done) {
request(app)
.get('/api/organizations')
.expect(200)
.expect('Content-Type', /json/)
.end(function(err, res) {
if (err) return done(err);
res.body.should.be.instanceof(Array);
done();
});
});
}); |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Lint = require("tslint");
var sprintf_js_1 = require("sprintf-js");
var SyntaxKind = require("./util/syntaxKind");
var ng2Walker_1 = require("./angular/ng2Walker");
var selectorValidator_1 = require("./util/selectorValidator");
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule(ruleName, value, disabledIntervals) {
var _this = _super.call(this, ruleName, value, disabledIntervals) || this;
if (value[1] === 'camelCase') {
_this.validator = selectorValidator_1.SelectorValidator.camelCase;
}
if (value.length > 2) {
_this.hasPrefix = true;
var prefixExpression = (value.slice(2) || []).join('|');
_this.prefix = (value.slice(2) || []).join(',');
_this.prefixChecker = selectorValidator_1.SelectorValidator.prefix(prefixExpression, 'camelCase');
}
return _this;
}
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new ClassMetadataWalker(sourceFile, this));
};
Rule.prototype.validateName = function (name) {
return this.validator(name);
};
Rule.prototype.validatePrefix = function (prefix) {
return this.prefixChecker(prefix);
};
return Rule;
}(Lint.Rules.AbstractRule));
Rule.metadata = {
ruleName: 'pipe-naming-rule',
type: 'style',
description: "Enforce consistent case and prefix for pipes.",
rationale: "Consistent conventions make it easy to quickly identify and reference assets of different types.",
options: {
'type': 'array',
'items': [
{ 'enum': ['kebab-case', 'attribute'] },
{ 'type': 'string' }
],
'minItems': 1
},
optionExamples: [
"[\"camelCase\", \"myPrefix\"]",
"[\"camelCase\", \"myPrefix\", \"myOtherPrefix\"]",
"[\"kebab-case\", \"my-prefix\"]",
],
optionsDescription: (_a = ["\n * The first item in the array is `\"kebab-case\"` or `\"camelCase\"`, which allows you to pick a case.\n * The rest of the arguments are supported prefixes (given as strings). They are optional."], _a.raw = ["\n * The first item in the array is \\`\"kebab-case\"\\` or \\`\"camelCase\"\\`, which allows you to pick a case.\n * The rest of the arguments are supported prefixes (given as strings). They are optional."], Lint.Utils.dedent(_a)),
typescriptOnly: true,
};
Rule.FAILURE_WITHOUT_PREFIX = 'The name of the Pipe decorator of class %s should' +
' be named camelCase, however its value is "%s".';
Rule.FAILURE_WITH_PREFIX = 'The name of the Pipe decorator of class %s should' +
' be named camelCase with prefix %s, however its value is "%s".';
exports.Rule = Rule;
var ClassMetadataWalker = (function (_super) {
__extends(ClassMetadataWalker, _super);
function ClassMetadataWalker(sourceFile, rule) {
var _this = _super.call(this, sourceFile, rule.getOptions()) || this;
_this.rule = rule;
return _this;
}
ClassMetadataWalker.prototype.visitNg2Pipe = function (controller, decorator) {
var className = controller.name.text;
this.validateProperties(className, decorator);
};
ClassMetadataWalker.prototype.validateProperties = function (className, pipe) {
var argument = this.extractArgument(pipe);
if (argument.kind === SyntaxKind.current().ObjectLiteralExpression) {
argument.properties.filter(function (n) { return n.name.text === 'name'; })
.forEach(this.validateProperty.bind(this, className));
}
};
ClassMetadataWalker.prototype.extractArgument = function (pipe) {
var baseExpr = pipe.expression || {};
var args = baseExpr.arguments || [];
return args[0];
};
ClassMetadataWalker.prototype.validateProperty = function (className, property) {
var propName = property.initializer.text;
var isValidName = this.rule.validateName(propName);
var isValidPrefix = (this.rule.hasPrefix ? this.rule.validatePrefix(propName) : true);
if (!isValidName || !isValidPrefix) {
this.addFailure(this.createFailure(property.getStart(), property.getWidth(), sprintf_js_1.sprintf.apply(this, this.createFailureArray(className, propName))));
}
};
ClassMetadataWalker.prototype.createFailureArray = function (className, pipeName) {
if (this.rule.hasPrefix) {
return [Rule.FAILURE_WITH_PREFIX, className, this.rule.prefix, pipeName];
}
return [Rule.FAILURE_WITHOUT_PREFIX, className, pipeName];
};
return ClassMetadataWalker;
}(ng2Walker_1.Ng2Walker));
exports.ClassMetadataWalker = ClassMetadataWalker;
var _a;
|
(function(size, angle, minimum, canvas, context, requestAnimationFrame){
context.translate(minimum(90*size, 2*canvas.width/3), minimum(45*size, 2*canvas.height/3));
context.strokeStyle = 'black';
var draw = function(){
context.beginPath();
context.moveTo(0,0);
context.lineTo(size, 0);
context.stroke();
}
var forward = function(){
context.translate(size, 0);
}
var left = function(){
context.rotate(-angle);
}
var right = function(){
context.rotate(angle);
}
var move = function(goRight){
forward();
if (goRight) {
right();
} else {
left();
}
}
var direction = function(n){
return (((n & -n) << 1) & n) !== 0;
}
var n = 1; var max = Math.pow(2, 15);
var continous = function(){
draw();
move(direction(n++));
requestAnimationFrame(continous);
}
continous();
})(5, Math.PI/2, Math.min, a, c, requestAnimationFrame);
|
//>>built
define({HKD_displayName:"\u05d3\u05d5\u05dc\u05e8 \u05d4\u05d5\u05e0\u05d2 \u05e7\u05d5\u05e0\u05d2\u05d9",CHF_displayName:"\u05e4\u05e8\u05e0\u05e7 \u05e9\u05d5\u05d5\u05d9\u05e6\u05e8\u05d9",JPY_symbol:"JP\u00a5",CAD_displayName:"\u05d3\u05d5\u05dc\u05e8 \u05e7\u05e0\u05d3\u05d9",HKD_symbol:"HK$",CNY_displayName:"\u05d9\u05d5\u05d0\u05df \u05e1\u05d9\u05e0\u05d9",USD_symbol:"$",AUD_displayName:"\u05d3\u05d5\u05dc\u05e8 \u05d0\u05d5\u05e1\u05d8\u05e8\u05dc\u05d9",JPY_displayName:"\u05d9\u05df \u05d9\u05e4\u05e0\u05d9",
CAD_symbol:"CA$",USD_displayName:"\u05d3\u05d5\u05dc\u05e8 \u05d0\u05de\u05e8\u05d9\u05e7\u05d0\u05d9",EUR_symbol:"\u20ac",CNY_symbol:"CN\u00a5",GBP_displayName:"\u05dc\u05d9\u05e8\u05d4 \u05e9\u05d8\u05e8\u05dc\u05d9\u05e0\u05d2",GBP_symbol:"\u00a3",AUD_symbol:"A$",EUR_displayName:"\u05d0\u05d9\u05e8\u05d5"}); |
// @flow
import I18nJs from 'i18n-js';
I18nJs.locale = 'en'; // a locale from your available translations
export const getLanguages = (): Promise<string[]> => Promise.resolve(['en']);
export default I18nJs;
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from 'react-reconciler/src/ReactFiber';
import type {
DispatchConfig,
ReactSyntheticEvent,
} from './ReactSyntheticEventType';
import type {TopLevelType} from './TopLevelEventTypes';
export type EventTypes = {[key: string]: DispatchConfig};
export type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | Touch;
export type PluginName = string;
export type PluginModule<NativeEvent> = {
eventTypes: EventTypes,
extractEvents: (
topLevelType: TopLevelType,
targetInst: Fiber,
nativeTarget: NativeEvent,
nativeEventTarget: EventTarget,
) => ?ReactSyntheticEvent,
tapMoveThreshold?: number,
};
|
var config = require('../../config'),
utils;
utils = {
getDeclarations: function () {
var baseUrl = config.urlFor('sitemap-xsl');
baseUrl = baseUrl.replace(/^(http:|https:)/, '');
return '<?xml version="1.0" encoding="UTF-8"?>' +
'<?xml-stylesheet type="text/xsl" href="' + baseUrl + 'sitemap.xsl"?>';
}
};
module.exports = utils;
|
/*!
* dc-addons v0.13.1
*
* 2016-04-08 11:34:39
*
*/
(function () {
'use strict';
if (dc.serverChart) {
return false;
}
if (!('dc' in window)) {
window.dc = {};
}
dc.serverChart = function (parent) {
var _chart = {},
socket = null,
hasInit = false,
connected = false,
element = d3.select(parent),
_options = {
name: null,
server: 'http://127.0.0.1:3000/',
errorMessage: 'A problem occurred creating the charts. Please try again later',
loadingMessage: 'Loading',
reconnectingMessage: 'There appears to be a problem connecting to the server. Retyring...',
connectionErrorMessage: 'Could not connect to the server.',
},
_conditions = null,
mouseDownCoords = null,
east = null,
west = null,
prevEast = null,
prevWest = null,
extentMouse = false,
resizeEastMouse = false,
resizeWestMouse = false,
chartWrapperClass = '.dc-server-chart';
//---------------------
// Browser Events
//---------------------
function attachEvents () {
element.selectAll(chartWrapperClass).each(function (chartData, chartIndex) {
var chartWrapper = d3.select(this),
chartType = getChartType(chartWrapper);
if (typeof dc.serverChart['attachEvents' + chartType] === 'function') {
dc.serverChart['attachEvents' + chartType](chartIndex, chartWrapper);
}
});
}
dc.serverChart.attachEventsBarChart = function (chartIndex, chartWrapper) {
chartWrapper
.selectAll('rect.bar')
.on('click', function (barData, barIndex) {
sendFilter(chartIndex, barIndex);
});
attachEventsBrush(chartIndex, chartWrapper);
};
dc.serverChart.attachEventsPieChart = function (chartIndex, chartWrapper) {
chartWrapper
.selectAll('g.pie-slice')
.on('click', function (sliceData, sliceIndex) {
sendFilter(chartIndex, sliceIndex);
});
};
dc.serverChart.attachEventsRowChart = function (chartIndex, chartWrapper) {
chartWrapper
.selectAll('rect')
.on('click', function (rowData, rowIndex) {
sendFilter(chartIndex, rowIndex);
});
};
dc.serverChart.attachEventsPairedRowChart = function (chartIndex, chartWrapper) {
chartWrapper
.selectAll('svg')
.selectAll('rect')
.on('click', function (rowData, rowIndex, svgIndex) {
sendFilter(chartIndex, rowIndex * 2 - svgIndex);
});
};
dc.serverChart.attachEventsLineChart = function (chartIndex, chartWrapper) {
chartWrapper
.selectAll('circle.dot')
.on('mousemove', function () {
var dot = d3.select(this);
dot.style('fill-opacity', 0.8);
dot.style('stroke-opacity', 0.8);
})
.on('mouseout', function () {
var dot = d3.select(this);
dot.style('fill-opacity', 0.01);
dot.style('stroke-opacity', 0.01);
});
attachEventsBrush(chartIndex, chartWrapper);
};
function attachEventsBrush(chartIndex, chartWrapper) {
if (chartWrapper.select('g.brush').size() > 0) {
var maxEast = chartWrapper
.select('g.brush')
.select('.background')
.attr('width');
chartWrapper
.select('g.brush')
.on('mousedown', function () {
mouseDownCoords = d3.mouse(this);
prevWest = west;
prevEast = east;
})
.on('mousemove', function () {
if (mouseDownCoords !== null) {
var coords = d3.mouse(this),
el = d3.select(this),
tmp = null;
if (extentMouse) {
var diff = coords[0] - mouseDownCoords[0];
west = prevWest + diff;
east = prevEast + diff;
if (west < 0) {
west = 0;
east = prevEast - prevWest;
}
if (east > maxEast) {
east = maxEast;
west = maxEast - (prevEast - prevWest);
}
} else if (resizeEastMouse) {
west = west;
east = coords[0];
if (east < west) {
tmp = west;
west = east;
east = tmp;
resizeEastMouse = false;
resizeWestMouse = true;
}
if (west < 0) {
west = 0;
}
if (east > maxEast) {
east = maxEast;
}
} else if (resizeWestMouse) {
west = coords[0];
east = east;
if (east < west) {
tmp = west;
west = east;
east = tmp;
resizeEastMouse = true;
resizeWestMouse = false;
}
if (west < 0) {
west = 0;
}
if (east > maxEast) {
east = maxEast;
}
} else {
west = d3.min([coords[0], mouseDownCoords[0]]);
east = d3.max([coords[0], mouseDownCoords[0]]);
if (west < 0) {
west = 0;
}
if (east > maxEast) {
east = maxEast;
}
}
el
.select('.extent')
.attr('x', west)
.attr('width', east - west);
el
.selectAll('g.resize')
.style('display', 'inline');
el
.select('g.resize.e')
.attr('transform', 'translate(' + east + ', 0)');
el
.select('g.resize.w')
.attr('transform', 'translate(' + west + ', 0)');
}
})
.on('mouseup', function () {
var coords = d3.mouse(this),
el = d3.select(this);
if (mouseDownCoords === null || coords[0] === mouseDownCoords[0]) {
el
.select('.extent')
.attr('width', 0);
el
.selectAll('g.resize')
.style('display', 'none');
sendFilter(chartIndex, [null, null]);
} else {
// somehow calculate what was selected
sendFilter(chartIndex, [west, east]);
}
mouseDownCoords = null;
});
chartWrapper
.select('g.brush')
.select('.extent')
.on('mousedown', function () {
extentMouse = true;
})
.on('mouseup', function () {
extentMouse = false;
});
chartWrapper
.select('g.brush')
.select('g.resize.e')
.on('mousedown', function () {
resizeEastMouse = true;
})
.on('mouseup', function () {
resizeEastMouse = false;
});
chartWrapper
.select('g.brush')
.select('g.resize.w')
.on('mousedown', function () {
resizeWestMouse = true;
})
.on('mouseup', function () {
resizeWestMouse = false;
});
}
}
//---------------------
// Chart Events
//---------------------
_chart.render = function () {
init();
sendRender();
return _chart;
};
_chart.options = function (_) {
if (arguments.length === 0) {
return _options;
}
for (var key in _) {
if (_.hasOwnProperty(key)) {
_options[key] = _[key];
}
}
return _chart;
};
_chart.conditions = function (_) {
if (arguments.length === 0) {
return _conditions;
}
_conditions = _;
updateConditions();
return _chart;
};
//---------------------
// Socket Events
//---------------------
function sendFilter (chartIndex, index) {
socket.emit('filter', [chartIndex, index]);
}
function sendRender () {
onRefresh();
if (!_options.name) {
throw Error('Name is a required option');
}
socket.emit('render', _options.name);
}
function preRender (charts) {
element.selectAll('*').remove();
for (var i = 0; i < charts.length; i++) {
element
.append('div')
.style('width', charts[i].width + 'px')
.style('height', charts[i].height + 'px')
.style('float', 'left')
.style('text-align', 'center')
.style('line-height', charts[i].height + 'px')
.html(_options.loadingMessage);
}
}
function render (response) {
element.html(response);
attachEvents();
}
function renderError (response) {
element.html(_options.errorMessage);
console.warn(response);
}
function redraw (response) {
var next = document.createElement('div');
next.innerHTML = response;
next = d3.select(next);
element.selectAll(chartWrapperClass).each(function (el, chartIndex) {
var chartWrapper = d3.select(this),
nextWrapper = next.selectAll(chartWrapperClass).filter(function (d, j) {
return j === chartIndex;
}),
chartType = getChartType(chartWrapper);
if (chartType) {
if (typeof dc.serverChart['redraw' + chartType] === 'function') {
dc.serverChart['redraw' + chartType](chartIndex, chartWrapper, nextWrapper);
} else {
chartWrapper.html(nextWrapper.html());
attachEvents();
}
}
});
}
function updateConditions () {
if (hasInit) {
socket.emit('updateConditions', _conditions);
}
}
//---------------------
// Helper Functions
//---------------------
function onRefresh () {
element.html(_options.loadingMessage);
}
function init () {
socket = io(_options.server, {
reconnectionDelay: 500,
reconnectionDelayMax: 2000,
reconnectionAttempts: 4,
});
// socket events
socket.io.on('open', function () {
connected = true;
});
socket.io.on('reconnecting', function () {
if (!connected) {
element.html(_options.reconnectingMessage);
}
});
socket.io.on('reconnect_failed', function () {
if (!connected) {
element.html(_options.connectionErrorMessage);
}
});
// custom events
socket.on('preRender', preRender);
socket.on('afterRender', render);
socket.on('afterRenderError', renderError);
socket.on('afterFilter', redraw);
socket.on('afterFilterError', renderError);
hasInit = true;
}
function getChartType (chartWrapper) {
try {
var chartType = chartWrapper.attr('data-type').split('');
chartType[0] = chartType[0].toUpperCase();
return chartType.join('');
} catch (ex) {
return null;
}
}
//---------------------
// Init
//---------------------
onRefresh();
return _chart;
};
})();
(function () {
'use strict';
if (dc.serverChart.redrawPieChart) {
return false;
}
var duration = 5000;
var ease = 'quad-in-out';
var pieRegEx = new RegExp([
'M ?([\\d\\.e-]+) ?, ?([\\d\\.e-]+) ?', // move to starting point
// see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#Arcs
'A ?', // start arc
'[\\d\\.e-]+ ?, ?[\\d\\.e-]+ ?,? ', // arc x radius and y radius
'\\d ,? ?', // arc x-axis-rotation
'\\d ?,? ?', // arc large-arc-flag
'\\d ?,? ?', // arc sweep-flag
'([\\d\\.e-]+) ?,? ?([\\d\\.e-]+) ?', // arc finishing points
'L ?([\\d\\.e-]+) ?,? ?([\\d\\.e-]+)', // draw line too
'Z', // close off
].join(''));
dc.serverChart.redrawPieChart = function (chartIndex, chartWrapper, nextWrapper) {
var svg = chartWrapper.select('svg'),
currentSlices = chartWrapper.selectAll('g.pie-slice'),
nextSlices = nextWrapper.selectAll('g.pie-slice');
chartWrapper
.select('g')
.attr('class', nextWrapper.select('g').attr('class'));
chartWrapper
.selectAll('text')
.each(function (textData, textIndex) {
var textElement = d3.select(this),
nextText = filterNextItem(nextWrapper.selectAll('text'), textIndex);
if (nextText.empty()) {
textElement
.text('');
} else {
textElement
.text(nextText.text())
.transition()
.duration(duration)
.ease(ease)
.attr('transform', nextText.attr('transform'));
}
});
currentSlices
.each(function (sliceData, sliceIndex) {
var sliceElement = d3.select(this),
nextSlice = filterNextItem(nextSlices, sliceIndex);
if (!nextSlice.empty()) {
sliceElement
.attr('class', nextSlice.attr('class'));
var nextText = nextSlice.select('text');
if (!nextText.empty()) {
sliceElement
.select('title')
.text(nextText.text());
}
}
});
currentSlices
.select('path')
.each(function (sliceData, sliceIndex) {
var sliceElement = d3.select(this),
nextSlice = filterNextItem(nextSlices, sliceIndex).select('path');
if (!nextSlice.empty()) {
sliceElement
.attr('class', nextSlice.attr('class'))
.attr('fill', nextSlice.attr('fill'));
}
})
.transition()
.duration(duration)
.ease(ease)
.attrTween('d', function (pathData, pathIndex, attrValue) {
var radius = d3.min([svg.attr('width'), svg.attr('height')]) / 2,
arc = d3.svg.arc().outerRadius(radius).innerRadius(0),
nextSlice = filterNextItem(nextSlices, pathIndex),
nextD = '';
if (!nextSlice.empty()) {
nextD = nextSlice.select('path').attr('d');
}
var interpolate = d3.interpolate(
pathToInterpolateAngles(attrValue),
pathToInterpolateAngles(nextD)
);
return function (t) {
return arc(interpolate(t));
};
});
};
dc.serverChart.redrawBarChart = function (chartIndex, chartWrapper, nextWrapper) {
var currentBars = chartWrapper.selectAll('rect.bar'),
nextBars = nextWrapper.selectAll('rect.bar');
currentBars
.each(function (barData, barIndex) {
var barElement = d3.select(this),
nextBar = filterNextItem(nextBars, barIndex);
barElement
.attr('class', nextBar.attr('class'))
.attr('fill', nextBar.attr('fill'))
.transition()
.duration(duration)
.ease(ease)
.attr('x', nextBar.attr('x'))
.attr('y', nextBar.attr('y'))
.attr('width', nextBar.attr('width'))
.attr('height', nextBar.attr('height'));
});
currentBars
.select('title')
.each(function (titleData, titleIndex) {
var titleElement = d3.select(this),
nextTitle = filterNextItem(nextBars, titleIndex).select('title');
titleElement
.text(nextTitle.text());
});
redrawAxis(chartIndex, chartWrapper, nextWrapper);
};
dc.serverChart.redrawRowChart = dc.serverChart.redrawPairedRowChart = function (chartIndex, chartWrapper, nextWrapper) {
chartWrapper
.selectAll('g.row')
.each(function (rowData, rowIndex) {
var rowElement = d3.select(this),
nextRow = filterNextItem(nextWrapper.selectAll('g.row'), rowIndex),
nextRect = nextRow.select('rect'),
nextText = nextRow.select('text'),
nextTitle = nextRow.select('title');
rowElement
.transition()
.duration(duration)
.ease(ease)
.attr('transform', nextRow.attr('transform'));
rowElement
.select('rect')
.attr('class', nextRect.attr('class'))
.transition()
.duration(duration)
.ease(ease)
.attr('width', nextRect.attr('width'))
.attr('height', nextRect.attr('height'))
.attr('fill', nextRect.attr('fill'))
.attr('transform', nextRect.attr('transform'));
rowElement
.select('text')
.text(nextText.text())
.transition()
.duration(duration)
.ease(ease)
.attr('x', nextText.attr('x'))
.attr('y', nextText.attr('y'))
.attr('dy', nextText.attr('dy'))
.attr('transform', nextText.attr('transform'));
rowElement
.select('title')
.text(nextTitle.text());
});
redrawAxis(chartIndex, chartWrapper, nextWrapper);
};
dc.serverChart.redrawLineChart = function (chartIndex, chartWrapper, nextWrapper) {
chartWrapper
.selectAll('g.stack')
.each(function (stackData, stackIndex) {
var stackElement = d3.select(this),
nextStack = filterNextItem(nextWrapper.selectAll('g.stack'), stackIndex);
stackElement
.selectAll('path')
.each(function (pathData, pathIndex) {
var pathElement = d3.select(this),
nextPath = filterNextItem(nextStack.selectAll('path'), pathIndex);
pathElement
.transition()
.duration(duration)
.ease(ease)
.attr('stroke', nextPath.attr('stroke'))
.attr('d', nextPath.attr('d'));
});
});
redrawAxis(chartIndex, chartWrapper, nextWrapper);
};
dc.serverChart.redrawNumberDisplay = function (chartIndex, chartWrapper, nextWrapper) {
var spanElement = chartWrapper.select('span.number-display'),
spanText = spanElement.text(),
textParts = spanText.match(/([^\d]*)([\d\.]+)([^\d]*)/i),
currentNumber = textParts === null ? 0 : parseFloat(textParts[2]),
nextSpan = nextWrapper.select('span.number-display'),
nextText = nextSpan.text(),
nextParts = nextText.match(/([^\d]*)([\d\.]+)([^\d]*)/i),
nextNumber = nextParts === null ? 0 : parseFloat(nextParts[2]);
spanElement.transition()
.duration(duration)
.ease(ease)
.tween('text', function () {
var interp = d3.interpolateNumber(currentNumber, nextNumber);
return function (t) {
var num = d3.format('.2s')(interp(t));
this.innerHTML = nextParts[1] + num + nextParts[3];
};
});
};
function redrawAxis (chartIndex, chartWrapper, nextWrapper) {
chartWrapper
.selectAll('.axis')
.each(function (axisData, axisIndex) {
var axisElement = d3.select(this),
axisBBox = axisElement.select('path.domain').node().getBBox(),
axisTicks = axisElement.selectAll('g.tick'),
isHorizontal = axisTicks.empty() ? null : /translate\([\d.]+,0\)/i.exec(d3.select(axisTicks[0][1]).attr('transform')) !== null,
firstRow = d3.select(axisElement[0][0].nextElementSibling),
isRightYAxis = firstRow.empty() ? null : /translate\(0,[\d.]+\)/i.exec(firstRow.attr('transform')) === null,
nextAxis = filterNextItem(nextWrapper.selectAll('.axis'), axisIndex),
nextTicks = nextAxis.selectAll('g.tick'),
minTickValue = nextTicks.empty() ? 0 : parseFloat(d3.select(nextTicks[0][0]).select('text').text()),
maxTickValue = nextTicks.empty() ? 1 : parseFloat(d3.select(nextTicks[0][nextTicks[0].length - 1]).select('text').text()),
grid = chartWrapper.select(isHorizontal ? '.grid-line.vertical' : '.grid-line.horizontal'),
nextGrid = nextWrapper.select(isHorizontal ? '.grid-line.vertical' : '.grid-line.horizontal');
axisElement
.transition()
.duration(duration)
.ease(ease)
.attr('transform', nextAxis.attr('transform'));
if (!grid.empty()) {
grid
.transition()
.duration(duration)
.ease(ease)
.attr('transform', nextGrid.attr('transform'));
}
axisTicks
.each(function (tickData, tickIndex) {
var tickElement = d3.select(this),
tickText = tickElement.select('text'),
tickValue = parseFloat(tickText.text()),
tickPercentage = (tickValue - minTickValue) / (maxTickValue - minTickValue) * 100,
matched = false;
nextTicks
.each(function (nextData, nextIndex) {
var nextTick = d3.select(this),
nextText = nextTick.select('text');
if (parseFloat(nextText.text()) === tickValue) {
matched = true;
tickElement
.transition()
.duration(duration)
.ease(ease)
.attr('transform', nextTick.attr('transform'))
.attr('opacity', null)
.style('opacity', nextTick.attr('opacity'))
.each('end', function () {
tickElement
.select('text')
.text(nextTick.select('text').text());
});
if (!grid.empty()) {
var gridLine = filterNextItem(grid.selectAll('line'), tickIndex),
nextGridLine = filterNextItem(nextGrid.selectAll('line'), nextIndex);
gridLine
.transition()
.duration(duration)
.ease(ease)
.attr('x1', nextGridLine.attr('x1'))
.attr('y1', nextGridLine.attr('y1'))
.attr('x2', nextGridLine.attr('x2'))
.attr('y2', nextGridLine.attr('y2'))
.attr('transform', null)
.style('opacity', nextGridLine.attr('opacity'));
}
}
});
if (!matched) {
var transform = '';
if (isHorizontal) {
var translate = (axisBBox.width * tickPercentage / 100);
if (isRightYAxis) {
transform = 'translate(-' + translate + ', 0)';
} else {
transform = 'translate(' + translate + ', 0)';
}
} else {
transform = 'translate(0, ' +
(axisBBox.height - (axisBBox.height * tickPercentage / 100)) +
')';
}
tickElement
.transition()
.duration(duration)
.ease(ease)
.attr('transform', transform)
.style('opacity', 0)
.each('end', function () {
tickElement.remove();
});
if (!grid.empty()) {
var gridLine = filterNextItem(grid.selectAll('line'), tickIndex);
gridLine
.transition()
.duration(duration)
.ease(ease)
.attr('transform', transform)
.style('opacity', 0)
.each('end', function () {
gridLine.remove();
});
}
}
});
});
nextWrapper
.selectAll('.axis')
.each(function (d, axisIndex, tickIndex) {
var nextAxis = d3.select(this),
nextTicks = nextAxis.selectAll('g.tick');
if (!nextTicks.empty()) {
var isHorizontal = /translate\([\d.]+,0\)/i.exec(d3.select(nextTicks[0][1]).attr('transform')) !== null,
firstRow = d3.select(nextAxis[0][0].nextElementSibling),
isRightYAxis = firstRow.empty() ? null : /translate\(0,[\d.]+\)/i.exec(firstRow.attr('transform')) === null,
axisElement = filterNextItem(chartWrapper.selectAll('.axis'), axisIndex),
axisBBox = axisElement.select('path.domain').node().getBBox(),
axisTicks = axisElement.selectAll('g.tick'),
minTickValue = axisTicks.empty() ? 0 : parseFloat(d3.select(axisTicks[0][0]).select('text').text()),
maxTickValue = axisTicks.empty() ? 1 : parseFloat(d3.select(axisTicks[0][axisTicks[0].length - 1]).select('text').text()),
grid = chartWrapper.select(isHorizontal ? '.grid-line.vertical' : '.grid-line.horizontal'),
nextGrid = nextWrapper.select(isHorizontal ? '.grid-line.vertical' : '.grid-line.horizontal');
nextTicks
.each(function (nextData, nextIndex) {
var nextTick = d3.select(this),
nextText = nextTick.select('text'),
nextLine = nextTick.select('line'),
nextValue = parseFloat(nextText.text()),
tickPercentage = (nextValue - minTickValue) / (maxTickValue - minTickValue) * 100,
matched = false;
axisTicks
.each(function (tickData, tickIndex) {
var tickElement = d3.select(this),
tickText = tickElement.select('text');
if (parseFloat(tickText.text()) === nextValue) {
matched = true;
}
});
if (!matched) {
var translate = 0,
transform = '',
gridLineTransform = '',
nextGridLine = null;
if (grid.empty()) {
nextGridLine = nextTick.select('line.grid-line');
} else {
nextGridLine = filterNextItem(nextGrid.selectAll('line'), nextIndex);
}
if (isHorizontal) {
translate = axisBBox.width * tickPercentage / 100;
if (isRightYAxis) {
transform = 'translate(-' + translate + ', 0)';
} else {
transform = 'translate(' + translate + ', 0)';
}
if (!nextGridLine.empty()) {
gridLineTransform = 'translate(' + (translate - nextGridLine.attr('x1')) + ', 0)';
}
} else {
translate = axisBBox.height - (axisBBox.height * tickPercentage / 100);
transform = 'translate(0, ' + translate + ')';
if (!nextGridLine.empty()) {
gridLineTransform = 'translate(0, ' + (translate - nextGridLine.attr('y1')) + ')';
}
}
var addedTick = axisElement
.append('g')
.attr('class', 'tick')
.attr('transform', transform)
.attr('opacity', 0);
addedTick
.transition()
.duration(duration)
.ease(ease)
.attr('transform', nextTick.attr('transform'))
.style('opacity', 1);
addedTick
.append('text')
.attr('x', nextText.attr('x'))
.attr('y', nextText.attr('y'))
.attr('dy', nextText.attr('dy'))
.attr('style', nextText.attr('style'))
.text(nextText.text());
addedTick
.append('line')
.attr('x1', nextLine.attr('x1'))
.attr('y1', nextLine.attr('y1'))
.attr('x2', nextLine.attr('x2'))
.attr('y2', nextLine.attr('y2'));
if (!nextGridLine.empty()) {
if (grid.empty()) {
addedTick
.append('line')
.attr('class', nextGridLine.attr('class'))
.attr('x1', nextGridLine.attr('x1'))
.attr('y1', nextGridLine.attr('y1'))
.attr('x2', nextGridLine.attr('x2'))
.attr('y2', nextGridLine.attr('y2'));
} else {
grid
.append('line')
.attr('x1', nextGridLine.attr('x1'))
.attr('y1', nextGridLine.attr('y1'))
.attr('x2', nextGridLine.attr('x2'))
.attr('y2', nextGridLine.attr('y2'))
.attr('transform', gridLineTransform)
.attr('opacity', 0)
.transition()
.duration(duration)
.ease(ease)
.attr('transform', 'translate(0, 0)')
.style('opacity', 1);
}
}
}
});
}
});
}
function filterNextItem (next, i) {
return next.filter(function (d, j) {
return j === i;
});
}
function pathToInterpolateAngles(path) {
// get the points of the pie slice
var p = path.match(pieRegEx);
if (!p) {
return {
startAngle: 0,
endAngle: Math.PI * 2,
};
}
var coords = {
x1: parseFloat(p[5]),
y1: parseFloat(p[6]),
x2: parseFloat(p[1]),
y2: parseFloat(p[2]),
x3: parseFloat(p[3]),
y3: parseFloat(p[4]),
};
// convert the points into angles
var angles = {
startAngle: switchRadians(Math.atan2((coords.y2 - coords.y1), (coords.x2 - coords.x1))),
endAngle: switchRadians(Math.atan2((coords.y3 - coords.y1), (coords.x3 - coords.x1))),
};
if (angles.startAngle < 0) {
angles.startAngle = 0;
}
if (angles.endAngle > (Math.PI * 2) || angles.endAngle < angles.startAngle) {
angles.endAngle = Math.PI * 2;
}
return angles;
}
// since silly maths makes the following angles we have to convert it from
// -90 -(PI / 2)
// -180 0 or -PI 0
// 90 PI / 2
//
// to
//
// 360 PI * 2
// 270 90 or PI * 1.5 PI / 2
// 180 PI
function switchRadians(angle) {
var quarter = Math.PI * 0.5;
if (angle >= 0) {
return quarter + angle;
} else if (angle >= -quarter) {
return quarter - Math.abs(angle);
}
return (Math.PI * 2.5) - Math.abs(angle);
}
})();
|
'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
const Sim = require('./../../../.sim-dist');
let battle;
describe('Rage Powder', function () {
afterEach(function () {
battle.destroy();
});
it('should redirect single-target moves towards it if it is a valid target', function () {
this.timeout(5000);
battle = common.gen(5).createBattle({gameType: 'triples'});
battle.setPlayer('p1', {team: [
{species: 'Amoonguss', ability: 'overcoat', item: 'safetygoggles', moves: ['ragepowder']},
{species: 'Venusaur', ability: 'overcoat', moves: ['growth']},
{species: 'Ivysaur', ability: 'overcoat', moves: ['growth']},
]});
battle.setPlayer('p2', {team: [
{species: 'Abra', ability: 'synchronize', moves: ['absorb']},
{species: 'Kadabra', ability: 'synchronize', moves: ['absorb']},
{species: 'Alakazam', ability: 'synchronize', moves: ['absorb']},
]});
let hitCount = [0, 0, 0];
battle.p1.active[0].damage = function (...args) {
hitCount[0]++;
return Sim.Pokemon.prototype.damage.apply(this, args);
};
battle.p1.active[1].damage = function (...args) {
hitCount[1]++;
return Sim.Pokemon.prototype.damage.apply(this, args);
};
battle.p1.active[2].damage = function (...args) {
hitCount[2]++;
return Sim.Pokemon.prototype.damage.apply(this, args);
};
battle.makeChoices('move ragepowder, move growth, move growth', 'move absorb 2, move absorb 2, move absorb 2');
assert.strictEqual(hitCount[0], 2);
assert.strictEqual(hitCount[1], 1);
assert.strictEqual(hitCount[2], 0);
});
it('should not affect Pokemon with Powder immunities', function () {
battle = common.gen(5).createBattle({gameType: 'triples'});
battle.setPlayer('p1', {team: [
{species: 'Amoonguss', ability: 'overcoat', moves: ['growth']},
{species: 'Venusaur', ability: 'overcoat', moves: ['ragepowder']},
{species: 'Ivysaur', ability: 'overcoat', moves: ['growth']},
]});
battle.setPlayer('p2', {team: [
{species: 'Squirtle', ability: 'naturalcure', moves: ['absorb']},
{species: 'Escavalier', ability: 'overcoat', moves: ['absorb']},
{species: 'Alakazam', ability: 'synchronize', item: 'safetygoggles', moves: ['absorb']},
]});
let hitCount = [0, 0, 0];
battle.p1.active[0].damage = function (...args) {
hitCount[0]++;
return Sim.Pokemon.prototype.damage.apply(this, args);
};
battle.p1.active[1].damage = function (...args) {
hitCount[1]++;
return Sim.Pokemon.prototype.damage.apply(this, args);
};
battle.p1.active[2].damage = function (...args) {
hitCount[2]++;
return Sim.Pokemon.prototype.damage.apply(this, args);
};
battle.makeChoices('move growth, move ragepowder, move growth', 'move absorb 3, move absorb 1, move absorb 1');
assert.strictEqual(hitCount[0], 2);
assert.strictEqual(hitCount[1], 1);
assert.strictEqual(hitCount[2], 0);
});
});
|
require('./setAttributes.prototype.js')
require('./setStyles.prototype.js')
require('./appendChildren.prototype.js')
|
define(['./_baseSortedIndex', './eq'], function(baseSortedIndex, eq) {
/**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/
function sortedIndexOf(array, value) {
var length = array ? array.length : 0;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) {
return index;
}
}
return -1;
}
return sortedIndexOf;
});
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* InMage Azure V2 input to update replication protected item.
*
* @extends models['UpdateReplicationProtectedItemProviderInput']
*/
class A2AUpdateReplicationProtectedItemInput extends models['UpdateReplicationProtectedItemProviderInput'] {
/**
* Create a A2AUpdateReplicationProtectedItemInput.
* @member {string} [recoveryCloudServiceId] The target cloud service ARM Id
* (for V1).
* @member {string} [recoveryResourceGroupId] The target resource group ARM
* Id (for V2).
*/
constructor() {
super();
}
/**
* Defines the metadata of A2AUpdateReplicationProtectedItemInput
*
* @returns {object} metadata of A2AUpdateReplicationProtectedItemInput
*
*/
mapper() {
return {
required: false,
serializedName: 'A2A',
type: {
name: 'Composite',
polymorphicDiscriminator: {
serializedName: 'instanceType',
clientName: 'instanceType'
},
uberParent: 'UpdateReplicationProtectedItemProviderInput',
className: 'A2AUpdateReplicationProtectedItemInput',
modelProperties: {
instanceType: {
required: true,
serializedName: 'instanceType',
isPolymorphicDiscriminator: true,
type: {
name: 'String'
}
},
recoveryCloudServiceId: {
required: false,
serializedName: 'recoveryCloudServiceId',
type: {
name: 'String'
}
},
recoveryResourceGroupId: {
required: false,
serializedName: 'recoveryResourceGroupId',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = A2AUpdateReplicationProtectedItemInput;
|
var traverseScope = require('../lib/traverse');
var validation = require('../lib/validation');
var config = require('../lib/config');
var rule;
/**
* @param {Object} context
* @param {settings} settings
* @return {Function}
*/
function handleMemberExpressions(context, settings) {
return function (node) {
var scope;
if (node.object && node.object.name) {
// memoize settings
config.settings = settings;
scope = traverseScope(node, {
init: {
start: node.start,
end: node.end
},
props: [],
typedVars: [],
nativeVars: [],
});
if (scope.props.length && scope.typedVars.length) {
scope.typedVars.some(function (param) {
if (param.varName === node.object.name) {
validation.validate(param, scope, node, context);
return true;
}
return false;
});
}
}
};
}
/**
* @param {Object} context
* @returns {{MemberExpression: (function)}}
*/
rule = function (context) {
return {
MemberExpression: handleMemberExpressions(context, context.settings.typelint),
};
};
rule.handleMemberExpressions = handleMemberExpressions;
module.exports = rule; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.