code stringlengths 2 1.05M |
|---|
goog.provide("prov.B");
/** @constructor */
function foo() {}
prov.B.typB = foo;
prov.B.valB = new foo();
|
/*
* Copyright (c) 2016, Bruce Schubert.
* The MIT License
*/
// Given these inputs:
// year = 2003;
// month = 10; (October)
// day = 17;
// hour = 12;
// minute = 30;
// second = 30;
// timezone = -7.0;
// delta_ut1 = 0;
// delta_t = 67;
// longitude = -105.1786;
// latitude = 39.742476;
// elevation = 1830.14;
// pressure = 820;
// temperature = 11;
// slope = 30;
// azm_rotation = -10;
// atmos_refract = 0.5667;
//
// The output of this test should be:
// Julian Day: 2452930.312847
// L: 2.401826e+01 degrees // Earth heliocentric longitude
// B: -1.011219e-04 degrees // Earth heliocentric latitude
// R: 0.996542 AU // Earth radius vector
// H: 11.105902 degrees // Observer hour angle
// Delta Psi: -3.998404e-03 degrees // Nutation longitude
// Delta Epsilon: 1.666568e-03 degrees // Nutation obliquity
// Epsilon: 23.440465 degrees // Ecliptic true obliquity
// Zenith: 50.111622 degrees // Topocentric zenith angle
// Azimuth: 194.340241 degrees // Topocentric azimuth angle
// Incidence: 25.187000 degrees // Surface incidence angle
// Sunrise: 06:12:43 Local Time
// Sunset: 17:20:19 Local Time
//
define(['model/sun/SolarCalculator', 'tests/sun/SolarData', 'tests/sun/SolarPositionAlgorithm', 'QUnit'],
function (SolarCalculator, SolarData, spa, QUnit) {
"use strict";
var run = function () {
var nearlyEquals = function (a, b, epsilon) {
return Math.abs(a - b) <= Math.abs(epsilon);
};
// reference date for test
var refDate = new Date(2003, 9, 17, 12, 30, 30);
// reference position for test
var observer = {latitude: 39.742476, longitude: -105.1786, elevation: 1830.14};
var terrain = {aspect: -10, slope: 30};
var refData = new SolarData(refDate, -7, observer, terrain, 11, 820);
spa.calculate(refData);
test("getJD", function (assert) {// Passing in the QUnit.assert namespace
var calc = new SolarCalculator();
var julianDates = [
{yr: 1987, mo: 1, dy: 27, jd: 2446822.5},
{yr: 1988, mo: 1, dy: 27, jd: 2447187.5},
{yr: 1999, mo: 1, dy: 1, jd: 2451179.5},
{yr: 2003, mo: 10, dy: 17, jd: 2452929.5}],
i, max, date, jd;
for (i = 0, max = julianDates.length; i < max; i++) {
date = julianDates[i];
jd = calc.getJD(date.yr, date.mo, date.dy);
assert.ok(nearlyEquals(date.jd, jd, 0.0), date.yr + '/' + date.mo + '/' + date.dy + " : " + date.jd + " ~= " + jd);
}
});
/**
*
* @param {type} assert
* @returns {undefined}
*/
test("validate", function (assert) {
// Create the instance to be tested
var calc = new SolarCalculator();
for (var i = 0; i <= 365; i++) {
var testDate = new Date();
testDate.setTime(refDate.getTime() + i * 86400000);
var testData = new SolarData(testDate, -7, observer, terrain, 11, 820);
// Generate expected test results
spa.calculate(testData);
// Define the expected results
var expected = {
julianDate: testData.jd,
azimuth: spa.limit_degrees180pm(testData.azimuth),
zenith: testData.zenith,
hourAngle: spa.limit_degrees180pm(testData.h),
subsolarLatitude: testData.delta_prime,
subsolarLongitude: spa.limit_degrees180pm(observer.longitude - testData.h_prime),
};
// Generate the test results
var result = calc.calculate(testDate, -7, observer.latitude, observer.longitude);
// Validate the results
assert.ok(result !== undefined, "result is not 'undefined'");
assert.ok(nearlyEquals(result.julianDate, expected.julianDate, 0.0001), 'julianDate: ' + result.julianDate + " ~= " + expected.julianDate);
assert.ok(nearlyEquals(result.azimuth, expected.azimuth, 0.05), 'azimuth: ' + result.azimuth + " ~= " + expected.azimuth);
assert.ok(nearlyEquals(result.zenith, expected.zenith, 0.05), 'zenith: ' + result.zenith + " ~= " + expected.zenith);
assert.ok(nearlyEquals(result.hourAngle, expected.hourAngle, 0.02), 'hourAngle: ' + result.hourAngle + " ~= " + expected.hourAngle);
assert.ok(nearlyEquals(result.subsolarLatitude, expected.subsolarLatitude, 0.01), 'subsolarLatitude: ' + result.subsolarLatitude + " ~= " + expected.subsolarLatitude);
assert.ok(nearlyEquals(result.subsolarLongitude, expected.subsolarLongitude, 0.02), 'subsolarLongitude: ' + result.subsolarLongitude + " ~= " + expected.subsolarLongitude);
}
});
test("calculate", function (assert) {
// Create the instance to be tested
var calc = new SolarCalculator();
// Define the expected results
var expected = {
julianDate: refData.jd,
azimuth: spa.limit_degrees180pm(refData.azimuth),
zenith: refData.zenith,
hourAngle: refData.h,
subsolarLatitude: refData.delta_prime,
subsolarLongitude: observer.longitude - refData.h_prime,
rightAscension: refData.alpha,
};
// Generate the test results
var result = calc.calculate(refDate, -7, observer.latitude, observer.longitude);
// Validate the results
assert.ok(result !== undefined, "result is not 'undefined'");
assert.ok(nearlyEquals(result.julianDate, expected.julianDate, 0.0001), 'julianDate: ' + result.julianDate + " ~= " + expected.julianDate);
assert.ok(nearlyEquals(result.azimuth, expected.azimuth, 0.01), 'azimuth: ' + result.azimuth + " ~= " + expected.azimuth);
assert.ok(nearlyEquals(result.zenith, expected.zenith, 0.02), 'zenith: ' + result.zenith + " ~= " + expected.zenith);
assert.ok(nearlyEquals(result.hourAngle, expected.hourAngle, 0.01), 'hourAngle: ' + result.hourAngle + " ~= " + expected.hourAngle);
assert.ok(nearlyEquals(result.subsolarLatitude, expected.subsolarLatitude, 0.01), 'subsolarLatitude: ' + result.subsolarLatitude + " ~= " + expected.subsolarLatitude);
assert.ok(nearlyEquals(result.subsolarLongitude, expected.subsolarLongitude, 0.01), 'subsolarLongitude: ' + result.subsolarLongitude + " ~= " + expected.subsolarLongitude);
assert.ok(nearlyEquals(result.rightAscension, expected.rightAscension, 0.01), 'rightAscension: ' + result.rightAscension + " ~= " + expected.rightAscension);
});
};
return {run: run};
});
|
Prism.languages.scala = Prism.languages.extend('java', {
'keyword': /(<-|=>)|\b(abstract|case|catch|class|def|do|else|extends|final|finally|for|forSome|if|implicit|import|lazy|match|new|null|object|override|package|private|protected|return|sealed|self|super|this|throw|trait|try|type|val|var|while|with|yield)\b/g,
'builtin': /\b(String|Int|Long|Short|Byte|Boolean|Double|Float|Char|Any|AnyRef|AnyVal|Unit|Nothing)\b/g,
'number': /\b0x[\da-f]*\.?[\da-f\-]+\b|\b\d*\.?\d+[e]?[\d]*[dfl]?\b/gi,
'symbol': /'([^\d\s]\w*)/g,
'string': /(""")[\W\w]*?\1|("|\/)[\W\w]*?\2|('.')/g
});
delete Prism.languages.scala['class-name'];
delete Prism.languages.scala['function'];
|
define({
"add": "Klik om nieuwe toe te voegen",
"title": "Titel",
"placeholderBookmarkName": "Naam van bladwijzer",
"ok": "OK",
"cancel": "Afbreken",
"warning": "Bewerking voltooien!",
"edit": "Bladwijzer bewerken",
"errorNameExist": "Bladwijzer bestaat al.",
"errorNameNull": "Ongeldige naam van bladwijzer.",
"addBookmark": "Maak nieuwe",
"thumbnail": "Thumbnail",
"thumbnailHint": "Klik op de afbeelding om deze te bewerken",
"displayBookmarksAs": "Bladwijzers weergeven als",
"cards": "Kaarten",
"list": "Lijst",
"cardsTips": "Cardweergave",
"listTips": "Lijstweergave",
"makeAsDefault": "Standaard maken",
"default": "Standaard",
"editable": "Laat het toevoegen van bladwijzers toe in de widget.",
"alwaysSync": "Toon bladwijzers uit de webmap",
"configCustom": "Toon aangepaste bladwijzers",
"import": "Importeren",
"create": "Maken",
"importTitle": "Bladwijzers importeren",
"importFromWeb": "Importeer bladwijzers uit de huidige webmap",
"selectAll": "Alles selecteren",
"noBookmarkInConfig": "Klik op “Importeren†of “Nieuw maken†om bladwijzers toe te voegen.",
"noBookmarkInWebMap": "Er is geen bladwijzer in de kaart geconfigureerd.",
"extent": "Extent",
"saveExtent": "Sla kaartextent op voor deze bladwijzer",
"savelayers": "Laagzichtbaarheid opslaan",
"withVisibility": "Met laagzichtbaarheid",
"bookmark": "Bladwijzer",
"addBtn": "Toevoegen",
"deleteBtn": "Verwijderen",
"editBtn": "Bewerken",
"dragReorderTip": "Vasthouden en slepen om opnieuw te rangschikken",
"deleteBtnTip": "De bladwijzer verwijderen",
"editBtnTip": "De bladwijzer bewerken"
}); |
JSMpeg.Decoder.MPEG1Video = (function(){ "use strict";
// Inspired by Java MPEG-1 Video Decoder and Player by Zoltan Korandi
// https://sourceforge.net/projects/javampeg1video/
var MPEG1 = function(options) {
JSMpeg.Decoder.Base.call(this, options);
var bufferSize = options.videoBufferSize || 512*1024;
var bufferMode = options.streaming
? JSMpeg.BitBuffer.MODE.EVICT
: JSMpeg.BitBuffer.MODE.EXPAND;
this.bits = new JSMpeg.BitBuffer(bufferSize, bufferMode);
this.customIntraQuantMatrix = new Uint8Array(64);
this.customNonIntraQuantMatrix = new Uint8Array(64);
this.blockData = new Int32Array(64);
this.currentFrame = 0;
this.decodeFirstFrame = options.decodeFirstFrame !== false;
};
MPEG1.prototype = Object.create(JSMpeg.Decoder.Base.prototype);
MPEG1.prototype.constructor = MPEG1;
MPEG1.prototype.write = function(pts, buffers) {
JSMpeg.Decoder.Base.prototype.write.call(this, pts, buffers);
if (!this.hasSequenceHeader) {
if (this.bits.findStartCode(MPEG1.START.SEQUENCE) === -1) {
return false;
}
this.decodeSequenceHeader();
if (this.decodeFirstFrame) {
this.decode();
}
}
};
MPEG1.prototype.decode = function() {
if (!this.hasSequenceHeader) {
return false;
}
if (this.bits.findStartCode(MPEG1.START.PICTURE) === -1) {
var bufferedBytes = this.bits.byteLength - (this.bits.index >> 3);
return false;
}
this.decodePicture();
this.advanceDecodedTime(1/this.frameRate);
return true;
};
MPEG1.prototype.readHuffman = function(codeTable) {
var state = 0;
do {
state = codeTable[state + this.bits.read(1)];
} while (state >= 0 && codeTable[state] !== 0);
return codeTable[state+2];
};
// Sequence Layer
MPEG1.prototype.frameRate = 30;
MPEG1.prototype.decodeSequenceHeader = function() {
var newWidth = this.bits.read(12),
newHeight = this.bits.read(12);
// skip pixel aspect ratio
this.bits.skip(4);
this.frameRate = MPEG1.PICTURE_RATE[this.bits.read(4)];
// skip bitRate, marker, bufferSize and constrained bit
this.bits.skip(18 + 1 + 10 + 1);
if (newWidth !== this.width || newHeight !== this.height) {
this.width = newWidth;
this.height = newHeight;
this.initBuffers();
if (this.destination) {
this.destination.resize(newWidth, newHeight);
}
}
if (this.bits.read(1)) { // load custom intra quant matrix?
for (var i = 0; i < 64; i++) {
this.customIntraQuantMatrix[MPEG1.ZIG_ZAG[i]] = this.bits.read(8);
}
this.intraQuantMatrix = this.customIntraQuantMatrix;
}
if (this.bits.read(1)) { // load custom non intra quant matrix?
for (var i = 0; i < 64; i++) {
var idx = MPEG1.ZIG_ZAG[i];
this.customNonIntraQuantMatrix[idx] = this.bits.read(8);
}
this.nonIntraQuantMatrix = this.customNonIntraQuantMatrix;
}
this.hasSequenceHeader = true;
};
MPEG1.prototype.initBuffers = function() {
this.intraQuantMatrix = MPEG1.DEFAULT_INTRA_QUANT_MATRIX;
this.nonIntraQuantMatrix = MPEG1.DEFAULT_NON_INTRA_QUANT_MATRIX;
this.mbWidth = (this.width + 15) >> 4;
this.mbHeight = (this.height + 15) >> 4;
this.mbSize = this.mbWidth * this.mbHeight;
this.codedWidth = this.mbWidth << 4;
this.codedHeight = this.mbHeight << 4;
this.codedSize = this.codedWidth * this.codedHeight;
this.halfWidth = this.mbWidth << 3;
this.halfHeight = this.mbHeight << 3;
// Allocated buffers and resize the canvas
this.currentY = new Uint8ClampedArray(this.codedSize);
this.currentY32 = new Uint32Array(this.currentY.buffer);
this.currentCr = new Uint8ClampedArray(this.codedSize >> 2);
this.currentCr32 = new Uint32Array(this.currentCr.buffer);
this.currentCb = new Uint8ClampedArray(this.codedSize >> 2);
this.currentCb32 = new Uint32Array(this.currentCb.buffer);
this.forwardY = new Uint8ClampedArray(this.codedSize);
this.forwardY32 = new Uint32Array(this.forwardY.buffer);
this.forwardCr = new Uint8ClampedArray(this.codedSize >> 2);
this.forwardCr32 = new Uint32Array(this.forwardCr.buffer);
this.forwardCb = new Uint8ClampedArray(this.codedSize >> 2);
this.forwardCb32 = new Uint32Array(this.forwardCb.buffer);
};
// Picture Layer
MPEG1.prototype.currentY = null;
MPEG1.prototype.currentCr = null;
MPEG1.prototype.currentCb = null;
MPEG1.prototype.pictureType = 0;
// Buffers for motion compensation
MPEG1.prototype.forwardY = null;
MPEG1.prototype.forwardCr = null;
MPEG1.prototype.forwardCb = null;
MPEG1.prototype.fullPelForward = false;
MPEG1.prototype.forwardFCode = 0;
MPEG1.prototype.forwardRSize = 0;
MPEG1.prototype.forwardF = 0;
MPEG1.prototype.decodePicture = function(skipOutput) {
this.currentFrame++;
this.bits.skip(10); // skip temporalReference
this.pictureType = this.bits.read(3);
this.bits.skip(16); // skip vbv_delay
// Skip B and D frames or unknown coding type
if (this.pictureType <= 0 || this.pictureType >= MPEG1.PICTURE_TYPE.B) {
return;
}
// full_pel_forward, forward_f_code
if (this.pictureType === MPEG1.PICTURE_TYPE.PREDICTIVE) {
this.fullPelForward = this.bits.read(1);
this.forwardFCode = this.bits.read(3);
if (this.forwardFCode === 0) {
// Ignore picture with zero forward_f_code
return;
}
this.forwardRSize = this.forwardFCode - 1;
this.forwardF = 1 << this.forwardRSize;
}
var code = 0;
do {
code = this.bits.findNextStartCode();
} while (code === MPEG1.START.EXTENSION || code === MPEG1.START.USER_DATA );
while (code >= MPEG1.START.SLICE_FIRST && code <= MPEG1.START.SLICE_LAST) {
this.decodeSlice(code & 0x000000FF);
code = this.bits.findNextStartCode();
}
if (code !== -1) {
// We found the next start code; rewind 32bits and let the main loop
// handle it.
this.bits.rewind(32);
}
// Invoke decode callbacks
if (this.destination) {
this.destination.render(this.currentY, this.currentCr, this.currentCb);
}
// If this is a reference picutre then rotate the prediction pointers
if (
this.pictureType === MPEG1.PICTURE_TYPE.INTRA ||
this.pictureType === MPEG1.PICTURE_TYPE.PREDICTIVE
) {
var
tmpY = this.forwardY,
tmpY32 = this.forwardY32,
tmpCr = this.forwardCr,
tmpCr32 = this.forwardCr32,
tmpCb = this.forwardCb,
tmpCb32 = this.forwardCb32;
this.forwardY = this.currentY;
this.forwardY32 = this.currentY32;
this.forwardCr = this.currentCr;
this.forwardCr32 = this.currentCr32;
this.forwardCb = this.currentCb;
this.forwardCb32 = this.currentCb32;
this.currentY = tmpY;
this.currentY32 = tmpY32;
this.currentCr = tmpCr;
this.currentCr32 = tmpCr32;
this.currentCb = tmpCb;
this.currentCb32 = tmpCb32;
}
};
// Slice Layer
MPEG1.prototype.quantizerScale = 0;
MPEG1.prototype.sliceBegin = false;
MPEG1.prototype.decodeSlice = function(slice) {
this.sliceBegin = true;
this.macroblockAddress = (slice - 1) * this.mbWidth - 1;
// Reset motion vectors and DC predictors
this.motionFwH = this.motionFwHPrev = 0;
this.motionFwV = this.motionFwVPrev = 0;
this.dcPredictorY = 128;
this.dcPredictorCr = 128;
this.dcPredictorCb = 128;
this.quantizerScale = this.bits.read(5);
// skip extra bits
while (this.bits.read(1)) {
this.bits.skip(8);
}
do {
this.decodeMacroblock();
} while (!this.bits.nextBytesAreStartCode());
};
// Macroblock Layer
MPEG1.prototype.macroblockAddress = 0;
MPEG1.prototype.mbRow = 0;
MPEG1.prototype.mbCol = 0;
MPEG1.prototype.macroblockType = 0;
MPEG1.prototype.macroblockIntra = false;
MPEG1.prototype.macroblockMotFw = false;
MPEG1.prototype.motionFwH = 0;
MPEG1.prototype.motionFwV = 0;
MPEG1.prototype.motionFwHPrev = 0;
MPEG1.prototype.motionFwVPrev = 0;
MPEG1.prototype.decodeMacroblock = function() {
// Decode macroblock_address_increment
var
increment = 0,
t = this.readHuffman(MPEG1.MACROBLOCK_ADDRESS_INCREMENT);
while (t === 34) {
// macroblock_stuffing
t = this.readHuffman(MPEG1.MACROBLOCK_ADDRESS_INCREMENT);
}
while (t === 35) {
// macroblock_escape
increment += 33;
t = this.readHuffman(MPEG1.MACROBLOCK_ADDRESS_INCREMENT);
}
increment += t;
// Process any skipped macroblocks
if (this.sliceBegin) {
// The first macroblock_address_increment of each slice is relative
// to beginning of the preverious row, not the preverious macroblock
this.sliceBegin = false;
this.macroblockAddress += increment;
}
else {
if (this.macroblockAddress + increment >= this.mbSize) {
// Illegal (too large) macroblock_address_increment
return;
}
if (increment > 1) {
// Skipped macroblocks reset DC predictors
this.dcPredictorY = 128;
this.dcPredictorCr = 128;
this.dcPredictorCb = 128;
// Skipped macroblocks in P-pictures reset motion vectors
if (this.pictureType === MPEG1.PICTURE_TYPE.PREDICTIVE) {
this.motionFwH = this.motionFwHPrev = 0;
this.motionFwV = this.motionFwVPrev = 0;
}
}
// Predict skipped macroblocks
while (increment > 1) {
this.macroblockAddress++;
this.mbRow = (this.macroblockAddress / this.mbWidth)|0;
this.mbCol = this.macroblockAddress % this.mbWidth;
this.copyMacroblock(
this.motionFwH, this.motionFwV,
this.forwardY, this.forwardCr, this.forwardCb
);
increment--;
}
this.macroblockAddress++;
}
this.mbRow = (this.macroblockAddress / this.mbWidth)|0;
this.mbCol = this.macroblockAddress % this.mbWidth;
// Process the current macroblock
var mbTable = MPEG1.MACROBLOCK_TYPE[this.pictureType];
this.macroblockType = this.readHuffman(mbTable);
this.macroblockIntra = (this.macroblockType & 0x01);
this.macroblockMotFw = (this.macroblockType & 0x08);
// Quantizer scale
if ((this.macroblockType & 0x10) !== 0) {
this.quantizerScale = this.bits.read(5);
}
if (this.macroblockIntra) {
// Intra-coded macroblocks reset motion vectors
this.motionFwH = this.motionFwHPrev = 0;
this.motionFwV = this.motionFwVPrev = 0;
}
else {
// Non-intra macroblocks reset DC predictors
this.dcPredictorY = 128;
this.dcPredictorCr = 128;
this.dcPredictorCb = 128;
this.decodeMotionVectors();
this.copyMacroblock(
this.motionFwH, this.motionFwV,
this.forwardY, this.forwardCr, this.forwardCb
);
}
// Decode blocks
var cbp = ((this.macroblockType & 0x02) !== 0)
? this.readHuffman(MPEG1.CODE_BLOCK_PATTERN)
: (this.macroblockIntra ? 0x3f : 0);
for (var block = 0, mask = 0x20; block < 6; block++) {
if ((cbp & mask) !== 0) {
this.decodeBlock(block);
}
mask >>= 1;
}
};
MPEG1.prototype.decodeMotionVectors = function() {
var code, d, r = 0;
// Forward
if (this.macroblockMotFw) {
// Horizontal forward
code = this.readHuffman(MPEG1.MOTION);
if ((code !== 0) && (this.forwardF !== 1)) {
r = this.bits.read(this.forwardRSize);
d = ((Math.abs(code) - 1) << this.forwardRSize) + r + 1;
if (code < 0) {
d = -d;
}
}
else {
d = code;
}
this.motionFwHPrev += d;
if (this.motionFwHPrev > (this.forwardF << 4) - 1) {
this.motionFwHPrev -= this.forwardF << 5;
}
else if (this.motionFwHPrev < ((-this.forwardF) << 4)) {
this.motionFwHPrev += this.forwardF << 5;
}
this.motionFwH = this.motionFwHPrev;
if (this.fullPelForward) {
this.motionFwH <<= 1;
}
// Vertical forward
code = this.readHuffman(MPEG1.MOTION);
if ((code !== 0) && (this.forwardF !== 1)) {
r = this.bits.read(this.forwardRSize);
d = ((Math.abs(code) - 1) << this.forwardRSize) + r + 1;
if (code < 0) {
d = -d;
}
}
else {
d = code;
}
this.motionFwVPrev += d;
if (this.motionFwVPrev > (this.forwardF << 4) - 1) {
this.motionFwVPrev -= this.forwardF << 5;
}
else if (this.motionFwVPrev < ((-this.forwardF) << 4)) {
this.motionFwVPrev += this.forwardF << 5;
}
this.motionFwV = this.motionFwVPrev;
if (this.fullPelForward) {
this.motionFwV <<= 1;
}
}
else if (this.pictureType === MPEG1.PICTURE_TYPE.PREDICTIVE) {
// No motion information in P-picture, reset vectors
this.motionFwH = this.motionFwHPrev = 0;
this.motionFwV = this.motionFwVPrev = 0;
}
};
MPEG1.prototype.copyMacroblock = function(motionH, motionV, sY, sCr, sCb) {
var
width, scan,
H, V, oddH, oddV,
src, dest, last;
// We use 32bit writes here
var dY = this.currentY32,
dCb = this.currentCb32,
dCr = this.currentCr32;
// Luminance
width = this.codedWidth;
scan = width - 16;
H = motionH >> 1;
V = motionV >> 1;
oddH = (motionH & 1) === 1;
oddV = (motionV & 1) === 1;
src = ((this.mbRow << 4) + V) * width + (this.mbCol << 4) + H;
dest = (this.mbRow * width + this.mbCol) << 2;
last = dest + (width << 2);
var x, y1, y2, y;
if (oddH) {
if (oddV) {
while (dest < last) {
y1 = sY[src] + sY[src+width]; src++;
for (x = 0; x < 4; x++) {
y2 = sY[src] + sY[src+width]; src++;
y = (((y1 + y2 + 2) >> 2) & 0xff);
y1 = sY[src] + sY[src+width]; src++;
y |= (((y1 + y2 + 2) << 6) & 0xff00);
y2 = sY[src] + sY[src+width]; src++;
y |= (((y1 + y2 + 2) << 14) & 0xff0000);
y1 = sY[src] + sY[src+width]; src++;
y |= (((y1 + y2 + 2) << 22) & 0xff000000);
dY[dest++] = y;
}
dest += scan >> 2; src += scan-1;
}
}
else {
while (dest < last) {
y1 = sY[src++];
for (x = 0; x < 4; x++) {
y2 = sY[src++];
y = (((y1 + y2 + 1) >> 1) & 0xff);
y1 = sY[src++];
y |= (((y1 + y2 + 1) << 7) & 0xff00);
y2 = sY[src++];
y |= (((y1 + y2 + 1) << 15) & 0xff0000);
y1 = sY[src++];
y |= (((y1 + y2 + 1) << 23) & 0xff000000);
dY[dest++] = y;
}
dest += scan >> 2; src += scan-1;
}
}
}
else {
if (oddV) {
while (dest < last) {
for (x = 0; x < 4; x++) {
y = (((sY[src] + sY[src+width] + 1) >> 1) & 0xff); src++;
y |= (((sY[src] + sY[src+width] + 1) << 7) & 0xff00); src++;
y |= (((sY[src] + sY[src+width] + 1) << 15) & 0xff0000); src++;
y |= (((sY[src] + sY[src+width] + 1) << 23) & 0xff000000); src++;
dY[dest++] = y;
}
dest += scan >> 2; src += scan;
}
}
else {
while (dest < last) {
for (x = 0; x < 4; x++) {
y = sY[src]; src++;
y |= sY[src] << 8; src++;
y |= sY[src] << 16; src++;
y |= sY[src] << 24; src++;
dY[dest++] = y;
}
dest += scan >> 2; src += scan;
}
}
}
// Chrominance
width = this.halfWidth;
scan = width - 8;
H = (motionH/2) >> 1;
V = (motionV/2) >> 1;
oddH = ((motionH/2) & 1) === 1;
oddV = ((motionV/2) & 1) === 1;
src = ((this.mbRow << 3) + V) * width + (this.mbCol << 3) + H;
dest = (this.mbRow * width + this.mbCol) << 1;
last = dest + (width << 1);
var cr1, cr2, cr,
cb1, cb2, cb;
if (oddH) {
if (oddV) {
while (dest < last) {
cr1 = sCr[src] + sCr[src+width];
cb1 = sCb[src] + sCb[src+width];
src++;
for (x = 0; x < 2; x++) {
cr2 = sCr[src] + sCr[src+width];
cb2 = sCb[src] + sCb[src+width]; src++;
cr = (((cr1 + cr2 + 2) >> 2) & 0xff);
cb = (((cb1 + cb2 + 2) >> 2) & 0xff);
cr1 = sCr[src] + sCr[src+width];
cb1 = sCb[src] + sCb[src+width]; src++;
cr |= (((cr1 + cr2 + 2) << 6) & 0xff00);
cb |= (((cb1 + cb2 + 2) << 6) & 0xff00);
cr2 = sCr[src] + sCr[src+width];
cb2 = sCb[src] + sCb[src+width]; src++;
cr |= (((cr1 + cr2 + 2) << 14) & 0xff0000);
cb |= (((cb1 + cb2 + 2) << 14) & 0xff0000);
cr1 = sCr[src] + sCr[src+width];
cb1 = sCb[src] + sCb[src+width]; src++;
cr |= (((cr1 + cr2 + 2) << 22) & 0xff000000);
cb |= (((cb1 + cb2 + 2) << 22) & 0xff000000);
dCr[dest] = cr;
dCb[dest] = cb;
dest++;
}
dest += scan >> 2; src += scan-1;
}
}
else {
while (dest < last) {
cr1 = sCr[src];
cb1 = sCb[src];
src++;
for (x = 0; x < 2; x++) {
cr2 = sCr[src];
cb2 = sCb[src++];
cr = (((cr1 + cr2 + 1) >> 1) & 0xff);
cb = (((cb1 + cb2 + 1) >> 1) & 0xff);
cr1 = sCr[src];
cb1 = sCb[src++];
cr |= (((cr1 + cr2 + 1) << 7) & 0xff00);
cb |= (((cb1 + cb2 + 1) << 7) & 0xff00);
cr2 = sCr[src];
cb2 = sCb[src++];
cr |= (((cr1 + cr2 + 1) << 15) & 0xff0000);
cb |= (((cb1 + cb2 + 1) << 15) & 0xff0000);
cr1 = sCr[src];
cb1 = sCb[src++];
cr |= (((cr1 + cr2 + 1) << 23) & 0xff000000);
cb |= (((cb1 + cb2 + 1) << 23) & 0xff000000);
dCr[dest] = cr;
dCb[dest] = cb;
dest++;
}
dest += scan >> 2; src += scan-1;
}
}
}
else {
if (oddV) {
while (dest < last) {
for (x = 0; x < 2; x++) {
cr = (((sCr[src] + sCr[src+width] + 1) >> 1) & 0xff);
cb = (((sCb[src] + sCb[src+width] + 1) >> 1) & 0xff); src++;
cr |= (((sCr[src] + sCr[src+width] + 1) << 7) & 0xff00);
cb |= (((sCb[src] + sCb[src+width] + 1) << 7) & 0xff00); src++;
cr |= (((sCr[src] + sCr[src+width] + 1) << 15) & 0xff0000);
cb |= (((sCb[src] + sCb[src+width] + 1) << 15) & 0xff0000); src++;
cr |= (((sCr[src] + sCr[src+width] + 1) << 23) & 0xff000000);
cb |= (((sCb[src] + sCb[src+width] + 1) << 23) & 0xff000000); src++;
dCr[dest] = cr;
dCb[dest] = cb;
dest++;
}
dest += scan >> 2; src += scan;
}
}
else {
while (dest < last) {
for (x = 0; x < 2; x++) {
cr = sCr[src];
cb = sCb[src]; src++;
cr |= sCr[src] << 8;
cb |= sCb[src] << 8; src++;
cr |= sCr[src] << 16;
cb |= sCb[src] << 16; src++;
cr |= sCr[src] << 24;
cb |= sCb[src] << 24; src++;
dCr[dest] = cr;
dCb[dest] = cb;
dest++;
}
dest += scan >> 2; src += scan;
}
}
}
};
// Block layer
MPEG1.prototype.dcPredictorY = 0;
MPEG1.prototype.dcPredictorCr = 0;
MPEG1.prototype.dcPredictorCb = 0;
MPEG1.prototype.blockData = null;
MPEG1.prototype.decodeBlock = function(block) {
var
n = 0,
quantMatrix;
// Decode DC coefficient of intra-coded blocks
if (this.macroblockIntra) {
var
predictor,
dctSize;
// DC prediction
if (block < 4) {
predictor = this.dcPredictorY;
dctSize = this.readHuffman(MPEG1.DCT_DC_SIZE_LUMINANCE);
}
else {
predictor = (block === 4 ? this.dcPredictorCr : this.dcPredictorCb);
dctSize = this.readHuffman(MPEG1.DCT_DC_SIZE_CHROMINANCE);
}
// Read DC coeff
if (dctSize > 0) {
var differential = this.bits.read(dctSize);
if ((differential & (1 << (dctSize - 1))) !== 0) {
this.blockData[0] = predictor + differential;
}
else {
this.blockData[0] = predictor + ((-1 << dctSize)|(differential+1));
}
}
else {
this.blockData[0] = predictor;
}
// Save predictor value
if (block < 4) {
this.dcPredictorY = this.blockData[0];
}
else if (block === 4) {
this.dcPredictorCr = this.blockData[0];
}
else {
this.dcPredictorCb = this.blockData[0];
}
// Dequantize + premultiply
this.blockData[0] <<= (3 + 5);
quantMatrix = this.intraQuantMatrix;
n = 1;
}
else {
quantMatrix = this.nonIntraQuantMatrix;
}
// Decode AC coefficients (+DC for non-intra)
var level = 0;
while (true) {
var
run = 0,
coeff = this.readHuffman(MPEG1.DCT_COEFF);
if ((coeff === 0x0001) && (n > 0) && (this.bits.read(1) === 0)) {
// end_of_block
break;
}
if (coeff === 0xffff) {
// escape
run = this.bits.read(6);
level = this.bits.read(8);
if (level === 0) {
level = this.bits.read(8);
}
else if (level === 128) {
level = this.bits.read(8) - 256;
}
else if (level > 128) {
level = level - 256;
}
}
else {
run = coeff >> 8;
level = coeff & 0xff;
if (this.bits.read(1)) {
level = -level;
}
}
n += run;
var dezigZagged = MPEG1.ZIG_ZAG[n];
n++;
// Dequantize, oddify, clip
level <<= 1;
if (!this.macroblockIntra) {
level += (level < 0 ? -1 : 1);
}
level = (level * this.quantizerScale * quantMatrix[dezigZagged]) >> 4;
if ((level & 1) === 0) {
level -= level > 0 ? 1 : -1;
}
if (level > 2047) {
level = 2047;
}
else if (level < -2048) {
level = -2048;
}
// Save premultiplied coefficient
this.blockData[dezigZagged] = level * MPEG1.PREMULTIPLIER_MATRIX[dezigZagged];
}
// Move block to its place
var
destArray,
destIndex,
scan;
if (block < 4) {
destArray = this.currentY;
scan = this.codedWidth - 8;
destIndex = (this.mbRow * this.codedWidth + this.mbCol) << 4;
if ((block & 1) !== 0) {
destIndex += 8;
}
if ((block & 2) !== 0) {
destIndex += this.codedWidth << 3;
}
}
else {
destArray = (block === 4) ? this.currentCb : this.currentCr;
scan = (this.codedWidth >> 1) - 8;
destIndex = ((this.mbRow * this.codedWidth) << 2) + (this.mbCol << 3);
}
if (this.macroblockIntra) {
// Overwrite (no prediction)
if (n === 1) {
MPEG1.CopyValueToDestination((this.blockData[0] + 128) >> 8, destArray, destIndex, scan);
this.blockData[0] = 0;
}
else {
MPEG1.IDCT(this.blockData);
MPEG1.CopyBlockToDestination(this.blockData, destArray, destIndex, scan);
JSMpeg.Fill(this.blockData, 0);
}
}
else {
// Add data to the predicted macroblock
if (n === 1) {
MPEG1.AddValueToDestination((this.blockData[0] + 128) >> 8, destArray, destIndex, scan);
this.blockData[0] = 0;
}
else {
MPEG1.IDCT(this.blockData);
MPEG1.AddBlockToDestination(this.blockData, destArray, destIndex, scan);
JSMpeg.Fill(this.blockData, 0);
}
}
n = 0;
};
MPEG1.CopyBlockToDestination = function(block, dest, index, scan) {
for (var n = 0; n < 64; n += 8, index += scan+8) {
dest[index+0] = block[n+0];
dest[index+1] = block[n+1];
dest[index+2] = block[n+2];
dest[index+3] = block[n+3];
dest[index+4] = block[n+4];
dest[index+5] = block[n+5];
dest[index+6] = block[n+6];
dest[index+7] = block[n+7];
}
};
MPEG1.AddBlockToDestination = function(block, dest, index, scan) {
for (var n = 0; n < 64; n += 8, index += scan+8) {
dest[index+0] += block[n+0];
dest[index+1] += block[n+1];
dest[index+2] += block[n+2];
dest[index+3] += block[n+3];
dest[index+4] += block[n+4];
dest[index+5] += block[n+5];
dest[index+6] += block[n+6];
dest[index+7] += block[n+7];
}
};
MPEG1.CopyValueToDestination = function(value, dest, index, scan) {
for (var n = 0; n < 64; n += 8, index += scan+8) {
dest[index+0] = value;
dest[index+1] = value;
dest[index+2] = value;
dest[index+3] = value;
dest[index+4] = value;
dest[index+5] = value;
dest[index+6] = value;
dest[index+7] = value;
}
};
MPEG1.AddValueToDestination = function(value, dest, index, scan) {
for (var n = 0; n < 64; n += 8, index += scan+8) {
dest[index+0] += value;
dest[index+1] += value;
dest[index+2] += value;
dest[index+3] += value;
dest[index+4] += value;
dest[index+5] += value;
dest[index+6] += value;
dest[index+7] += value;
}
};
MPEG1.IDCT = function(block) {
// See http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/IDCT.html
// for more info.
var
b1, b3, b4, b6, b7, tmp1, tmp2, m0,
x0, x1, x2, x3, x4, y3, y4, y5, y6, y7;
// Transform columns
for (var i = 0; i < 8; ++i) {
b1 = block[4*8+i];
b3 = block[2*8+i] + block[6*8+i];
b4 = block[5*8+i] - block[3*8+i];
tmp1 = block[1*8+i] + block[7*8+i];
tmp2 = block[3*8+i] + block[5*8+i];
b6 = block[1*8+i] - block[7*8+i];
b7 = tmp1 + tmp2;
m0 = block[0*8+i];
x4 = ((b6*473 - b4*196 + 128) >> 8) - b7;
x0 = x4 - (((tmp1 - tmp2)*362 + 128) >> 8);
x1 = m0 - b1;
x2 = (((block[2*8+i] - block[6*8+i])*362 + 128) >> 8) - b3;
x3 = m0 + b1;
y3 = x1 + x2;
y4 = x3 + b3;
y5 = x1 - x2;
y6 = x3 - b3;
y7 = -x0 - ((b4*473 + b6*196 + 128) >> 8);
block[0*8+i] = b7 + y4;
block[1*8+i] = x4 + y3;
block[2*8+i] = y5 - x0;
block[3*8+i] = y6 - y7;
block[4*8+i] = y6 + y7;
block[5*8+i] = x0 + y5;
block[6*8+i] = y3 - x4;
block[7*8+i] = y4 - b7;
}
// Transform rows
for (var i = 0; i < 64; i += 8) {
b1 = block[4+i];
b3 = block[2+i] + block[6+i];
b4 = block[5+i] - block[3+i];
tmp1 = block[1+i] + block[7+i];
tmp2 = block[3+i] + block[5+i];
b6 = block[1+i] - block[7+i];
b7 = tmp1 + tmp2;
m0 = block[0+i];
x4 = ((b6*473 - b4*196 + 128) >> 8) - b7;
x0 = x4 - (((tmp1 - tmp2)*362 + 128) >> 8);
x1 = m0 - b1;
x2 = (((block[2+i] - block[6+i])*362 + 128) >> 8) - b3;
x3 = m0 + b1;
y3 = x1 + x2;
y4 = x3 + b3;
y5 = x1 - x2;
y6 = x3 - b3;
y7 = -x0 - ((b4*473 + b6*196 + 128) >> 8);
block[0+i] = (b7 + y4 + 128) >> 8;
block[1+i] = (x4 + y3 + 128) >> 8;
block[2+i] = (y5 - x0 + 128) >> 8;
block[3+i] = (y6 - y7 + 128) >> 8;
block[4+i] = (y6 + y7 + 128) >> 8;
block[5+i] = (x0 + y5 + 128) >> 8;
block[6+i] = (y3 - x4 + 128) >> 8;
block[7+i] = (y4 - b7 + 128) >> 8;
}
};
// VLC Tables and Constants
MPEG1.PICTURE_RATE = [
0.000, 23.976, 24.000, 25.000, 29.970, 30.000, 50.000, 59.940,
60.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000
];
MPEG1.ZIG_ZAG = new Uint8Array([
0, 1, 8, 16, 9, 2, 3, 10,
17, 24, 32, 25, 18, 11, 4, 5,
12, 19, 26, 33, 40, 48, 41, 34,
27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36,
29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46,
53, 60, 61, 54, 47, 55, 62, 63
]);
MPEG1.DEFAULT_INTRA_QUANT_MATRIX = new Uint8Array([
8, 16, 19, 22, 26, 27, 29, 34,
16, 16, 22, 24, 27, 29, 34, 37,
19, 22, 26, 27, 29, 34, 34, 38,
22, 22, 26, 27, 29, 34, 37, 40,
22, 26, 27, 29, 32, 35, 40, 48,
26, 27, 29, 32, 35, 40, 48, 58,
26, 27, 29, 34, 38, 46, 56, 69,
27, 29, 35, 38, 46, 56, 69, 83
]);
MPEG1.DEFAULT_NON_INTRA_QUANT_MATRIX = new Uint8Array([
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16
]);
MPEG1.PREMULTIPLIER_MATRIX = new Uint8Array([
32, 44, 42, 38, 32, 25, 17, 9,
44, 62, 58, 52, 44, 35, 24, 12,
42, 58, 55, 49, 42, 33, 23, 12,
38, 52, 49, 44, 38, 30, 20, 10,
32, 44, 42, 38, 32, 25, 17, 9,
25, 35, 33, 30, 25, 20, 14, 7,
17, 24, 23, 20, 17, 14, 9, 5,
9, 12, 12, 10, 9, 7, 5, 2
]);
// MPEG-1 VLC
// macroblock_stuffing decodes as 34.
// macroblock_escape decodes as 35.
MPEG1.MACROBLOCK_ADDRESS_INCREMENT = new Int16Array([
1*3, 2*3, 0, // 0
3*3, 4*3, 0, // 1 0
0, 0, 1, // 2 1.
5*3, 6*3, 0, // 3 00
7*3, 8*3, 0, // 4 01
9*3, 10*3, 0, // 5 000
11*3, 12*3, 0, // 6 001
0, 0, 3, // 7 010.
0, 0, 2, // 8 011.
13*3, 14*3, 0, // 9 0000
15*3, 16*3, 0, // 10 0001
0, 0, 5, // 11 0010.
0, 0, 4, // 12 0011.
17*3, 18*3, 0, // 13 0000 0
19*3, 20*3, 0, // 14 0000 1
0, 0, 7, // 15 0001 0.
0, 0, 6, // 16 0001 1.
21*3, 22*3, 0, // 17 0000 00
23*3, 24*3, 0, // 18 0000 01
25*3, 26*3, 0, // 19 0000 10
27*3, 28*3, 0, // 20 0000 11
-1, 29*3, 0, // 21 0000 000
-1, 30*3, 0, // 22 0000 001
31*3, 32*3, 0, // 23 0000 010
33*3, 34*3, 0, // 24 0000 011
35*3, 36*3, 0, // 25 0000 100
37*3, 38*3, 0, // 26 0000 101
0, 0, 9, // 27 0000 110.
0, 0, 8, // 28 0000 111.
39*3, 40*3, 0, // 29 0000 0001
41*3, 42*3, 0, // 30 0000 0011
43*3, 44*3, 0, // 31 0000 0100
45*3, 46*3, 0, // 32 0000 0101
0, 0, 15, // 33 0000 0110.
0, 0, 14, // 34 0000 0111.
0, 0, 13, // 35 0000 1000.
0, 0, 12, // 36 0000 1001.
0, 0, 11, // 37 0000 1010.
0, 0, 10, // 38 0000 1011.
47*3, -1, 0, // 39 0000 0001 0
-1, 48*3, 0, // 40 0000 0001 1
49*3, 50*3, 0, // 41 0000 0011 0
51*3, 52*3, 0, // 42 0000 0011 1
53*3, 54*3, 0, // 43 0000 0100 0
55*3, 56*3, 0, // 44 0000 0100 1
57*3, 58*3, 0, // 45 0000 0101 0
59*3, 60*3, 0, // 46 0000 0101 1
61*3, -1, 0, // 47 0000 0001 00
-1, 62*3, 0, // 48 0000 0001 11
63*3, 64*3, 0, // 49 0000 0011 00
65*3, 66*3, 0, // 50 0000 0011 01
67*3, 68*3, 0, // 51 0000 0011 10
69*3, 70*3, 0, // 52 0000 0011 11
71*3, 72*3, 0, // 53 0000 0100 00
73*3, 74*3, 0, // 54 0000 0100 01
0, 0, 21, // 55 0000 0100 10.
0, 0, 20, // 56 0000 0100 11.
0, 0, 19, // 57 0000 0101 00.
0, 0, 18, // 58 0000 0101 01.
0, 0, 17, // 59 0000 0101 10.
0, 0, 16, // 60 0000 0101 11.
0, 0, 35, // 61 0000 0001 000. -- macroblock_escape
0, 0, 34, // 62 0000 0001 111. -- macroblock_stuffing
0, 0, 33, // 63 0000 0011 000.
0, 0, 32, // 64 0000 0011 001.
0, 0, 31, // 65 0000 0011 010.
0, 0, 30, // 66 0000 0011 011.
0, 0, 29, // 67 0000 0011 100.
0, 0, 28, // 68 0000 0011 101.
0, 0, 27, // 69 0000 0011 110.
0, 0, 26, // 70 0000 0011 111.
0, 0, 25, // 71 0000 0100 000.
0, 0, 24, // 72 0000 0100 001.
0, 0, 23, // 73 0000 0100 010.
0, 0, 22 // 74 0000 0100 011.
]);
// macroblock_type bitmap:
// 0x10 macroblock_quant
// 0x08 macroblock_motion_forward
// 0x04 macroblock_motion_backward
// 0x02 macrobkock_pattern
// 0x01 macroblock_intra
//
MPEG1.MACROBLOCK_TYPE_INTRA = new Int8Array([
1*3, 2*3, 0, // 0
-1, 3*3, 0, // 1 0
0, 0, 0x01, // 2 1.
0, 0, 0x11 // 3 01.
]);
MPEG1.MACROBLOCK_TYPE_PREDICTIVE = new Int8Array([
1*3, 2*3, 0, // 0
3*3, 4*3, 0, // 1 0
0, 0, 0x0a, // 2 1.
5*3, 6*3, 0, // 3 00
0, 0, 0x02, // 4 01.
7*3, 8*3, 0, // 5 000
0, 0, 0x08, // 6 001.
9*3, 10*3, 0, // 7 0000
11*3, 12*3, 0, // 8 0001
-1, 13*3, 0, // 9 00000
0, 0, 0x12, // 10 00001.
0, 0, 0x1a, // 11 00010.
0, 0, 0x01, // 12 00011.
0, 0, 0x11 // 13 000001.
]);
MPEG1.MACROBLOCK_TYPE_B = new Int8Array([
1*3, 2*3, 0, // 0
3*3, 5*3, 0, // 1 0
4*3, 6*3, 0, // 2 1
8*3, 7*3, 0, // 3 00
0, 0, 0x0c, // 4 10.
9*3, 10*3, 0, // 5 01
0, 0, 0x0e, // 6 11.
13*3, 14*3, 0, // 7 001
12*3, 11*3, 0, // 8 000
0, 0, 0x04, // 9 010.
0, 0, 0x06, // 10 011.
18*3, 16*3, 0, // 11 0001
15*3, 17*3, 0, // 12 0000
0, 0, 0x08, // 13 0010.
0, 0, 0x0a, // 14 0011.
-1, 19*3, 0, // 15 00000
0, 0, 0x01, // 16 00011.
20*3, 21*3, 0, // 17 00001
0, 0, 0x1e, // 18 00010.
0, 0, 0x11, // 19 000001.
0, 0, 0x16, // 20 000010.
0, 0, 0x1a // 21 000011.
]);
MPEG1.MACROBLOCK_TYPE = [
null,
MPEG1.MACROBLOCK_TYPE_INTRA,
MPEG1.MACROBLOCK_TYPE_PREDICTIVE,
MPEG1.MACROBLOCK_TYPE_B
];
MPEG1.CODE_BLOCK_PATTERN = new Int16Array([
2*3, 1*3, 0, // 0
3*3, 6*3, 0, // 1 1
4*3, 5*3, 0, // 2 0
8*3, 11*3, 0, // 3 10
12*3, 13*3, 0, // 4 00
9*3, 7*3, 0, // 5 01
10*3, 14*3, 0, // 6 11
20*3, 19*3, 0, // 7 011
18*3, 16*3, 0, // 8 100
23*3, 17*3, 0, // 9 010
27*3, 25*3, 0, // 10 110
21*3, 28*3, 0, // 11 101
15*3, 22*3, 0, // 12 000
24*3, 26*3, 0, // 13 001
0, 0, 60, // 14 111.
35*3, 40*3, 0, // 15 0000
44*3, 48*3, 0, // 16 1001
38*3, 36*3, 0, // 17 0101
42*3, 47*3, 0, // 18 1000
29*3, 31*3, 0, // 19 0111
39*3, 32*3, 0, // 20 0110
0, 0, 32, // 21 1010.
45*3, 46*3, 0, // 22 0001
33*3, 41*3, 0, // 23 0100
43*3, 34*3, 0, // 24 0010
0, 0, 4, // 25 1101.
30*3, 37*3, 0, // 26 0011
0, 0, 8, // 27 1100.
0, 0, 16, // 28 1011.
0, 0, 44, // 29 0111 0.
50*3, 56*3, 0, // 30 0011 0
0, 0, 28, // 31 0111 1.
0, 0, 52, // 32 0110 1.
0, 0, 62, // 33 0100 0.
61*3, 59*3, 0, // 34 0010 1
52*3, 60*3, 0, // 35 0000 0
0, 0, 1, // 36 0101 1.
55*3, 54*3, 0, // 37 0011 1
0, 0, 61, // 38 0101 0.
0, 0, 56, // 39 0110 0.
57*3, 58*3, 0, // 40 0000 1
0, 0, 2, // 41 0100 1.
0, 0, 40, // 42 1000 0.
51*3, 62*3, 0, // 43 0010 0
0, 0, 48, // 44 1001 0.
64*3, 63*3, 0, // 45 0001 0
49*3, 53*3, 0, // 46 0001 1
0, 0, 20, // 47 1000 1.
0, 0, 12, // 48 1001 1.
80*3, 83*3, 0, // 49 0001 10
0, 0, 63, // 50 0011 00.
77*3, 75*3, 0, // 51 0010 00
65*3, 73*3, 0, // 52 0000 00
84*3, 66*3, 0, // 53 0001 11
0, 0, 24, // 54 0011 11.
0, 0, 36, // 55 0011 10.
0, 0, 3, // 56 0011 01.
69*3, 87*3, 0, // 57 0000 10
81*3, 79*3, 0, // 58 0000 11
68*3, 71*3, 0, // 59 0010 11
70*3, 78*3, 0, // 60 0000 01
67*3, 76*3, 0, // 61 0010 10
72*3, 74*3, 0, // 62 0010 01
86*3, 85*3, 0, // 63 0001 01
88*3, 82*3, 0, // 64 0001 00
-1, 94*3, 0, // 65 0000 000
95*3, 97*3, 0, // 66 0001 111
0, 0, 33, // 67 0010 100.
0, 0, 9, // 68 0010 110.
106*3, 110*3, 0, // 69 0000 100
102*3, 116*3, 0, // 70 0000 010
0, 0, 5, // 71 0010 111.
0, 0, 10, // 72 0010 010.
93*3, 89*3, 0, // 73 0000 001
0, 0, 6, // 74 0010 011.
0, 0, 18, // 75 0010 001.
0, 0, 17, // 76 0010 101.
0, 0, 34, // 77 0010 000.
113*3, 119*3, 0, // 78 0000 011
103*3, 104*3, 0, // 79 0000 111
90*3, 92*3, 0, // 80 0001 100
109*3, 107*3, 0, // 81 0000 110
117*3, 118*3, 0, // 82 0001 001
101*3, 99*3, 0, // 83 0001 101
98*3, 96*3, 0, // 84 0001 110
100*3, 91*3, 0, // 85 0001 011
114*3, 115*3, 0, // 86 0001 010
105*3, 108*3, 0, // 87 0000 101
112*3, 111*3, 0, // 88 0001 000
121*3, 125*3, 0, // 89 0000 0011
0, 0, 41, // 90 0001 1000.
0, 0, 14, // 91 0001 0111.
0, 0, 21, // 92 0001 1001.
124*3, 122*3, 0, // 93 0000 0010
120*3, 123*3, 0, // 94 0000 0001
0, 0, 11, // 95 0001 1110.
0, 0, 19, // 96 0001 1101.
0, 0, 7, // 97 0001 1111.
0, 0, 35, // 98 0001 1100.
0, 0, 13, // 99 0001 1011.
0, 0, 50, // 100 0001 0110.
0, 0, 49, // 101 0001 1010.
0, 0, 58, // 102 0000 0100.
0, 0, 37, // 103 0000 1110.
0, 0, 25, // 104 0000 1111.
0, 0, 45, // 105 0000 1010.
0, 0, 57, // 106 0000 1000.
0, 0, 26, // 107 0000 1101.
0, 0, 29, // 108 0000 1011.
0, 0, 38, // 109 0000 1100.
0, 0, 53, // 110 0000 1001.
0, 0, 23, // 111 0001 0001.
0, 0, 43, // 112 0001 0000.
0, 0, 46, // 113 0000 0110.
0, 0, 42, // 114 0001 0100.
0, 0, 22, // 115 0001 0101.
0, 0, 54, // 116 0000 0101.
0, 0, 51, // 117 0001 0010.
0, 0, 15, // 118 0001 0011.
0, 0, 30, // 119 0000 0111.
0, 0, 39, // 120 0000 0001 0.
0, 0, 47, // 121 0000 0011 0.
0, 0, 55, // 122 0000 0010 1.
0, 0, 27, // 123 0000 0001 1.
0, 0, 59, // 124 0000 0010 0.
0, 0, 31 // 125 0000 0011 1.
]);
MPEG1.MOTION = new Int16Array([
1*3, 2*3, 0, // 0
4*3, 3*3, 0, // 1 0
0, 0, 0, // 2 1.
6*3, 5*3, 0, // 3 01
8*3, 7*3, 0, // 4 00
0, 0, -1, // 5 011.
0, 0, 1, // 6 010.
9*3, 10*3, 0, // 7 001
12*3, 11*3, 0, // 8 000
0, 0, 2, // 9 0010.
0, 0, -2, // 10 0011.
14*3, 15*3, 0, // 11 0001
16*3, 13*3, 0, // 12 0000
20*3, 18*3, 0, // 13 0000 1
0, 0, 3, // 14 0001 0.
0, 0, -3, // 15 0001 1.
17*3, 19*3, 0, // 16 0000 0
-1, 23*3, 0, // 17 0000 00
27*3, 25*3, 0, // 18 0000 11
26*3, 21*3, 0, // 19 0000 01
24*3, 22*3, 0, // 20 0000 10
32*3, 28*3, 0, // 21 0000 011
29*3, 31*3, 0, // 22 0000 101
-1, 33*3, 0, // 23 0000 001
36*3, 35*3, 0, // 24 0000 100
0, 0, -4, // 25 0000 111.
30*3, 34*3, 0, // 26 0000 010
0, 0, 4, // 27 0000 110.
0, 0, -7, // 28 0000 0111.
0, 0, 5, // 29 0000 1010.
37*3, 41*3, 0, // 30 0000 0100
0, 0, -5, // 31 0000 1011.
0, 0, 7, // 32 0000 0110.
38*3, 40*3, 0, // 33 0000 0011
42*3, 39*3, 0, // 34 0000 0101
0, 0, -6, // 35 0000 1001.
0, 0, 6, // 36 0000 1000.
51*3, 54*3, 0, // 37 0000 0100 0
50*3, 49*3, 0, // 38 0000 0011 0
45*3, 46*3, 0, // 39 0000 0101 1
52*3, 47*3, 0, // 40 0000 0011 1
43*3, 53*3, 0, // 41 0000 0100 1
44*3, 48*3, 0, // 42 0000 0101 0
0, 0, 10, // 43 0000 0100 10.
0, 0, 9, // 44 0000 0101 00.
0, 0, 8, // 45 0000 0101 10.
0, 0, -8, // 46 0000 0101 11.
57*3, 66*3, 0, // 47 0000 0011 11
0, 0, -9, // 48 0000 0101 01.
60*3, 64*3, 0, // 49 0000 0011 01
56*3, 61*3, 0, // 50 0000 0011 00
55*3, 62*3, 0, // 51 0000 0100 00
58*3, 63*3, 0, // 52 0000 0011 10
0, 0, -10, // 53 0000 0100 11.
59*3, 65*3, 0, // 54 0000 0100 01
0, 0, 12, // 55 0000 0100 000.
0, 0, 16, // 56 0000 0011 000.
0, 0, 13, // 57 0000 0011 110.
0, 0, 14, // 58 0000 0011 100.
0, 0, 11, // 59 0000 0100 010.
0, 0, 15, // 60 0000 0011 010.
0, 0, -16, // 61 0000 0011 001.
0, 0, -12, // 62 0000 0100 001.
0, 0, -14, // 63 0000 0011 101.
0, 0, -15, // 64 0000 0011 011.
0, 0, -11, // 65 0000 0100 011.
0, 0, -13 // 66 0000 0011 111.
]);
MPEG1.DCT_DC_SIZE_LUMINANCE = new Int8Array([
2*3, 1*3, 0, // 0
6*3, 5*3, 0, // 1 1
3*3, 4*3, 0, // 2 0
0, 0, 1, // 3 00.
0, 0, 2, // 4 01.
9*3, 8*3, 0, // 5 11
7*3, 10*3, 0, // 6 10
0, 0, 0, // 7 100.
12*3, 11*3, 0, // 8 111
0, 0, 4, // 9 110.
0, 0, 3, // 10 101.
13*3, 14*3, 0, // 11 1111
0, 0, 5, // 12 1110.
0, 0, 6, // 13 1111 0.
16*3, 15*3, 0, // 14 1111 1
17*3, -1, 0, // 15 1111 11
0, 0, 7, // 16 1111 10.
0, 0, 8 // 17 1111 110.
]);
MPEG1.DCT_DC_SIZE_CHROMINANCE = new Int8Array([
2*3, 1*3, 0, // 0
4*3, 3*3, 0, // 1 1
6*3, 5*3, 0, // 2 0
8*3, 7*3, 0, // 3 11
0, 0, 2, // 4 10.
0, 0, 1, // 5 01.
0, 0, 0, // 6 00.
10*3, 9*3, 0, // 7 111
0, 0, 3, // 8 110.
12*3, 11*3, 0, // 9 1111
0, 0, 4, // 10 1110.
14*3, 13*3, 0, // 11 1111 1
0, 0, 5, // 12 1111 0.
16*3, 15*3, 0, // 13 1111 11
0, 0, 6, // 14 1111 10.
17*3, -1, 0, // 15 1111 111
0, 0, 7, // 16 1111 110.
0, 0, 8 // 17 1111 1110.
]);
// dct_coeff bitmap:
// 0xff00 run
// 0x00ff level
// Decoded values are unsigned. Sign bit follows in the stream.
// Interpretation of the value 0x0001
// for dc_coeff_first: run=0, level=1
// for dc_coeff_next: If the next bit is 1: run=0, level=1
// If the next bit is 0: end_of_block
// escape decodes as 0xffff.
MPEG1.DCT_COEFF = new Int32Array([
1*3, 2*3, 0, // 0
4*3, 3*3, 0, // 1 0
0, 0, 0x0001, // 2 1.
7*3, 8*3, 0, // 3 01
6*3, 5*3, 0, // 4 00
13*3, 9*3, 0, // 5 001
11*3, 10*3, 0, // 6 000
14*3, 12*3, 0, // 7 010
0, 0, 0x0101, // 8 011.
20*3, 22*3, 0, // 9 0011
18*3, 21*3, 0, // 10 0001
16*3, 19*3, 0, // 11 0000
0, 0, 0x0201, // 12 0101.
17*3, 15*3, 0, // 13 0010
0, 0, 0x0002, // 14 0100.
0, 0, 0x0003, // 15 0010 1.
27*3, 25*3, 0, // 16 0000 0
29*3, 31*3, 0, // 17 0010 0
24*3, 26*3, 0, // 18 0001 0
32*3, 30*3, 0, // 19 0000 1
0, 0, 0x0401, // 20 0011 0.
23*3, 28*3, 0, // 21 0001 1
0, 0, 0x0301, // 22 0011 1.
0, 0, 0x0102, // 23 0001 10.
0, 0, 0x0701, // 24 0001 00.
0, 0, 0xffff, // 25 0000 01. -- escape
0, 0, 0x0601, // 26 0001 01.
37*3, 36*3, 0, // 27 0000 00
0, 0, 0x0501, // 28 0001 11.
35*3, 34*3, 0, // 29 0010 00
39*3, 38*3, 0, // 30 0000 11
33*3, 42*3, 0, // 31 0010 01
40*3, 41*3, 0, // 32 0000 10
52*3, 50*3, 0, // 33 0010 010
54*3, 53*3, 0, // 34 0010 001
48*3, 49*3, 0, // 35 0010 000
43*3, 45*3, 0, // 36 0000 001
46*3, 44*3, 0, // 37 0000 000
0, 0, 0x0801, // 38 0000 111.
0, 0, 0x0004, // 39 0000 110.
0, 0, 0x0202, // 40 0000 100.
0, 0, 0x0901, // 41 0000 101.
51*3, 47*3, 0, // 42 0010 011
55*3, 57*3, 0, // 43 0000 0010
60*3, 56*3, 0, // 44 0000 0001
59*3, 58*3, 0, // 45 0000 0011
61*3, 62*3, 0, // 46 0000 0000
0, 0, 0x0a01, // 47 0010 0111.
0, 0, 0x0d01, // 48 0010 0000.
0, 0, 0x0006, // 49 0010 0001.
0, 0, 0x0103, // 50 0010 0101.
0, 0, 0x0005, // 51 0010 0110.
0, 0, 0x0302, // 52 0010 0100.
0, 0, 0x0b01, // 53 0010 0011.
0, 0, 0x0c01, // 54 0010 0010.
76*3, 75*3, 0, // 55 0000 0010 0
67*3, 70*3, 0, // 56 0000 0001 1
73*3, 71*3, 0, // 57 0000 0010 1
78*3, 74*3, 0, // 58 0000 0011 1
72*3, 77*3, 0, // 59 0000 0011 0
69*3, 64*3, 0, // 60 0000 0001 0
68*3, 63*3, 0, // 61 0000 0000 0
66*3, 65*3, 0, // 62 0000 0000 1
81*3, 87*3, 0, // 63 0000 0000 01
91*3, 80*3, 0, // 64 0000 0001 01
82*3, 79*3, 0, // 65 0000 0000 11
83*3, 86*3, 0, // 66 0000 0000 10
93*3, 92*3, 0, // 67 0000 0001 10
84*3, 85*3, 0, // 68 0000 0000 00
90*3, 94*3, 0, // 69 0000 0001 00
88*3, 89*3, 0, // 70 0000 0001 11
0, 0, 0x0203, // 71 0000 0010 11.
0, 0, 0x0104, // 72 0000 0011 00.
0, 0, 0x0007, // 73 0000 0010 10.
0, 0, 0x0402, // 74 0000 0011 11.
0, 0, 0x0502, // 75 0000 0010 01.
0, 0, 0x1001, // 76 0000 0010 00.
0, 0, 0x0f01, // 77 0000 0011 01.
0, 0, 0x0e01, // 78 0000 0011 10.
105*3, 107*3, 0, // 79 0000 0000 111
111*3, 114*3, 0, // 80 0000 0001 011
104*3, 97*3, 0, // 81 0000 0000 010
125*3, 119*3, 0, // 82 0000 0000 110
96*3, 98*3, 0, // 83 0000 0000 100
-1, 123*3, 0, // 84 0000 0000 000
95*3, 101*3, 0, // 85 0000 0000 001
106*3, 121*3, 0, // 86 0000 0000 101
99*3, 102*3, 0, // 87 0000 0000 011
113*3, 103*3, 0, // 88 0000 0001 110
112*3, 116*3, 0, // 89 0000 0001 111
110*3, 100*3, 0, // 90 0000 0001 000
124*3, 115*3, 0, // 91 0000 0001 010
117*3, 122*3, 0, // 92 0000 0001 101
109*3, 118*3, 0, // 93 0000 0001 100
120*3, 108*3, 0, // 94 0000 0001 001
127*3, 136*3, 0, // 95 0000 0000 0010
139*3, 140*3, 0, // 96 0000 0000 1000
130*3, 126*3, 0, // 97 0000 0000 0101
145*3, 146*3, 0, // 98 0000 0000 1001
128*3, 129*3, 0, // 99 0000 0000 0110
0, 0, 0x0802, // 100 0000 0001 0001.
132*3, 134*3, 0, // 101 0000 0000 0011
155*3, 154*3, 0, // 102 0000 0000 0111
0, 0, 0x0008, // 103 0000 0001 1101.
137*3, 133*3, 0, // 104 0000 0000 0100
143*3, 144*3, 0, // 105 0000 0000 1110
151*3, 138*3, 0, // 106 0000 0000 1010
142*3, 141*3, 0, // 107 0000 0000 1111
0, 0, 0x000a, // 108 0000 0001 0011.
0, 0, 0x0009, // 109 0000 0001 1000.
0, 0, 0x000b, // 110 0000 0001 0000.
0, 0, 0x1501, // 111 0000 0001 0110.
0, 0, 0x0602, // 112 0000 0001 1110.
0, 0, 0x0303, // 113 0000 0001 1100.
0, 0, 0x1401, // 114 0000 0001 0111.
0, 0, 0x0702, // 115 0000 0001 0101.
0, 0, 0x1101, // 116 0000 0001 1111.
0, 0, 0x1201, // 117 0000 0001 1010.
0, 0, 0x1301, // 118 0000 0001 1001.
148*3, 152*3, 0, // 119 0000 0000 1101
0, 0, 0x0403, // 120 0000 0001 0010.
153*3, 150*3, 0, // 121 0000 0000 1011
0, 0, 0x0105, // 122 0000 0001 1011.
131*3, 135*3, 0, // 123 0000 0000 0001
0, 0, 0x0204, // 124 0000 0001 0100.
149*3, 147*3, 0, // 125 0000 0000 1100
172*3, 173*3, 0, // 126 0000 0000 0101 1
162*3, 158*3, 0, // 127 0000 0000 0010 0
170*3, 161*3, 0, // 128 0000 0000 0110 0
168*3, 166*3, 0, // 129 0000 0000 0110 1
157*3, 179*3, 0, // 130 0000 0000 0101 0
169*3, 167*3, 0, // 131 0000 0000 0001 0
174*3, 171*3, 0, // 132 0000 0000 0011 0
178*3, 177*3, 0, // 133 0000 0000 0100 1
156*3, 159*3, 0, // 134 0000 0000 0011 1
164*3, 165*3, 0, // 135 0000 0000 0001 1
183*3, 182*3, 0, // 136 0000 0000 0010 1
175*3, 176*3, 0, // 137 0000 0000 0100 0
0, 0, 0x0107, // 138 0000 0000 1010 1.
0, 0, 0x0a02, // 139 0000 0000 1000 0.
0, 0, 0x0902, // 140 0000 0000 1000 1.
0, 0, 0x1601, // 141 0000 0000 1111 1.
0, 0, 0x1701, // 142 0000 0000 1111 0.
0, 0, 0x1901, // 143 0000 0000 1110 0.
0, 0, 0x1801, // 144 0000 0000 1110 1.
0, 0, 0x0503, // 145 0000 0000 1001 0.
0, 0, 0x0304, // 146 0000 0000 1001 1.
0, 0, 0x000d, // 147 0000 0000 1100 1.
0, 0, 0x000c, // 148 0000 0000 1101 0.
0, 0, 0x000e, // 149 0000 0000 1100 0.
0, 0, 0x000f, // 150 0000 0000 1011 1.
0, 0, 0x0205, // 151 0000 0000 1010 0.
0, 0, 0x1a01, // 152 0000 0000 1101 1.
0, 0, 0x0106, // 153 0000 0000 1011 0.
180*3, 181*3, 0, // 154 0000 0000 0111 1
160*3, 163*3, 0, // 155 0000 0000 0111 0
196*3, 199*3, 0, // 156 0000 0000 0011 10
0, 0, 0x001b, // 157 0000 0000 0101 00.
203*3, 185*3, 0, // 158 0000 0000 0010 01
202*3, 201*3, 0, // 159 0000 0000 0011 11
0, 0, 0x0013, // 160 0000 0000 0111 00.
0, 0, 0x0016, // 161 0000 0000 0110 01.
197*3, 207*3, 0, // 162 0000 0000 0010 00
0, 0, 0x0012, // 163 0000 0000 0111 01.
191*3, 192*3, 0, // 164 0000 0000 0001 10
188*3, 190*3, 0, // 165 0000 0000 0001 11
0, 0, 0x0014, // 166 0000 0000 0110 11.
184*3, 194*3, 0, // 167 0000 0000 0001 01
0, 0, 0x0015, // 168 0000 0000 0110 10.
186*3, 193*3, 0, // 169 0000 0000 0001 00
0, 0, 0x0017, // 170 0000 0000 0110 00.
204*3, 198*3, 0, // 171 0000 0000 0011 01
0, 0, 0x0019, // 172 0000 0000 0101 10.
0, 0, 0x0018, // 173 0000 0000 0101 11.
200*3, 205*3, 0, // 174 0000 0000 0011 00
0, 0, 0x001f, // 175 0000 0000 0100 00.
0, 0, 0x001e, // 176 0000 0000 0100 01.
0, 0, 0x001c, // 177 0000 0000 0100 11.
0, 0, 0x001d, // 178 0000 0000 0100 10.
0, 0, 0x001a, // 179 0000 0000 0101 01.
0, 0, 0x0011, // 180 0000 0000 0111 10.
0, 0, 0x0010, // 181 0000 0000 0111 11.
189*3, 206*3, 0, // 182 0000 0000 0010 11
187*3, 195*3, 0, // 183 0000 0000 0010 10
218*3, 211*3, 0, // 184 0000 0000 0001 010
0, 0, 0x0025, // 185 0000 0000 0010 011.
215*3, 216*3, 0, // 186 0000 0000 0001 000
0, 0, 0x0024, // 187 0000 0000 0010 100.
210*3, 212*3, 0, // 188 0000 0000 0001 110
0, 0, 0x0022, // 189 0000 0000 0010 110.
213*3, 209*3, 0, // 190 0000 0000 0001 111
221*3, 222*3, 0, // 191 0000 0000 0001 100
219*3, 208*3, 0, // 192 0000 0000 0001 101
217*3, 214*3, 0, // 193 0000 0000 0001 001
223*3, 220*3, 0, // 194 0000 0000 0001 011
0, 0, 0x0023, // 195 0000 0000 0010 101.
0, 0, 0x010b, // 196 0000 0000 0011 100.
0, 0, 0x0028, // 197 0000 0000 0010 000.
0, 0, 0x010c, // 198 0000 0000 0011 011.
0, 0, 0x010a, // 199 0000 0000 0011 101.
0, 0, 0x0020, // 200 0000 0000 0011 000.
0, 0, 0x0108, // 201 0000 0000 0011 111.
0, 0, 0x0109, // 202 0000 0000 0011 110.
0, 0, 0x0026, // 203 0000 0000 0010 010.
0, 0, 0x010d, // 204 0000 0000 0011 010.
0, 0, 0x010e, // 205 0000 0000 0011 001.
0, 0, 0x0021, // 206 0000 0000 0010 111.
0, 0, 0x0027, // 207 0000 0000 0010 001.
0, 0, 0x1f01, // 208 0000 0000 0001 1011.
0, 0, 0x1b01, // 209 0000 0000 0001 1111.
0, 0, 0x1e01, // 210 0000 0000 0001 1100.
0, 0, 0x1002, // 211 0000 0000 0001 0101.
0, 0, 0x1d01, // 212 0000 0000 0001 1101.
0, 0, 0x1c01, // 213 0000 0000 0001 1110.
0, 0, 0x010f, // 214 0000 0000 0001 0011.
0, 0, 0x0112, // 215 0000 0000 0001 0000.
0, 0, 0x0111, // 216 0000 0000 0001 0001.
0, 0, 0x0110, // 217 0000 0000 0001 0010.
0, 0, 0x0603, // 218 0000 0000 0001 0100.
0, 0, 0x0b02, // 219 0000 0000 0001 1010.
0, 0, 0x0e02, // 220 0000 0000 0001 0111.
0, 0, 0x0d02, // 221 0000 0000 0001 1000.
0, 0, 0x0c02, // 222 0000 0000 0001 1001.
0, 0, 0x0f02 // 223 0000 0000 0001 0110.
]);
MPEG1.PICTURE_TYPE = {
INTRA: 1,
PREDICTIVE: 2,
B: 3
};
MPEG1.START = {
SEQUENCE: 0xB3,
SLICE_FIRST: 0x01,
SLICE_LAST: 0xAF,
PICTURE: 0x00,
EXTENSION: 0xB5,
USER_DATA: 0xB2
};
return MPEG1;
})();
|
var frontexpress = (function () {
'use strict';
/**
* HTTP method list
* @private
*/
var HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];
// not supported yet
// HEAD', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var slicedToArray = function () {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* Module dependencies.
* @private
*/
var Requester = function () {
function Requester() {
classCallCheck(this, Requester);
}
createClass(Requester, [{
key: 'fetch',
/**
* Make an ajax request.
*
* @param {Object} request
* @param {Function} success callback
* @param {Function} failure callback
* @private
*/
value: function fetch(request, resolve, reject) {
var method = request.method,
uri = request.uri,
headers = request.headers,
data = request.data;
var success = function success(responseText) {
resolve(request, {
status: 200,
statusText: 'OK',
responseText: responseText
});
};
var fail = function fail(_ref) {
var status = _ref.status,
statusText = _ref.statusText,
errorThrown = _ref.errorThrown;
reject(request, {
status: status,
statusText: statusText,
errorThrown: errorThrown,
errors: 'HTTP ' + status + ' ' + (statusText ? statusText : '')
});
};
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
success(xmlhttp.responseText);
} else {
fail({ status: xmlhttp.status, statusText: xmlhttp.statusText });
}
}
};
try {
xmlhttp.open(method, uri, true);
if (headers) {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = Object.keys(headers)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var header = _step.value;
xmlhttp.setRequestHeader(header, headers[header]);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
if (data) {
xmlhttp.send(data);
} else {
xmlhttp.send();
}
} catch (errorThrown) {
fail({ errorThrown: errorThrown });
}
}
}]);
return Requester;
}();
/**
* Module dependencies.
* @private
*/
/**
* Settings object.
* @private
*/
var Settings = function () {
/**
* Initialize the settings.
*
* - setup default configuration
*
* @private
*/
function Settings() {
classCallCheck(this, Settings);
// default settings
this.settings = {
'http requester': new Requester(),
'http GET transformer': {
uri: function uri(_ref) {
var _uri = _ref.uri,
headers = _ref.headers,
data = _ref.data;
if (!data) {
return _uri;
}
var uriWithoutAnchor = _uri,
anchor = '';
var match = /^(.*)(#.*)$/.exec(_uri);
if (match) {
var _$exec = /^(.*)(#.*)$/.exec(_uri);
var _$exec2 = slicedToArray(_$exec, 3);
uriWithoutAnchor = _$exec2[1];
anchor = _$exec2[2];
}
uriWithoutAnchor = Object.keys(data).reduce(function (gUri, d, index) {
gUri += '' + (index === 0 && gUri.indexOf('?') === -1 ? '?' : '&') + d + '=' + data[d];
return gUri;
}, uriWithoutAnchor);
return uriWithoutAnchor + anchor;
}
}
};
this.rules = {
'http requester': function httpRequester(requester) {
if (typeof requester.fetch !== 'function') {
throw new TypeError('setting http requester has no fetch method');
}
}
};
}
/**
* Assign `setting` to `val`
*
* @param {String} setting
* @param {*} [val]
* @private
*/
createClass(Settings, [{
key: 'set',
value: function set$$1(name, value) {
var checkRules = this.rules[name];
if (checkRules) {
checkRules(value);
}
this.settings[name] = value;
}
/**
* Return `setting`'s value.
*
* @param {String} setting
* @private
*/
}, {
key: 'get',
value: function get$$1(name) {
return this.settings[name];
}
}]);
return Settings;
}();
/**
* Middleware object.
* @public
*/
var Middleware = function () {
/**
* Middleware initialization
*
* @param {String} middleware name
*/
function Middleware() {
var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
classCallCheck(this, Middleware);
this.name = name;
}
/**
* Invoked by the app before an ajax request is sent or
* during the DOM loading (document.readyState === 'loading').
* See Application#_callMiddlewareEntered documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
// entered(request) { }
/**
* Invoked by the app before a new ajax request is sent or before the DOM is unloaded.
* See Application#_callMiddlewareExited documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @public
*/
// exited(request) { }
/**
* Invoked by the app after an ajax request has responded or on DOM ready
* (document.readyState === 'interactive').
* See Application#_callMiddlewareUpdated documentation for details.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
// updated(request, response) { }
/**
* Invoked by the app when an ajax request has failed.
*
* Override this method to add your custom behaviour
*
* @param {Object} request
* @param {Object} response
* @public
*/
// failed(request, response) { }
/**
* Allow the hand over to the next middleware object or function.
*
* Override this method and return `false` to break execution of
* middleware chain.
*
* @return {Boolean} `true` by default
*
* @public
*/
createClass(Middleware, [{
key: 'next',
value: function next() {
return true;
}
}]);
return Middleware;
}();
/**
* Module dependencies.
* @private
*/
/**
* Route object.
* @private
*/
var Route = function () {
/**
* Initialize the route.
*
* @private
*/
function Route(router, uriPart, method, middleware) {
classCallCheck(this, Route);
this.router = router;
this.uriPart = uriPart;
this.method = method;
this.middleware = middleware;
this.visited = false;
}
/**
* Return route's uri.
*
* @private
*/
createClass(Route, [{
key: 'uri',
get: function get$$1() {
if (!this.uriPart && !this.method) {
return undefined;
}
if (this.uriPart instanceof RegExp) {
return this.uriPart;
}
if (this.router.baseUri instanceof RegExp) {
return this.router.baseUri;
}
if (this.router.baseUri) {
var baseUri = this.router.baseUri.trim();
if (this.uriPart) {
return (baseUri + this.uriPart.trim()).replace(/\/{2,}/, '/');
}
return baseUri;
}
return this.uriPart;
}
}]);
return Route;
}();
/**
* Router object.
* @public
*/
var error_middleware_message = 'method takes at least a middleware';
var Router = function () {
/**
* Initialize the router.
*
* @private
*/
function Router(uri) {
classCallCheck(this, Router);
this._baseUri = uri;
this._routes = [];
}
/**
* Do some checks and set _baseUri.
*
* @private
*/
createClass(Router, [{
key: '_add',
/**
* Add a route to the router.
*
* @private
*/
value: function _add(route) {
this._routes.push(route);
return this;
}
/**
* Gather routes from routers filtered by _uri_ and HTTP _method_.
*
* @private
*/
}, {
key: 'routes',
value: function routes(uri, method) {
return this._routes.filter(function (route) {
if (route.method && route.method !== method) {
return false;
}
if (!route.uri || !uri) {
return true;
}
//remove query string from uri to test
//remove anchor from uri to test
var match = /^(.*)\?.*#.*|(.*)(?=\?|#)|(.*[^\?#])$/.exec(uri);
var baseUriToCheck = match[1] || match[2] || match[3];
if (route.uri instanceof RegExp) {
return baseUriToCheck.match(route.uri);
}
return route.uri === baseUriToCheck;
});
}
/**
* Gather visited routes from routers.
*
* @private
*/
}, {
key: 'visited',
value: function visited() {
return this._routes.filter(function (route) {
return route.visited;
});
}
/**
* Use the given middleware function or object on this router.
*
* // middleware function
* router.use((req, res, next) => {console.log('Hello')});
*
* // middleware object
* router.use(new Middleware());
*
* @param {Middleware|Function} middleware object or function
* @return {Router} for chaining
*
* @public
*/
}, {
key: 'use',
value: function use(middleware) {
if (!(middleware instanceof Middleware) && typeof middleware !== 'function') {
throw new TypeError(error_middleware_message);
}
this._add(new Route(this, undefined, undefined, middleware));
return this;
}
/**
* Use the given middleware function or object on this router for
* all HTTP methods.
*
* // middleware function
* router.all((req, res, next) => {console.log('Hello')});
*
* // middleware object
* router.all(new Middleware());
*
* @param {Middleware|Function} middleware object or function
* @return {Router} for chaining
*
* @public
*/
}, {
key: 'all',
value: function all() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var _toParameters = toParameters(args),
middleware = _toParameters.middleware;
if (!middleware) {
throw new TypeError(error_middleware_message);
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = HTTP_METHODS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var method = _step.value;
this[method.toLowerCase()].apply(this, args);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return this;
}
}, {
key: 'baseUri',
set: function set$$1(uri) {
if (!uri) {
return;
}
if (!this._baseUri) {
this._baseUri = uri;
return;
}
if (_typeof(this._baseUri) !== (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
throw new TypeError('router cannot mix regexp and uri');
}
}
/**
* Return router's _baseUri.
*
* @private
*/
,
get: function get$$1() {
return this._baseUri;
}
}]);
return Router;
}();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
var _loop = function _loop() {
var method = _step2.value;
/**
* Use the given middleware function or object, with optional _uri_ on
* HTTP methods: get, post, put, delete...
* Default _uri_ is "/".
*
* // middleware function will be applied on path "/"
* router.get((req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/" and
* router.get(new Middleware());
*
* // middleware function will be applied on path "/user"
* router.post('/user', (req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/user" and
* router.post('/user', new Middleware());
*
* @param {String} uri
* @param {Middleware|Function} middleware object or function
* @return {Router} for chaining
* @public
*/
var methodName = method.toLowerCase();
Router.prototype[methodName] = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var _toParameters2 = toParameters(args),
baseUri = _toParameters2.baseUri,
middleware = _toParameters2.middleware;
if (!middleware) {
throw new TypeError(error_middleware_message);
}
if (baseUri && this._baseUri && this._baseUri instanceof RegExp) {
throw new TypeError('router cannot mix uri/regexp');
}
this._add(new Route(this, baseUri, method, middleware));
return this;
};
};
for (var _iterator2 = HTTP_METHODS[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
_loop();
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
/**
* Module dependencies.
* @private
*/
/**
* Application class.
*/
var Application = function () {
/**
* Initialize the application.
*
* - setup default configuration
*
* @private
*/
function Application() {
classCallCheck(this, Application);
this.routers = [];
this.isDOMLoaded = false;
this.isDOMReady = false;
this.settings = new Settings();
}
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.set('foo');
* // => "bar"
*
* @param {String} setting
* @param {*} [val]
* @return {app} for chaining
* @public
*/
createClass(Application, [{
key: 'set',
value: function set$$1() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
// get behaviour
if (args.length === 1) {
return this.settings.get([args]);
}
// set behaviour
var name = args[0],
value = args[1];
this.settings.set(name, value);
return this;
}
/**
* Listen for DOM initialization and history state changes.
*
* The callback function is called once the DOM has
* the `document.readyState` equals to 'interactive'.
*
* app.listen(()=> {
* console.log('App is listening requests');
* console.log('DOM is ready!');
* });
*
*
* @param {Function} callback
* @public
*/
}, {
key: 'listen',
value: function listen(callback) {
var _this = this;
window.onbeforeunload = function () {
_this._callMiddlewareMethod('exited');
};
window.onpopstate = function (event) {
if (event.state) {
var _event$state = event.state,
request = _event$state.request,
response = _event$state.response;
var currentRoutes = _this._routes(request.uri, request.method);
_this._callMiddlewareMethod('entered', currentRoutes, request);
_this._callMiddlewareMethod('updated', currentRoutes, request, response);
}
};
document.onreadystatechange = function () {
var request = { method: 'GET', uri: window.location.pathname + window.location.search };
var response = { status: 200, statusText: 'OK' };
var currentRoutes = _this._routes();
// DOM state
if (document.readyState === 'loading' && !_this.isDOMLoaded) {
_this.isDOMLoaded = true;
_this._callMiddlewareMethod('entered', currentRoutes, request);
} else if (document.readyState === 'interactive' && !_this.isDOMReady) {
if (!_this.isDOMLoaded) {
_this.isDOMLoaded = true;
_this._callMiddlewareMethod('entered', currentRoutes, request);
}
_this.isDOMReady = true;
_this._callMiddlewareMethod('updated', currentRoutes, request, response);
if (callback) {
callback(request, response);
}
}
};
}
/**
* Returns a new `Router` instance for the _uri_.
* See the Router api docs for details.
*
* app.route('/');
* // => new Router instance
*
* @param {String} uri
* @return {Router} for chaining
*
* @public
*/
}, {
key: 'route',
value: function route(uri) {
var router = new Router(uri);
this.routers.push(router);
return router;
}
/**
* Use the given middleware function or object, with optional _uri_.
* Default _uri_ is "/".
*
* // middleware function will be applied on path "/"
* app.use((req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/"
* app.use(new Middleware());
*
* @param {String} uri
* @param {Middleware|Function} middleware object or function
* @return {app} for chaining
*
* @public
*/
}, {
key: 'use',
value: function use() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var _toParameters = toParameters(args),
baseUri = _toParameters.baseUri,
router = _toParameters.router,
middleware = _toParameters.middleware;
if (router) {
router.baseUri = baseUri;
} else if (middleware) {
router = new Router(baseUri);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = HTTP_METHODS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var method = _step.value;
router[method.toLowerCase()](middleware);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
} else {
throw new TypeError('method takes at least a middleware or a router');
}
this.routers.push(router);
return this;
}
/**
* Gather routes from all routers filtered by _uri_ and HTTP _method_.
* See Router#routes() documentation for details.
*
* @private
*/
}, {
key: '_routes',
value: function _routes() {
var uri = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location.pathname + window.location.search;
var method = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'GET';
var currentRoutes = [];
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = this.routers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var router = _step2.value;
currentRoutes.push.apply(currentRoutes, toConsumableArray(router.routes(uri, method)));
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return currentRoutes;
}
/**
* Call `Middleware` method or middleware function on _currentRoutes_.
*
* @private
*/
}, {
key: '_callMiddlewareMethod',
value: function _callMiddlewareMethod(meth, currentRoutes, request, response) {
if (meth === 'exited') {
// currentRoutes, request, response params not needed
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this.routers[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var router = _step3.value;
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = router.visited()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var route = _step4.value;
if (route.middleware.exited) {
route.middleware.exited(route.visited);
route.visited = null;
}
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4.return) {
_iterator4.return();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
return;
}
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = currentRoutes[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var _route = _step5.value;
if (meth === 'updated') {
_route.visited = request;
}
if (_route.middleware[meth]) {
_route.middleware[meth](request, response);
if (_route.middleware.next && !_route.middleware.next()) {
break;
}
} else if (meth !== 'entered') {
// calls middleware method
var breakMiddlewareLoop = true;
var next = function next() {
breakMiddlewareLoop = false;
};
_route.middleware(request, response, next);
if (breakMiddlewareLoop) {
break;
}
}
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5.return) {
_iterator5.return();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
}
/**
* Make an ajax request. Manage History#pushState if history object set.
*
* @private
*/
}, {
key: '_fetch',
value: function _fetch(request, resolve, reject) {
var _this2 = this;
var method = request.method,
uri = request.uri,
headers = request.headers,
data = request.data,
history = request.history;
var httpMethodTransformer = this.get('http ' + method + ' transformer');
if (httpMethodTransformer) {
uri = httpMethodTransformer.uri ? httpMethodTransformer.uri({ uri: uri, headers: headers, data: data }) : uri;
headers = httpMethodTransformer.headers ? httpMethodTransformer.headers({ uri: uri, headers: headers, data: data }) : headers;
data = httpMethodTransformer.data ? httpMethodTransformer.data({ uri: uri, headers: headers, data: data }) : data;
}
// calls middleware exited method
this._callMiddlewareMethod('exited');
// gathers all routes impacted by the uri
var currentRoutes = this._routes(uri, method);
// calls middleware entered method
this._callMiddlewareMethod('entered', currentRoutes, request);
// invokes http request
this.settings.get('http requester').fetch(request, function (req, res) {
if (history) {
window.history.pushState({ request: req, response: res }, history.title, history.uri);
}
_this2._callMiddlewareMethod('updated', currentRoutes, req, res);
if (resolve) {
resolve(req, res);
}
}, function (req, res) {
_this2._callMiddlewareMethod('failed', currentRoutes, req, res);
if (reject) {
reject(req, res);
}
});
}
}]);
return Application;
}();
HTTP_METHODS.reduce(function (reqProto, method) {
/**
* Use the given middleware function or object, with optional _uri_ on
* HTTP methods: get, post, put, delete...
* Default _uri_ is "/".
*
* // middleware function will be applied on path "/"
* app.get((req, res, next) => {console.log('Hello')});
*
* // middleware object will be applied on path "/" and
* app.get(new Middleware());
*
* // get a setting value
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* @param {String} uri or setting
* @param {Middleware|Function} middleware object or function
* @return {app} for chaining
* @public
*/
var middlewareMethodName = method.toLowerCase();
reqProto[middlewareMethodName] = function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
var _toParameters2 = toParameters(args),
baseUri = _toParameters2.baseUri,
middleware = _toParameters2.middleware,
which = _toParameters2.which;
if (middlewareMethodName === 'get' && typeof which === 'string') {
return this.settings.get(which);
}
if (!middleware) {
throw new TypeError('method takes a middleware ' + (middlewareMethodName === 'get' ? 'or a string' : ''));
}
var router = new Router();
router[middlewareMethodName](baseUri, middleware);
this.routers.push(router);
return this;
};
/**
* Ajax request (get, post, put, delete...).
*
* // HTTP GET method
* httpGet('/route1');
*
* // HTTP GET method
* httpGet({uri: '/route1', data: {'p1': 'val1'});
* // uri invoked => /route1?p1=val1
*
* // HTTP GET method with browser history management
* httpGet({uri: '/api/users', history: {state: {foo: "bar"}, title: 'users page', uri: '/view/users'});
*
* Samples above can be applied on other HTTP methods.
*
* @param {String|Object} uri or object containing uri, http headers, data, history
* @param {Function} success callback
* @param {Function} failure callback
* @public
*/
var httpMethodName = 'http' + method.charAt(0).toUpperCase() + method.slice(1).toLowerCase();
reqProto[httpMethodName] = function (request, resolve, reject) {
var uri = request.uri,
headers = request.headers,
data = request.data,
history = request.history;
if (!uri) {
uri = request;
}
return this._fetch({
uri: uri,
method: method,
headers: headers,
data: data,
history: history
}, resolve, reject);
};
return reqProto;
}, Application.prototype);
function toParameters(args) {
var baseUri = void 0,
middleware = void 0,
router = void 0,
which = void 0;
if (args && args.length > 0) {
if (args.length === 1) {
var _args = slicedToArray(args, 1);
which = _args[0];
} else {
var _args2 = slicedToArray(args, 2);
baseUri = _args2[0];
which = _args2[1];
}
if (which instanceof Router) {
router = which;
} else if (which instanceof Middleware || typeof which === 'function') {
middleware = which;
}
}
return { baseUri: baseUri, middleware: middleware, router: router, which: which };
}
/**
* Module dependencies.
*/
/**
* Create a frontexpress application.
*
* @return {Function}
* @api public
*/
var frontexpress = function frontexpress() {
return new Application();
};
/**
* Expose Router, Middleware constructors.
*/
frontexpress.Router = function (baseUri) {
return new Router(baseUri);
};
frontexpress.Middleware = Middleware;
return frontexpress;
}());
|
KISSY.add('a/b', function () {
return 2;
}); |
angular.module('IX.controllers')
.controller('Room', function($scope, /*$rootScope, */$stateParams, SharedProperties/*, $ionicScrollDelegate, $timeout, Message, Chatstate, Profile*/) {
var sharedData = SharedProperties.sharedObject,
roomJid = $stateParams.jid;
$scope.getRoomName = function() {
return sharedData.rooms.object[roomJid]['@attributes'].name;
}
/*var sharedData = SharedProperties.sharedObject,
pausedTimeout = null,
inactiveTimeout = null,
pausedSeconds = 5000,
inactiveSeconds = 120000;
sharedData.activeChat = $scope.userJid;
sharedData.messagePool[$scope.userJid] = sharedData.messagePool[$scope.userJid] || {};
sharedData.messagePool[$scope.userJid].messages = sharedData.messagePool[$scope.userJid].messages || [];
$scope.chat = sharedData.messagePool[$scope.userJid];
$scope.user = sharedData.profiles[$scope.userJid];
$scope.myMessage = '';
$scope.getName = function(obj) {
return Profile.getName(obj);
}
$scope.sendMessage = function($event) {
if ($scope.myMessage.replace(/(\r\n|\n|\r|\s)/gm,'') == '') {
$scope.myMessage = '';
return;
}
Message.send({
jid: $scope.userJid,
message: $scope.myMessage
});
$scope.myMessage = '';
$timeout(function(){
$event.target.parentElement.querySelector('textarea').focus();
},0);
$timeout.cancel(inactiveTimeout);
inactiveTimeout = null;
$timeout.cancel(pausedTimeout);
pausedTimeout = null;
}
function sendInactive() {
Chatstate.sendState({
jid: $scope.userJid,
state: 'inactive'
});
$timeout.cancel(inactiveTimeout);
inactiveTimeout = null;
}
function sendPaused() {
Chatstate.sendState({
jid: $scope.userJid,
state: 'paused'
});
$timeout.cancel(inactiveTimeout);
inactiveTimeout = null;
$timeout.cancel(pausedTimeout);
pausedTimeout = null;
inactiveTimeout = $timeout(sendInactive, inactiveSeconds);
}
$scope.changeState = function() {
if (!pausedTimeout) {
Chatstate.sendState({
jid: $scope.userJid,
state: 'composing'
});
pausedTimeout = $timeout(sendPaused, pausedSeconds);
$timeout.cancel(inactiveTimeout);
inactiveTimeout = null;
} else {
$timeout.cancel(pausedTimeout);
pausedTimeout = null;
pausedTimeout = $timeout(sendPaused, pausedSeconds);
}
}
var DisableLoadListener = $scope.$on('$viewContentLoaded', function() {
DisableLoadListener();
$ionicScrollDelegate.scrollBottom(false);
});
$scope.$on('incomingMessage', function() {
$scope.chat = sharedData.messagePool[$scope.userJid];
$ionicScrollDelegate.scrollBottom(true);
});
sharedData.messagePool[$scope.userJid].unread = false;
Message.refreshUnread();
Chatstate.sendState({
jid: $scope.userJid,
state: 'active'
});
$scope.$on('$destroy', function() {
$timeout.cancel(inactiveTimeout);
inactiveTimeout = null;
$timeout.cancel(pausedTimeout);
pausedTimeout = null;
Chatstate.sendState({
jid: $scope.userJid,
state: 'inactive'
});
});
$timeout(function(){
document.querySelector('textarea').focus();
},0);*/
}); |
/**
* Module dependencies.
*/
var dosMarkdown = require('markdown');
var marked = require('marked');
var t = require('t');
var template = require('./template');
var View = require('view');
/**
* Expose MarkdownView.
*/
module.exports = MarkdownView;
/**
* DemocracyOS markdown guide MarkdownView
*
* @return {MarkdownView} `MarkdownView` instance.
* @api public
*/
function MarkdownView() {
if (!(this instanceof MarkdownView)) {
return new MarkdownView();
};
View.call(this, template, { marked: marked, dosMarkdown: dosMarkdown });
this.playground = this.find('textarea.playground');
this.result = this.find('.result');
}
/**
* Inherit from `View`
*/
View(MarkdownView)
/**
* Switch on events
*
* @api public
*/
MarkdownView.prototype.switchOn = function() {
this.bind('keyup', 'textarea.playground', 'onchange');
};
/**
* On text change
*
* @param {Object} data
* @api public
*/
MarkdownView.prototype.onchange = function(ev) {
var value = this.playground.value();
if (value != '') {
value = dosMarkdown(value);
} else {
value = t('markdown.playground.text');
}
this.result.html(value)
}; |
import { Point, ObservablePoint } from '../math';
import TransformBase from './TransformBase';
/**
* Generic class to deal with traditional 2D matrix transforms
* local transformation is calculated from position,scale,skew and rotation
*
* @class
* @extends PIXI.TransformBase
* @memberof PIXI
*/
export default class Transform extends TransformBase
{
/**
*
*/
constructor()
{
super();
/**
* The coordinate of the object relative to the local coordinates of the parent.
*
* @member {PIXI.Point}
*/
this.position = new Point(0, 0);
/**
* The scale factor of the object.
*
* @member {PIXI.Point}
*/
this.scale = new Point(1, 1);
/**
* The skew amount, on the x and y axis.
*
* @member {PIXI.ObservablePoint}
*/
this.skew = new ObservablePoint(this.updateSkew, this, 0, 0);
/**
* The pivot point of the displayObject that it rotates around.
*
* @member {PIXI.Point}
*/
this.pivot = new Point(0, 0);
/**
* The rotation value of the object, in radians
*
* @member {Number}
* @private
*/
this._rotation = 0;
this._cx = 1; // cos rotation + skewY;
this._sx = 0; // sin rotation + skewY;
this._cy = 0; // cos rotation + Math.PI/2 - skewX;
this._sy = 1; // sin rotation + Math.PI/2 - skewX;
}
/**
* Updates the skew values when the skew or rotation changes.
*
* @private
*/
updateSkew()
{
this._cx = Math.cos(this._rotation + this.skew._y);
this._sx = Math.sin(this._rotation + this.skew._y);
this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2
this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2
}
/**
* Updates only local matrix
*/
updateLocalTransform()
{
const lt = this.localTransform;
lt.a = this._cx * this.scale.x;
lt.b = this._sx * this.scale.x;
lt.c = this._cy * this.scale.y;
lt.d = this._sy * this.scale.y;
lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c));
lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d));
}
/**
* Updates the values of the object and applies the parent's transform.
*
* @param {PIXI.Transform} parentTransform - The transform of the parent of this object
*/
updateTransform(parentTransform)
{
const lt = this.localTransform;
lt.a = this._cx * this.scale.x;
lt.b = this._sx * this.scale.x;
lt.c = this._cy * this.scale.y;
lt.d = this._sy * this.scale.y;
lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c));
lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d));
// concat the parent matrix with the objects transform.
const pt = parentTransform.worldTransform;
const wt = this.worldTransform;
wt.a = (lt.a * pt.a) + (lt.b * pt.c);
wt.b = (lt.a * pt.b) + (lt.b * pt.d);
wt.c = (lt.c * pt.a) + (lt.d * pt.c);
wt.d = (lt.c * pt.b) + (lt.d * pt.d);
wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx;
wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty;
this._worldID ++;
}
/**
* Decomposes a matrix and sets the transforms properties based on it.
*
* @param {PIXI.Matrix} matrix - The matrix to decompose
*/
setFromMatrix(matrix)
{
matrix.decompose(this);
}
/**
* The rotation of the object in radians.
*
* @member {number}
*/
get rotation()
{
return this._rotation;
}
set rotation(value) // eslint-disable-line require-jsdoc
{
this._rotation = value;
this.updateSkew();
}
}
|
var assert = require('assert');
var quiche = require('../quiche');
describe('QR Infograph', function() {
var qr = quiche('qr');
qr.setLabel('https://github.com/ryanrolds/quiche');
qr.setWidth(100);
qr.setHeight(100);
var url = qr.getUrl();
it('should return a url', function() {
assert.equal(typeof url, 'string');
});
it('should be a qr', function() {
assert.ok(url.indexOf('cht=qr') > 0);
});
}); |
describe('jqLite', function() {
var scope, a, b, c;
beforeEach(module(provideLog));
beforeEach(function() {
a = jqLite('<div>A</div>')[0];
b = jqLite('<div>B</div>')[0];
c = jqLite('<div>C</div>')[0];
});
beforeEach(inject(function($rootScope) {
scope = $rootScope;
this.addMatchers({
toJqEqual: function(expected) {
var msg = "Unequal length";
this.message = function() {return msg;};
var value = this.actual && expected && this.actual.length == expected.length;
for (var i = 0; value && i < expected.length; i++) {
var actual = jqLite(this.actual[i])[0];
var expect = jqLite(expected[i])[0];
value = value && equals(expect, actual);
msg = "Not equal at index: " + i
+ " - Expected: " + expect
+ " - Actual: " + actual;
}
return value;
}
});
}));
afterEach(function() {
dealoc(a);
dealoc(b);
dealoc(c);
});
it('should be jqLite when jqLiteMode is on, otherwise jQuery', function() {
expect(jqLite).toBe(_jqLiteMode ? JQLite : _jQuery);
});
describe('construction', function() {
it('should allow construction with text node', function() {
var text = a.firstChild;
var selected = jqLite(text);
expect(selected.length).toEqual(1);
expect(selected[0]).toEqual(text);
});
it('should allow construction with html', function() {
var nodes = jqLite('<div>1</div><span>2</span>');
expect(nodes[0].parentNode).toBeDefined();
expect(nodes[0].parentNode.nodeType).toBe(11); /** Document Fragment **/;
expect(nodes[0].parentNode).toBe(nodes[1].parentNode);
expect(nodes.length).toEqual(2);
expect(nodes[0].innerHTML).toEqual('1');
expect(nodes[1].innerHTML).toEqual('2');
});
it('should allow creation of comment tags', function() {
var nodes = jqLite('<!-- foo -->');
expect(nodes.length).toBe(1);
expect(nodes[0].nodeType).toBe(8);
});
it('should allow creation of script tags', function() {
var nodes = jqLite('<script></script>');
expect(nodes.length).toBe(1);
expect(nodes[0].tagName.toUpperCase()).toBe('SCRIPT');
});
it('should wrap document fragment', function() {
var fragment = jqLite(document.createDocumentFragment());
expect(fragment.length).toBe(1);
expect(fragment[0].nodeType).toBe(11);
});
});
describe('inheritedData', function() {
it('should retrieve data attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('myData', 'abc');
expect(element.inheritedData('myData')).toBe('abc');
dealoc(element);
});
it('should walk up the dom to find data', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('myData', 'abc');
expect(deepChild.inheritedData('myData')).toBe('abc');
dealoc(element);
});
it('should return undefined when no data was found', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
expect(deepChild.inheritedData('myData')).toBeFalsy();
dealoc(element);
});
it('should work with the child html element instead if the current element is the document obj',
function() {
var item = {},
doc = jqLite(document),
html = doc.find('html');
html.data('item', item);
expect(doc.inheritedData('item')).toBe(item);
expect(html.inheritedData('item')).toBe(item);
dealoc(doc);
}
);
it('should return null values', function () {
var ul = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>'),
li = ul.find('li'),
b = li.find('b');
ul.data('foo', 'bar');
li.data('foo', null);
expect(b.inheritedData('foo')).toBe(null);
expect(li.inheritedData('foo')).toBe(null);
expect(ul.inheritedData('foo')).toBe('bar');
dealoc(ul);
});
});
describe('scope', function() {
it('should retrieve scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$scope', scope);
expect(element.scope()).toBe(scope);
dealoc(element);
});
it('should retrieve isolate scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$isolateScope', scope);
expect(element.isolateScope()).toBe(scope);
dealoc(element);
});
it('should retrieve scope attached to the html element if its requested on the document',
function() {
var doc = jqLite(document),
html = doc.find('html'),
scope = {};
html.data('$scope', scope);
expect(doc.scope()).toBe(scope);
expect(html.scope()).toBe(scope);
dealoc(doc);
});
it('should walk up the dom to find scope', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('$scope', scope);
expect(deepChild.scope()).toBe(scope);
dealoc(element);
});
it('should return undefined when no scope was found', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
expect(deepChild.scope()).toBeFalsy();
dealoc(element);
});
});
describe('isolateScope', function() {
it('should retrieve isolate scope attached to the current element', function() {
var element = jqLite('<i>foo</i>');
element.data('$isolateScope', scope);
expect(element.isolateScope()).toBe(scope);
dealoc(element);
});
it('should not walk up the dom to find scope', function() {
var element = jqLite('<ul><li><p><b>deep deep</b><p></li></ul>');
var deepChild = jqLite(element[0].getElementsByTagName('b')[0]);
element.data('$isolateScope', scope);
expect(deepChild.isolateScope()).toBeUndefined();
dealoc(element);
});
it('should return undefined when no scope was found', function() {
var element = jqLite('<div></div>');
expect(element.isolateScope()).toBeFalsy();
dealoc(element);
});
});
describe('injector', function() {
it('should retrieve injector attached to the current element or its parent', function() {
var template = jqLite('<div><span></span></div>'),
span = template.children().eq(0),
injector = angular.bootstrap(template);
expect(span.injector()).toBe(injector);
dealoc(template);
});
it('should retrieve injector attached to the html element if its requested on document',
function() {
var doc = jqLite(document),
html = doc.find('html'),
injector = {};
html.data('$injector', injector);
expect(doc.injector()).toBe(injector);
expect(html.injector()).toBe(injector);
dealoc(doc);
});
it('should do nothing with a noncompiled template', function() {
var template = jqLite('<div><span></span></div>');
expect(template.injector()).toBeUndefined();
dealoc(template);
});
});
describe('controller', function() {
it('should retrieve controller attached to the current element or its parent', function() {
var div = jqLite('<div><span></span></div>'),
span = div.find('span');
div.data('$ngControllerController', 'ngController');
span.data('$otherController', 'other');
expect(span.controller()).toBe('ngController');
expect(span.controller('ngController')).toBe('ngController');
expect(span.controller('other')).toBe('other');
expect(div.controller()).toBe('ngController');
expect(div.controller('ngController')).toBe('ngController');
expect(div.controller('other')).toBe(undefined);
dealoc(div);
});
});
describe('data', function() {
it('should set and get and remove data', function() {
var selected = jqLite([a, b, c]);
expect(selected.data('prop')).toBeUndefined();
expect(selected.data('prop', 'value')).toBe(selected);
expect(selected.data('prop')).toBe('value');
expect(jqLite(a).data('prop')).toBe('value');
expect(jqLite(b).data('prop')).toBe('value');
expect(jqLite(c).data('prop')).toBe('value');
jqLite(a).data('prop', 'new value');
expect(jqLite(a).data('prop')).toBe('new value');
expect(selected.data('prop')).toBe('new value');
expect(jqLite(b).data('prop')).toBe('value');
expect(jqLite(c).data('prop')).toBe('value');
expect(selected.removeData('prop')).toBe(selected);
expect(jqLite(a).data('prop')).toBeUndefined();
expect(jqLite(b).data('prop')).toBeUndefined();
expect(jqLite(c).data('prop')).toBeUndefined();
});
it('should only remove the specified value when providing a property name to removeData', function () {
var selected = jqLite(a);
expect(selected.data('prop1')).toBeUndefined();
selected.data('prop1', 'value');
selected.data('prop2', 'doublevalue');
expect(selected.data('prop1')).toBe('value');
expect(selected.data('prop2')).toBe('doublevalue');
selected.removeData('prop1');
expect(selected.data('prop1')).toBeUndefined();
expect(selected.data('prop2')).toBe('doublevalue');
selected.removeData('prop2');
});
it('should emit $destroy event if element removed via remove()', function() {
var log = '';
var element = jqLite(a);
element.on('$destroy', function() {log+= 'destroy;';});
element.remove();
expect(log).toEqual('destroy;');
});
it('should emit $destroy event if an element is removed via html()', inject(function(log) {
var element = jqLite('<div><span>x</span></div>');
element.find('span').on('$destroy', log.fn('destroyed'));
element.html('');
expect(element.html()).toBe('');
expect(log).toEqual('destroyed');
}));
it('should retrieve all data if called without params', function() {
var element = jqLite(a);
expect(element.data()).toEqual({});
element.data('foo', 'bar');
expect(element.data()).toEqual({foo: 'bar'});
element.data().baz = 'xxx';
expect(element.data()).toEqual({foo: 'bar', baz: 'xxx'});
});
it('should create a new data object if called without args', function() {
var element = jqLite(a),
data = element.data();
expect(data).toEqual({});
element.data('foo', 'bar');
expect(data).toEqual({foo: 'bar'});
});
it('should create a new data object if called with a single object arg', function() {
var element = jqLite(a),
newData = {foo: 'bar'};
element.data(newData);
expect(element.data()).toEqual({foo: 'bar'});
expect(element.data()).not.toBe(newData); // create a copy
});
it('should merge existing data object with a new one if called with a single object arg',
function() {
var element = jqLite(a);
element.data('existing', 'val');
expect(element.data()).toEqual({existing: 'val'});
var oldData = element.data(),
newData = {meLike: 'turtles', 'youLike': 'carrots'};
expect(element.data(newData)).toBe(element);
expect(element.data()).toEqual({meLike: 'turtles', youLike: 'carrots', existing: 'val'});
expect(element.data()).toBe(oldData); // merge into the old object
});
describe('data cleanup', function() {
it('should remove data on element removal', function() {
var div = jqLite('<div><span>text</span></div>'),
span = div.find('span');
span.data('name', 'angular');
span.remove();
expect(span.data('name')).toBeUndefined();
});
it('should remove event listeners on element removal', function() {
var div = jqLite('<div><span>text</span></div>'),
span = div.find('span'),
log = '';
span.on('click', function() { log+= 'click;'});
browserTrigger(span);
expect(log).toEqual('click;');
span.remove();
browserTrigger(span);
expect(log).toEqual('click;');
});
});
});
describe('attr', function() {
it('should read write and remove attr', function() {
var selector = jqLite([a, b]);
expect(selector.attr('prop', 'value')).toEqual(selector);
expect(jqLite(a).attr('prop')).toEqual('value');
expect(jqLite(b).attr('prop')).toEqual('value');
expect(selector.attr({'prop': 'new value'})).toEqual(selector);
expect(jqLite(a).attr('prop')).toEqual('new value');
expect(jqLite(b).attr('prop')).toEqual('new value');
jqLite(b).attr({'prop': 'new value 2'});
expect(jqLite(selector).attr('prop')).toEqual('new value');
expect(jqLite(b).attr('prop')).toEqual('new value 2');
selector.removeAttr('prop');
expect(jqLite(a).attr('prop')).toBeFalsy();
expect(jqLite(b).attr('prop')).toBeFalsy();
});
it('should read boolean attributes as strings', function() {
var select = jqLite('<select>');
expect(select.attr('multiple')).toBeUndefined();
expect(jqLite('<select multiple>').attr('multiple')).toBe('multiple');
expect(jqLite('<select multiple="">').attr('multiple')).toBe('multiple');
expect(jqLite('<select multiple="x">').attr('multiple')).toBe('multiple');
});
it('should add/remove boolean attributes', function() {
var select = jqLite('<select>');
select.attr('multiple', false);
expect(select.attr('multiple')).toBeUndefined();
select.attr('multiple', true);
expect(select.attr('multiple')).toBe('multiple');
});
it('should normalize the case of boolean attributes', function() {
var input = jqLite('<input readonly>');
expect(input.attr('readonly')).toBe('readonly');
expect(input.attr('readOnly')).toBe('readonly');
expect(input.attr('READONLY')).toBe('readonly');
input.attr('readonly', false);
// attr('readonly') fails in jQuery 1.6.4, so we have to bypass it
//expect(input.attr('readOnly')).toBeUndefined();
//expect(input.attr('readonly')).toBeUndefined();
if (msie < 9) {
expect(input[0].getAttribute('readonly')).toBe('');
} else {
expect(input[0].getAttribute('readonly')).toBe(null);
}
//expect('readOnly' in input[0].attributes).toBe(false);
input.attr('readOnly', 'READonly');
expect(input.attr('readonly')).toBe('readonly');
expect(input.attr('readOnly')).toBe('readonly');
});
it('should return undefined for non-existing attributes', function() {
var elm = jqLite('<div class="any">a</div>');
expect(elm.attr('non-existing')).toBeUndefined();
});
it('should return undefined for non-existing attributes on input', function() {
var elm = jqLite('<input>');
expect(elm.attr('readonly')).toBeUndefined();
expect(elm.attr('readOnly')).toBeUndefined();
expect(elm.attr('disabled')).toBeUndefined();
});
});
describe('prop', function() {
it('should read element property', function() {
var elm = jqLite('<div class="foo">a</div>');
expect(elm.prop('className')).toBe('foo');
});
it('should set element property to a value', function() {
var elm = jqLite('<div class="foo">a</div>');
elm.prop('className', 'bar');
expect(elm[0].className).toBe('bar');
expect(elm.prop('className')).toBe('bar');
});
it('should set boolean element property', function() {
var elm = jqLite('<input type="checkbox">');
expect(elm.prop('checked')).toBe(false);
elm.prop('checked', true);
expect(elm.prop('checked')).toBe(true);
elm.prop('checked', '');
expect(elm.prop('checked')).toBe(false);
elm.prop('checked', 'lala');
expect(elm.prop('checked')).toBe(true);
elm.prop('checked', null);
expect(elm.prop('checked')).toBe(false);
});
});
describe('class', function() {
it('should properly do with SVG elements', function() {
// this is a jqLite & SVG only test (jquery doesn't behave this way right now, which is a bug)
if (!window.SVGElement || !_jqLiteMode) return;
var svg = jqLite('<svg><rect></rect></svg>');
var rect = svg.children();
expect(rect.hasClass('foo-class')).toBe(false);
rect.addClass('foo-class');
expect(rect.hasClass('foo-class')).toBe(true);
rect.removeClass('foo-class');
expect(rect.hasClass('foo-class')).toBe(false);
});
it('should ignore comment elements', function() {
var comment = jqLite(document.createComment('something'));
comment.addClass('whatever');
comment.hasClass('whatever');
comment.toggleClass('whatever');
comment.removeClass('whatever');
});
describe('hasClass', function() {
it('should check class', function() {
var selector = jqLite([a, b]);
expect(selector.hasClass('abc')).toEqual(false);
});
it('should make sure that partial class is not checked as a subset', function() {
var selector = jqLite([a, b]);
selector.addClass('a');
selector.addClass('b');
selector.addClass('c');
expect(selector.addClass('abc')).toEqual(selector);
expect(selector.removeClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
expect(jqLite(a).hasClass('a')).toEqual(true);
expect(jqLite(a).hasClass('b')).toEqual(true);
expect(jqLite(a).hasClass('c')).toEqual(true);
});
});
describe('addClass', function() {
it('should allow adding of class', function() {
var selector = jqLite([a, b]);
expect(selector.addClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
});
it('should ignore falsy values', function() {
var jqA = jqLite(a);
expect(jqA[0].className).toBe('');
jqA.addClass(undefined);
expect(jqA[0].className).toBe('');
jqA.addClass(null);
expect(jqA[0].className).toBe('');
jqA.addClass(false);
expect(jqA[0].className).toBe('');
});
it('should allow multiple classes to be added in a single string', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
jqA.addClass('foo bar baz');
expect(a.className).toBe('foo bar baz');
});
it('should not add duplicate classes', function() {
var jqA = jqLite(a);
expect(a.className).toBe('');
a.className = 'foo';
jqA.addClass('foo');
expect(a.className).toBe('foo');
jqA.addClass('bar foo baz');
expect(a.className).toBe('foo bar baz');
});
});
describe('toggleClass', function() {
it('should allow toggling of class', function() {
var selector = jqLite([a, b]);
expect(selector.toggleClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
expect(selector.toggleClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
expect(selector.toggleClass('abc'), true).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(true);
expect(jqLite(b).hasClass('abc')).toEqual(true);
expect(selector.toggleClass('abc'), false).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
});
});
describe('removeClass', function() {
it('should allow removal of class', function() {
var selector = jqLite([a, b]);
expect(selector.addClass('abc')).toEqual(selector);
expect(selector.removeClass('abc')).toEqual(selector);
expect(jqLite(a).hasClass('abc')).toEqual(false);
expect(jqLite(b).hasClass('abc')).toEqual(false);
});
it('should correctly remove middle class', function() {
var element = jqLite('<div class="foo bar baz"></div>');
expect(element.hasClass('bar')).toBe(true);
element.removeClass('bar');
expect(element.hasClass('foo')).toBe(true);
expect(element.hasClass('bar')).toBe(false);
expect(element.hasClass('baz')).toBe(true);
});
it('should remove multiple classes specified as one string', function() {
var jqA = jqLite(a);
a.className = 'foo bar baz';
jqA.removeClass('foo baz noexistent');
expect(a.className).toBe('bar');
});
});
});
describe('css', function() {
it('should set and read css', function() {
var selector = jqLite([a, b]);
expect(selector.css('margin', '1px')).toEqual(selector);
expect(jqLite(a).css('margin')).toEqual('1px');
expect(jqLite(b).css('margin')).toEqual('1px');
expect(selector.css({'margin': '2px'})).toEqual(selector);
expect(jqLite(a).css('margin')).toEqual('2px');
expect(jqLite(b).css('margin')).toEqual('2px');
jqLite(b).css({'margin': '3px'});
expect(jqLite(selector).css('margin')).toEqual('2px');
expect(jqLite(a).css('margin')).toEqual('2px');
expect(jqLite(b).css('margin')).toEqual('3px');
selector.css('margin', '');
if (msie <= 8) {
expect(jqLite(a).css('margin')).toBe('auto');
expect(jqLite(b).css('margin')).toBe('auto');
} else {
expect(jqLite(a).css('margin')).toBeFalsy();
expect(jqLite(b).css('margin')).toBeFalsy();
}
});
it('should set a bunch of css properties specified via an object', function() {
if (msie <= 8) {
expect(jqLite(a).css('margin')).toBe('auto');
expect(jqLite(a).css('padding')).toBe('0px');
expect(jqLite(a).css('border')).toBeUndefined();
} else {
expect(jqLite(a).css('margin')).toBeFalsy();
expect(jqLite(a).css('padding')).toBeFalsy();
expect(jqLite(a).css('border')).toBeFalsy();
}
jqLite(a).css({'margin': '1px', 'padding': '2px', 'border': ''});
expect(jqLite(a).css('margin')).toBe('1px');
expect(jqLite(a).css('padding')).toBe('2px');
expect(jqLite(a).css('border')).toBeFalsy();
});
it('should correctly handle dash-separated and camelCased properties', function() {
var jqA = jqLite(a);
expect(jqA.css('z-index')).toBeOneOf('', 'auto');
expect(jqA.css('zIndex')).toBeOneOf('', 'auto');
jqA.css({'zIndex':5});
expect(jqA.css('z-index')).toBeOneOf('5', 5);
expect(jqA.css('zIndex')).toBeOneOf('5', 5);
jqA.css({'z-index':7});
expect(jqA.css('z-index')).toBeOneOf('7', 7);
expect(jqA.css('zIndex')).toBeOneOf('7', 7);
});
});
describe('text', function() {
it('should return null on empty', function() {
expect(jqLite().length).toEqual(0);
expect(jqLite().text()).toEqual('');
});
it('should read/write value', function() {
var element = jqLite('<div>ab</div><span>c</span>');
expect(element.length).toEqual(2);
expect(element[0].innerHTML).toEqual('ab');
expect(element[1].innerHTML).toEqual('c');
expect(element.text()).toEqual('abc');
expect(element.text('xyz') == element).toBeTruthy();
expect(element.text()).toEqual('xyzxyz');
});
});
describe('val', function() {
it('should read, write value', function() {
var input = jqLite('<input type="text"/>');
expect(input.val('abc')).toEqual(input);
expect(input[0].value).toEqual('abc');
expect(input.val()).toEqual('abc');
});
it('should get an array of selected elements from a multi select', function () {
expect(jqLite(
'<select multiple>' +
'<option selected>test 1</option>' +
'<option selected>test 2</option>' +
'</select>').val()).toEqual(['test 1', 'test 2']);
expect(jqLite(
'<select multiple>' +
'<option selected>test 1</option>' +
'<option>test 2</option>' +
'</select>').val()).toEqual(['test 1']);
expect(jqLite(
'<select multiple>' +
'<option>test 1</option>' +
'<option>test 2</option>' +
'</select>').val()).toEqual(null);
});
});
describe('html', function() {
it('should return null on empty', function() {
expect(jqLite().length).toEqual(0);
expect(jqLite().html()).toEqual(null);
});
it('should read/write value', function() {
var element = jqLite('<div>abc</div>');
expect(element.length).toEqual(1);
expect(element[0].innerHTML).toEqual('abc');
expect(element.html()).toEqual('abc');
expect(element.html('xyz') == element).toBeTruthy();
expect(element.html()).toEqual('xyz');
});
});
describe('on', function() {
it('should bind to window on hashchange', function() {
if (jqLite.fn) return; // don't run in jQuery
var eventFn;
var window = {
document: {},
location: {},
alert: noop,
setInterval: noop,
length:10, // pretend you are an array
addEventListener: function(type, fn){
expect(type).toEqual('hashchange');
eventFn = fn;
},
removeEventListener: noop,
attachEvent: function(type, fn){
expect(type).toEqual('onhashchange');
eventFn = fn;
},
detachEvent: noop
};
var log;
var jWindow = jqLite(window).on('hashchange', function() {
log = 'works!';
});
eventFn({type: 'hashchange'});
expect(log).toEqual('works!');
dealoc(jWindow);
});
it('should bind to all elements and return functions', function() {
var selected = jqLite([a, b]);
var log = '';
expect(selected.on('click', function() {
log += 'click on: ' + jqLite(this).text() + ';';
})).toEqual(selected);
browserTrigger(a, 'click');
expect(log).toEqual('click on: A;');
browserTrigger(b, 'click');
expect(log).toEqual('click on: A;click on: B;');
});
it('should bind to all events separated by space', function() {
var elm = jqLite(a),
callback = jasmine.createSpy('callback');
elm.on('click keypress', callback);
elm.on('click', callback);
browserTrigger(a, 'click');
expect(callback).toHaveBeenCalled();
expect(callback.callCount).toBe(2);
callback.reset();
browserTrigger(a, 'keypress');
expect(callback).toHaveBeenCalled();
expect(callback.callCount).toBe(1);
});
it('should set event.target on IE', function() {
var elm = jqLite(a);
elm.on('click', function(event) {
expect(event.target).toBe(a);
});
browserTrigger(a, 'click');
});
it('should have event.isDefaultPrevented method', function() {
jqLite(a).on('click', function(e) {
expect(function() {
expect(e.isDefaultPrevented()).toBe(false);
e.preventDefault();
expect(e.isDefaultPrevented()).toBe(true);
}).not.toThrow();
});
browserTrigger(a, 'click');
});
describe('mouseenter-mouseleave', function() {
var root, parent, sibling, child, log;
beforeEach(function() {
log = '';
root = jqLite('<div>root<p>parent<span>child</span></p><ul></ul></div>');
parent = root.find('p');
sibling = root.find('ul');
child = parent.find('span');
parent.on('mouseenter', function() { log += 'parentEnter;'; });
parent.on('mouseleave', function() { log += 'parentLeave;'; });
child.on('mouseenter', function() { log += 'childEnter;'; });
child.on('mouseleave', function() { log += 'childLeave;'; });
});
afterEach(function() {
dealoc(root);
});
it('should fire mouseenter when coming from outside the browser window', function() {
if (window.jQuery) return;
var browserMoveTrigger = function(from, to){
var fireEvent = function(type, element, relatedTarget){
var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
if (msie < 9){
var evnt = document.createEventObject();
evnt.srcElement = element;
evnt.relatedTarget = relatedTarget;
element.fireEvent('on' + type, evnt);
return;
};
var evnt = document.createEvent('MouseEvents'),
originalPreventDefault = evnt.preventDefault,
appWindow = window,
fakeProcessDefault = true,
finalProcessDefault;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
var x = 0, y = 0;
evnt.initMouseEvent(type, true, true, window, 0, x, y, x, y, false, false,
false, false, 0, relatedTarget);
element.dispatchEvent(evnt);
};
fireEvent('mouseout', from[0], to[0]);
fireEvent('mouseover', to[0], from[0]);
};
browserMoveTrigger(root, parent);
expect(log).toEqual('parentEnter;');
browserMoveTrigger(parent, child);
expect(log).toEqual('parentEnter;childEnter;');
browserMoveTrigger(child, parent);
expect(log).toEqual('parentEnter;childEnter;childLeave;');
browserMoveTrigger(parent, root);
expect(log).toEqual('parentEnter;childEnter;childLeave;parentLeave;');
});
});
// Only run this test for jqLite and not normal jQuery
if ( _jqLiteMode ) {
it('should throw an error if eventData or a selector is passed', function() {
var elm = jqLite(a),
anObj = {},
aString = '',
aValue = 45,
callback = function() {};
expect(function() {
elm.on('click', anObj, callback);
}).toThrowMinErr('jqLite', 'onargs');
expect(function() {
elm.on('click', null, aString, callback);
}).toThrowMinErr('jqLite', 'onargs');
expect(function() {
elm.on('click', aValue, callback);
}).toThrowMinErr('jqLite', 'onargs');
});
}
});
describe('off', function() {
it('should do nothing when no listener was registered with bound', function() {
var aElem = jqLite(a);
aElem.off();
aElem.off('click');
aElem.off('click', function() {});
});
it('should do nothing when a specific listener was not registered', function () {
var aElem = jqLite(a);
aElem.on('click', function() {});
aElem.off('mouseenter', function() {});
});
it('should deregister all listeners', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off();
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister listeners for specific type', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off('click');
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
mouseoverSpy.reset();
aElem.off('mouseover');
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister all listeners for types separated by spaces', function() {
var aElem = jqLite(a),
clickSpy = jasmine.createSpy('click'),
mouseoverSpy = jasmine.createSpy('mouseover');
aElem.on('click', clickSpy);
aElem.on('mouseover', mouseoverSpy);
browserTrigger(a, 'click');
expect(clickSpy).toHaveBeenCalledOnce();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).toHaveBeenCalledOnce();
clickSpy.reset();
mouseoverSpy.reset();
aElem.off('click mouseover');
browserTrigger(a, 'click');
expect(clickSpy).not.toHaveBeenCalled();
browserTrigger(a, 'mouseover');
expect(mouseoverSpy).not.toHaveBeenCalled();
});
it('should deregister specific listener', function() {
var aElem = jqLite(a),
clickSpy1 = jasmine.createSpy('click1'),
clickSpy2 = jasmine.createSpy('click2');
aElem.on('click', clickSpy1);
aElem.on('click', clickSpy2);
browserTrigger(a, 'click');
expect(clickSpy1).toHaveBeenCalledOnce();
expect(clickSpy2).toHaveBeenCalledOnce();
clickSpy1.reset();
clickSpy2.reset();
aElem.off('click', clickSpy1);
browserTrigger(a, 'click');
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).toHaveBeenCalledOnce();
clickSpy2.reset();
aElem.off('click', clickSpy2);
browserTrigger(a, 'click');
expect(clickSpy2).not.toHaveBeenCalled();
});
it('should deregister specific listener for multiple types separated by spaces', function() {
var aElem = jqLite(a),
masterSpy = jasmine.createSpy('master'),
extraSpy = jasmine.createSpy('extra');
aElem.on('click', masterSpy);
aElem.on('click', extraSpy);
aElem.on('mouseover', masterSpy);
browserTrigger(a, 'click');
browserTrigger(a, 'mouseover');
expect(masterSpy.callCount).toBe(2);
expect(extraSpy).toHaveBeenCalledOnce();
masterSpy.reset();
extraSpy.reset();
aElem.off('click mouseover', masterSpy);
browserTrigger(a, 'click');
browserTrigger(a, 'mouseover');
expect(masterSpy).not.toHaveBeenCalled();
expect(extraSpy).toHaveBeenCalledOnce();
});
// Only run this test for jqLite and not normal jQuery
if ( _jqLiteMode ) {
it('should throw an error if a selector is passed', function () {
var aElem = jqLite(a);
aElem.on('click', noop);
expect(function () {
aElem.off('click', noop, '.test');
}).toThrowMatching(/\[jqLite:offargs\]/);
});
}
});
describe('replaceWith', function() {
it('should replaceWith', function() {
var root = jqLite('<div>').html('before-<div></div>after');
var div = root.find('div');
expect(div.replaceWith('<span>span-</span><b>bold-</b>')).toEqual(div);
expect(root.text()).toEqual('before-span-bold-after');
});
it('should replaceWith text', function() {
var root = jqLite('<div>').html('before-<div></div>after');
var div = root.find('div');
expect(div.replaceWith('text-')).toEqual(div);
expect(root.text()).toEqual('before-text-after');
});
});
describe('children', function() {
it('should only select element nodes', function() {
var root = jqLite('<div><!-- some comment -->before-<div></div>after-<span></span>');
var div = root.find('div');
var span = root.find('span');
expect(root.children()).toJqEqual([div, span]);
});
});
describe('contents', function() {
it('should select all types child nodes', function() {
var root = jqLite('<div><!-- some comment -->before-<div></div>after-<span></span></div>');
var contents = root.contents();
expect(contents.length).toEqual(5);
expect(contents[0].data).toEqual(' some comment ');
expect(contents[1].data).toEqual('before-');
});
});
describe('append', function() {
it('should append', function() {
var root = jqLite('<div>');
expect(root.append('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>');
});
it('should append text', function() {
var root = jqLite('<div>');
expect(root.append('text')).toEqual(root);
expect(root.html()).toEqual('text');
});
it('should append to document fragment', function() {
var root = jqLite(document.createDocumentFragment());
expect(root.append('<p>foo</p>')).toBe(root);
expect(root.children().length).toBe(1);
});
it('should not append anything if parent node is not of type element or docfrag', function() {
var root = jqLite('<p>some text node</p>').contents();
expect(root.append('<p>foo</p>')).toBe(root);
expect(root.children().length).toBe(0);
});
});
describe('wrap', function() {
it('should wrap text node', function() {
var root = jqLite('<div>A<a>B</a>C</div>');
var text = root.contents();
expect(text.wrap("<span>")[0]).toBe(text[0]);
expect(root.find('span').text()).toEqual('A<a>B</a>C');
});
it('should wrap free text node', function() {
var root = jqLite('<div>A<a>B</a>C</div>');
var text = root.contents();
text.remove();
expect(root.text()).toBe('');
text.wrap("<span>");
expect(text.parent().text()).toEqual('A<a>B</a>C');
});
});
describe('prepend', function() {
it('should prepend to empty', function() {
var root = jqLite('<div>');
expect(root.prepend('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>');
});
it('should prepend to content', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend('<span>abc</span>')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('<span>abc</span>text');
});
it('should prepend text to content', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend('abc')).toEqual(root);
expect(root.html().toLowerCase()).toEqual('abctext');
});
it('should prepend array to empty in the right order', function() {
var root = jqLite('<div>');
expect(root.prepend([a, b, c])).toBe(root);
expect(sortedHtml(root)).
toBe('<div><div>A</div><div>B</div><div>C</div></div>');
});
it('should prepend array to content in the right order', function() {
var root = jqLite('<div>text</div>');
expect(root.prepend([a, b, c])).toBe(root);
expect(sortedHtml(root)).
toBe('<div><div>A</div><div>B</div><div>C</div>text</div>');
});
});
describe('remove', function() {
it('should remove', function() {
var root = jqLite('<div><span>abc</span></div>');
var span = root.find('span');
expect(span.remove()).toEqual(span);
expect(root.html()).toEqual('');
});
});
describe('after', function() {
it('should after', function() {
var root = jqLite('<div><span></span></div>');
var span = root.find('span');
expect(span.after('<i></i><b></b>')).toEqual(span);
expect(root.html().toLowerCase()).toEqual('<span></span><i></i><b></b>');
});
it('should allow taking text', function() {
var root = jqLite('<div><span></span></div>');
var span = root.find('span');
span.after('abc');
expect(root.html().toLowerCase()).toEqual('<span></span>abc');
});
});
describe('parent', function() {
it('should return parent or an empty set when no parent', function() {
var parent = jqLite('<div><p>abc</p></div>'),
child = parent.find('p');
expect(parent.parent()).toBeTruthy();
expect(parent.parent().length).toEqual(0);
expect(child.parent().length).toBe(1);
expect(child.parent()[0]).toBe(parent[0]);
});
it('should return empty set when no parent', function() {
var element = jqLite('<div>abc</div>');
expect(element.parent()).toBeTruthy();
expect(element.parent().length).toEqual(0);
});
it('should return empty jqLite object when parent is a document fragment', function() {
//this is quite unfortunate but jQuery 1.5.1 behaves this way
var fragment = document.createDocumentFragment(),
child = jqLite('<p>foo</p>');
fragment.appendChild(child[0]);
expect(child[0].parentNode).toBe(fragment);
expect(child.parent().length).toBe(0);
});
});
describe('next', function() {
it('should return next sibling', function() {
var element = jqLite('<div><b>b</b><i>i</i></div>');
var b = element.find('b');
var i = element.find('i');
expect(b.next()).toJqEqual([i]);
});
it('should ignore non-element siblings', function() {
var element = jqLite('<div><b>b</b>TextNode<!-- comment node --><i>i</i></div>');
var b = element.find('b');
var i = element.find('i');
expect(b.next()).toJqEqual([i]);
});
});
describe('find', function() {
it('should find child by name', function() {
var root = jqLite('<div><div>text</div></div>');
var innerDiv = root.find('div');
expect(innerDiv.length).toEqual(1);
expect(innerDiv.html()).toEqual('text');
});
});
describe('eq', function() {
it('should select the nth element ', function() {
var element = jqLite('<div><span>aa</span></div><div><span>bb</span></div>');
expect(element.find('span').eq(0).html()).toBe('aa');
expect(element.find('span').eq(-1).html()).toBe('bb');
expect(element.find('span').eq(20).length).toBe(0);
});
});
describe('triggerHandler', function() {
it('should trigger all registered handlers for an event', function() {
var element = jqLite('<span>poke</span>'),
pokeSpy = jasmine.createSpy('poke'),
clickSpy1 = jasmine.createSpy('clickSpy1'),
clickSpy2 = jasmine.createSpy('clickSpy2');
element.on('poke', pokeSpy);
element.on('click', clickSpy1);
element.on('click', clickSpy2);
expect(pokeSpy).not.toHaveBeenCalled();
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).not.toHaveBeenCalled();
element.triggerHandler('poke');
expect(pokeSpy).toHaveBeenCalledOnce();
expect(clickSpy1).not.toHaveBeenCalled();
expect(clickSpy2).not.toHaveBeenCalled();
element.triggerHandler('click');
expect(clickSpy1).toHaveBeenCalledOnce();
expect(clickSpy2).toHaveBeenCalledOnce();
});
it('should pass in a dummy event', function() {
// we need the event to have at least preventDefault because angular will call it on
// all anchors with no href automatically
var element = jqLite('<a>poke</a>'),
pokeSpy = jasmine.createSpy('poke'),
event;
element.on('click', pokeSpy);
element.triggerHandler('click');
event = pokeSpy.mostRecentCall.args[0];
expect(event.preventDefault).toBeDefined();
});
it('should pass data as an additional argument', function() {
var element = jqLite('<a>poke</a>'),
pokeSpy = jasmine.createSpy('poke'),
data;
element.on('click', pokeSpy);
element.triggerHandler('click', [{hello: "world"}]);
data = pokeSpy.mostRecentCall.args[1];
expect(data.hello).toBe("world");
});
});
describe('camelCase', function() {
it('should leave non-dashed strings alone', function() {
expect(camelCase('foo')).toBe('foo');
expect(camelCase('')).toBe('');
expect(camelCase('fooBar')).toBe('fooBar');
});
it('should covert dash-separated strings to camelCase', function() {
expect(camelCase('foo-bar')).toBe('fooBar');
expect(camelCase('foo-bar-baz')).toBe('fooBarBaz');
expect(camelCase('foo:bar_baz')).toBe('fooBarBaz');
});
it('should covert browser specific css properties', function() {
expect(camelCase('-moz-foo-bar')).toBe('MozFooBar');
expect(camelCase('-webkit-foo-bar')).toBe('webkitFooBar');
expect(camelCase('-webkit-foo-bar')).toBe('webkitFooBar');
});
});
});
|
//
// Copyright (c) Microsoft and contributors. 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.
//
var ChunkStream = require('./chunkStream');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
/**
* Chunk stream
* 1. Calculate md5
* 2. Track reading offset
* 3. Work with customize memory allocator
* 4. Buffer data from stream.
* @param {object} options stream.Readable options
*/
function ChunkStreamWithStream(stream, options) {
ChunkStream.call(this, options);
stream.pause(); // Pause stream and wait for data listener. It's useful for node v0.6 and v0.8
this._stream = stream;
this._stream.on('end', this.end.bind(this)); // Should catch the end event for node v0.6 and v0.8
}
util.inherits(ChunkStreamWithStream, ChunkStream);
/**
* Add event listener
*/
ChunkStreamWithStream.prototype.on = function(event, listener) {
if(event === 'end' && this._streamEnded) {
listener(); //Directly call the end event when stream already ended
} else {
EventEmitter.prototype.on.call(this, event, listener);
}
if (event === 'data') {
if (!this._isStreamOpened) {
this._isStreamOpened = true;
this._stream.on('data', this._buildChunk.bind(this));
}
if (this._paused === undefined) {
this._stream.resume();
}
}
};
/**
* Pause chunk stream
*/
ChunkStreamWithStream.prototype.pause = function () {
ChunkStream.prototype.pause.call(this);
this._stream.pause();
};
/**
* Resume read stream
*/
ChunkStreamWithStream.prototype.resume = function() {
ChunkStream.prototype.resume.call(this);
this._stream.resume();
};
module.exports = ChunkStreamWithStream; |
var util = require('util')
, utils = require('utils')
, underscore = require('underscore')
, debug = require('debug')('cleverstack:utils:model');
module.exports = function emitBeforeEvent(eventName, modelDataOrFindOptions, queryOptions, callback) {
var listeners = this.listeners(eventName).length
, callbacks = 0
, errors = [];
if (listeners < 1) {
return callback(null);
}
if (debug.enabled) {
debug(util.format('Running hook, emitting %s %s(%s) on %s listeners...', this.modelName, eventName, utils.model.helpers.debugInspect(modelDataOrFindOptions), listeners));
}
this.emit(eventName, modelDataOrFindOptions, queryOptions, function(err, updatedModelDataOrFindOptions) {
if (err) {
errors.push(err);
} else if (updatedModelDataOrFindOptions !== undefined) {
underscore.extend(modelDataOrFindOptions, updatedModelDataOrFindOptions);
}
if (++callbacks === listeners) {
callback(errors.length ? errors.shift() : null);
}
});
}; |
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.
var common = require('./common.js');
var classCategory = 'class';
var namespaceCategory = 'ns';
exports.transform = function (model) {
handleItem(model, model._gitContribute, model._gitUrlPattern);
if (model.children) {
normalizeChildren(model.children).forEach(function (item) {
handleItem(item, model._gitContribute, model._gitUrlPattern);
});
};
if (model.type) {
switch (model.type.toLowerCase()) {
case 'namespace':
model.isNamespace = true;
if (model.children) groupChildren(model, namespaceCategory);
break;
case 'class':
case 'interface':
case 'struct':
case 'delegate':
model.isClass = true;
if (model.children) groupChildren(model, classCategory);
model[getTypePropertyName(model.type)] = true;
break;
case 'enum':
model.isEnum = true;
if (model.children) groupChildren(model, classCategory);
model[getTypePropertyName(model.type)] = true;
break;
default:
break;
}
}
model._disableToc = model._disableToc || !model._tocPath || (model._navPath === model._tocPath);
return { item: model };
}
exports.getBookmarks = function (model, ignoreChildren) {
if (!model || !model.type || model.type.toLowerCase() === "namespace") return null;
var bookmarks = {};
if (typeof ignoreChildren == 'undefined' || ignoreChildren === false) {
if (model.children) {
normalizeChildren(model.children).forEach(function (item) {
bookmarks[item.uid] = common.getHtmlId(item.uid);
if (item.overload && item.overload.uid) {
bookmarks[item.overload.uid] = common.getHtmlId(item.overload.uid);
}
});
}
}
// Reference's first level bookmark should have no anchor
bookmarks[model.uid] = "";
return bookmarks;
}
function handleItem(vm, gitContribute, gitUrlPattern) {
// get contribution information
vm.docurl = common.getImproveTheDocHref(vm, gitContribute, gitUrlPattern);
vm.sourceurl = common.getViewSourceHref(vm, null, gitUrlPattern);
// set to null incase mustache looks up
vm.summary = vm.summary || null;
vm.remarks = vm.remarks || null;
vm.conceptual = vm.conceptual || null;
vm.syntax = vm.syntax || null;
vm.implements = vm.implements || null;
vm.example = vm.example || null;
common.processSeeAlso(vm);
// id is used as default template's bookmark
vm.id = common.getHtmlId(vm.uid);
if (vm.overload && vm.overload.uid) {
vm.overload.id = common.getHtmlId(vm.overload.uid);
}
// concatenate multiple types with `|`
if (vm.syntax) {
var syntax = vm.syntax;
if (syntax.parameters) {
syntax.parameters = syntax.parameters.map(function (p) {
return joinType(p);
})
syntax.parameters = groupParameters(syntax.parameters);
}
if (syntax.return) {
syntax.return = joinType(syntax.return);
}
}
}
function joinType(parameter) {
// change type in syntax from array to string
var joinTypeProperty = function (type, key) {
if (!type || !type[0] || !type[0][key]) return null;
var value = type.map(function (t) {
return t[key][0].value;
}).join(' | ');
return [{
lang: type[0][key][0].lang,
value: value
}];
};
if (parameter.type) {
parameter.type = {
name: joinTypeProperty(parameter.type, "name"),
nameWithType: joinTypeProperty(parameter.type, "nameWithType"),
fullName: joinTypeProperty(parameter.type, "fullName"),
specName: joinTypeProperty(parameter.type, "specName")
}
}
return parameter;
}
function groupParameters(parameters) {
// group parameter with properties
if (!parameters || parameters.length == 0) return parameters;
var groupedParameters = [];
var stack = [];
for (var i = 0; i < parameters.length; i++) {
var parameter = parameters[i];
parameter.properties = null;
var prefixLength = 0;
while (stack.length > 0) {
var top = stack.pop();
var prefix = top.id + '.';
if (parameter.id.indexOf(prefix) == 0) {
prefixLength = prefix.length;
if (!top.parameter.properties) {
top.parameter.properties = [];
}
top.parameter.properties.push(parameter);
stack.push(top);
break;
}
if (stack.length == 0) {
groupedParameters.push(top.parameter);
}
}
stack.push({ id: parameter.id, parameter: parameter });
parameter.id = parameter.id.substring(prefixLength);
}
while (stack.length > 0) {
top = stack.pop();
}
groupedParameters.push(top.parameter);
return groupedParameters;
}
function groupChildren(model, category, typeChildrenItems) {
if (!model || !model.type) {
return;
}
if (!typeChildrenItems) {
var typeChildrenItems = getDefinitions(category);
}
var grouped = {};
normalizeChildren(model.children).forEach(function (c) {
if (c.isEii) {
var type = "eii";
} else {
var type = c.type.toLowerCase();
}
if (!grouped.hasOwnProperty(type)) {
grouped[type] = [];
}
// special handle for field
if (type === "field" && c.syntax) {
c.syntax.fieldValue = c.syntax.return;
c.syntax.return = undefined;
}
// special handle for property
if (type === "property" && c.syntax) {
c.syntax.propertyValue = c.syntax.return;
c.syntax.return = undefined;
}
// special handle for event
if (type === "event" && c.syntax) {
c.syntax.eventType = c.syntax.return;
c.syntax.return = undefined;
}
grouped[type].push(c);
})
var children = [];
for (var key in typeChildrenItems) {
if (typeChildrenItems.hasOwnProperty(key) && grouped.hasOwnProperty(key)) {
var typeChildrenItem = typeChildrenItems[key];
var items = grouped[key];
if (items && items.length > 0) {
var item = {};
for (var itemKey in typeChildrenItem) {
if (typeChildrenItem.hasOwnProperty(itemKey)){
item[itemKey] = typeChildrenItem[itemKey];
}
}
item.children = items;
children.push(item);
}
}
}
model.children = children;
}
function getTypePropertyName(type) {
if (!type) {
return undefined;
}
var loweredType = type.toLowerCase();
var definition = getDefinition(loweredType);
if (definition) {
return definition.typePropertyName;
}
return undefined;
}
function getCategory(type) {
var classItems = getDefinitions(classCategory);
if (classItems.hasOwnProperty(type)) {
return classCategory;
}
var namespaceItems = getDefinitions(namespaceCategory);
if (namespaceItems.hasOwnProperty(type)) {
return namespaceCategory;
}
return undefined;
}
function getDefinition(type) {
var classItems = getDefinitions(classCategory);
if (classItems.hasOwnProperty(type)) {
return classItems[type];
}
var namespaceItems = getDefinitions(namespaceCategory);
if (namespaceItems.hasOwnProperty(type)) {
return namespaceItems[type];
}
return undefined;
}
function getDefinitions(category) {
var namespaceItems = {
"class": { inClass: true, typePropertyName: "inClass", id: "classes" },
"struct": { inStruct: true, typePropertyName: "inStruct", id: "structs" },
"interface": { inInterface: true, typePropertyName: "inInterface", id: "interfaces" },
"enum": { inEnum: true, typePropertyName: "inEnum", id: "enums" },
"delegate": { inDelegate: true, typePropertyName: "inDelegate", id: "delegates" }
};
var classItems = {
"constructor": { inConstructor: true, typePropertyName: "inConstructor", id: "constructors" },
"field": { inField: true, typePropertyName: "inField", id: "fields" },
"property": { inProperty: true, typePropertyName: "inProperty", id: "properties" },
"method": { inMethod: true, typePropertyName: "inMethod", id: "methods" },
"event": { inEvent: true, typePropertyName: "inEvent", id: "events" },
"operator": { inOperator: true, typePropertyName: "inOperator", id: "operators" },
"eii": { inEii: true, typePropertyName: "inEii", id: "eii" },
"function": { inFunction: true, typePropertyName: "inFunction", id: "functions"},
"member": { inMember: true, typePropertyName: "inMember", id: "members"}
};
if (category === 'class') {
return classItems;
}
if (category === 'ns') {
return namespaceItems;
}
console.err("category '" + category + "' is not valid.");
return undefined;
}
function normalizeChildren(children) {
if (children[0] && children[0].lang && children[0].value) {
return children[0].value;
}
return children;
} |
'use strict';
const { By, until } = require('selenium-webdriver');
const { register, Page, platforms } = require('../../../../../scripts/e2e');
class E2ETestPage extends Page {
constructor(driver, platform) {
super(driver, `http://localhost:3333/src/components/segment/test/standalone?ionic:mode=${platform}`);
}
}
platforms.forEach(platform => {
describe('segment/standalone', () => {
register('should init', driver => {
const page = new E2ETestPage(driver, platform);
return page.navigate('#browserSegment');
});
});
});
|
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Define the function for main process.
*
* @param {string} name - A program name.
* @returns {function} The function for main process.
*/
function defineMain(name) {
/**
* The main process of `npm-run-all` command.
*
* @param {string[]} args - Arguments to parse.
* @param {stream.Writable} stdout - A writable stream to print logs.
* @param {stream.Writable} stderr - A writable stream to print errors.
* @returns {Promise} A promise which comes to be fulfilled when all
* npm-scripts are completed.
* @private
*/
return function main(args) {
var stdout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var stderr = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
switch (args[0]) {
case undefined:
case "-h":
case "--help":
return require("../" + name + "/help")(stdout);
case "-v":
case "--version":
return require("./version")(stdout);
default:
return require("../" + name + "/main")(args, stdout, stderr);
}
};
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = function bootstrap(entryModule, name) {
var main = entryModule.exports = defineMain(name);
/* eslint-disable no-console, no-process-exit */
/* istanbul ignore if */
if (require.main === entryModule) {
// Execute.
var promise = main(process.argv.slice(2), process.stdout, process.stderr);
// Error Handling.
promise.then(function () {
// I'm not sure why, but maybe the process never exits
// on Git Bash (MINGW64)
process.exit(0);
}, function (err) {
console.error("ERROR:", err.message);
process.exit(1);
});
}
}; |
/**
* @fileoverview Tests for keyword-spacing rule.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const parser = require("../../fixtures/fixture-parser"),
rule = require("../../../lib/rules/keyword-spacing"),
RuleTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const BOTH = { before: true, after: true };
const NEITHER = { before: false, after: false };
/**
* Creates an option object to test an "overrides" option.
*
* e.g.
*
* override("as", BOTH)
*
* returns
*
* {
* before: false,
* after: false,
* overrides: {as: {before: true, after: true}}
* }
*
* @param {string} keyword - A keyword to be overriden.
* @param {Object} value - A value to override.
* @returns {Object} An option object to test an "overrides" option.
*/
function override(keyword, value) {
const retv = {
before: value.before === false,
after: value.after === false,
overrides: {}
};
retv.overrides[keyword] = value;
return retv;
}
/**
* Gets an error message that expected space(s) before a specified keyword.
*
* @param {string} keyword - A keyword.
* @returns {string[]} An error message.
*/
function expectedBefore(keyword) {
return [`Expected space(s) before "${keyword}".`];
}
/**
* Gets an error message that expected space(s) after a specified keyword.
*
* @param {string} keyword - A keyword.
* @returns {string[]} An error message.
*/
function expectedAfter(keyword) {
return [`Expected space(s) after "${keyword}".`];
}
/**
* Gets error messages that expected space(s) before and after a specified
* keyword.
*
* @param {string} keyword - A keyword.
* @returns {string[]} Error messages.
*/
function expectedBeforeAndAfter(keyword) {
return [
`Expected space(s) before "${keyword}".`,
`Expected space(s) after "${keyword}".`
];
}
/**
* Gets an error message that unexpected space(s) before a specified keyword.
*
* @param {string} keyword - A keyword.
* @returns {string[]} An error message.
*/
function unexpectedBefore(keyword) {
return [`Unexpected space(s) before "${keyword}".`];
}
/**
* Gets an error message that unexpected space(s) after a specified keyword.
*
* @param {string} keyword - A keyword.
* @returns {string[]} An error message.
*/
function unexpectedAfter(keyword) {
return [`Unexpected space(s) after "${keyword}".`];
}
/**
* Gets error messages that unexpected space(s) before and after a specified
* keyword.
*
* @param {string} keyword - A keyword.
* @returns {string[]} Error messages.
*/
function unexpectedBeforeAndAfter(keyword) {
return [
`Unexpected space(s) before "${keyword}".`,
`Unexpected space(s) after "${keyword}".`
];
}
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new RuleTester();
ruleTester.run("keyword-spacing", rule, {
valid: [
//----------------------------------------------------------------------
// as
//----------------------------------------------------------------------
{ code: "import * as a from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "import*as a from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "import* as a from\"foo\"", options: [override("as", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "import *as a from \"foo\"", options: [override("as", NEITHER)], parserOptions: { sourceType: "module" } },
//----------------------------------------------------------------------
// async
//----------------------------------------------------------------------
{ code: "{} async function foo() {}", parserOptions: { ecmaVersion: 8 } },
{ code: "{}async function foo() {}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "{} async function foo() {}", options: [override("async", BOTH)], parserOptions: { ecmaVersion: 8 } },
{ code: "{}async function foo() {}", options: [override("async", NEITHER)], parserOptions: { ecmaVersion: 8 } },
{ code: "{} async () => {}", parserOptions: { ecmaVersion: 8 } },
{ code: "{}async () => {}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "{} async () => {}", options: [override("async", BOTH)], parserOptions: { ecmaVersion: 8 } },
{ code: "{}async () => {}", options: [override("async", NEITHER)], parserOptions: { ecmaVersion: 8 } },
{ code: "({async [b]() {}})", parserOptions: { ecmaVersion: 8 } },
{ code: "({async[b]() {}})", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "({async [b]() {}})", options: [override("async", BOTH)], parserOptions: { ecmaVersion: 8 } },
{ code: "({async[b]() {}})", options: [override("async", NEITHER)], parserOptions: { ecmaVersion: 8 } },
{ code: "class A {a(){} async [b]() {}}", parserOptions: { ecmaVersion: 8 } },
{ code: "class A {a(){}async[b]() {}}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "class A {a(){} async [b]() {}}", options: [override("async", BOTH)], parserOptions: { ecmaVersion: 8 } },
{ code: "class A {a(){}async[b]() {}}", options: [override("async", NEITHER)], parserOptions: { ecmaVersion: 8 } },
// not conflict with `array-bracket-spacing`
{ code: "[async function foo() {}]", parserOptions: { ecmaVersion: 8 } },
{ code: "[ async function foo() {}]", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `arrow-spacing`
{ code: "() =>async function foo() {}", parserOptions: { ecmaVersion: 8 } },
{ code: "() => async function foo() {}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `block-spacing`
{ code: "{async function foo() {} }", parserOptions: { ecmaVersion: 8 } },
{ code: "{ async function foo() {} }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `comma-spacing`
{ code: "(0,async function foo() {})", parserOptions: { ecmaVersion: 8 } },
{ code: "(0, async function foo() {})", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `computed-property-spacing`
{ code: "a[async function foo() {}]", parserOptions: { ecmaVersion: 8 } },
{ code: "({[async function foo() {}]: 0})", parserOptions: { ecmaVersion: 8 } },
{ code: "a[ async function foo() {}]", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "({[ async function foo() {}]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `key-spacing`
{ code: "({a:async function foo() {} })", parserOptions: { ecmaVersion: 8 } },
{ code: "({a: async function foo() {} })", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `semi-spacing`
{ code: ";async function foo() {};", parserOptions: { ecmaVersion: 8 } },
{ code: "; async function foo() {} ;", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-before-function-paren`
{ code: "async() => {}", parserOptions: { ecmaVersion: 8 } },
{ code: "async () => {}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-in-parens`
{ code: "(async function foo() {})", parserOptions: { ecmaVersion: 8 } },
{ code: "( async function foo() {})", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-infix-ops`
{ code: "a =async function foo() {}", parserOptions: { ecmaVersion: 8 } },
{ code: "a = async function foo() {}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-unary-ops`
{ code: "!async function foo() {}", parserOptions: { ecmaVersion: 8 } },
{ code: "! async function foo() {}", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `template-curly-spacing`
{ code: "`${async function foo() {}}`", parserOptions: { ecmaVersion: 8 } },
{ code: "`${ async function foo() {}}`", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={async function foo() {}} />", parserOptions: { ecmaVersion: 8, ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ async function foo() {}} />", options: [NEITHER], parserOptions: { ecmaVersion: 8, ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// await
//----------------------------------------------------------------------
{ code: "async function wrap() { {} await +1 }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { {}await +1 }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { {} await +1 }", options: [override("await", BOTH)], parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { {}await +1 }", options: [override("await", NEITHER)], parserOptions: { ecmaVersion: 8 } },
// not conflict with `array-bracket-spacing`
{ code: "async function wrap() { [await a] }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { [ await a] }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `arrow-spacing`
{ code: "async () =>await a", parserOptions: { ecmaVersion: 8 } },
{ code: "async () => await a", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `block-spacing`
{ code: "async function wrap() { {await a } }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { { await a } }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `comma-spacing`
{ code: "async function wrap() { (0,await a) }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { (0, await a) }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `computed-property-spacing`
{ code: "async function wrap() { a[await a] }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { ({[await a]: 0}) }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { a[ await a] }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { ({[ await a]: 0}) }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `key-spacing`
{ code: "async function wrap() { ({a:await a }) }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { ({a: await a }) }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `semi-spacing`
{ code: "async function wrap() { ;await a; }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { ; await a ; }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-in-parens`
{ code: "async function wrap() { (await a) }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { ( await a) }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-infix-ops`
{ code: "async function wrap() { a =await a }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { a = await a }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `space-unary-ops`
{ code: "async function wrap() { !await'a' }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { ! await 'a' }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `template-curly-spacing`
{ code: "async function wrap() { `${await a}` }", parserOptions: { ecmaVersion: 8 } },
{ code: "async function wrap() { `${ await a}` }", options: [NEITHER], parserOptions: { ecmaVersion: 8 } },
// not conflict with `jsx-curly-spacing`
{ code: "async function wrap() { <Foo onClick={await a} /> }", parserOptions: { ecmaVersion: 8, ecmaFeatures: { jsx: true } } },
{ code: "async function wrap() { <Foo onClick={ await a} /> }", options: [NEITHER], parserOptions: { ecmaVersion: 8, ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// break
//----------------------------------------------------------------------
"A: for (;;) { {} break A; }",
{ code: "A: for(;;) { {}break A; }", options: [NEITHER] },
{ code: "A: for(;;) { {} break A; }", options: [override("break", BOTH)] },
{ code: "A: for (;;) { {}break A; }", options: [override("break", NEITHER)] },
// not conflict with `block-spacing`
"for (;;) {break}",
{ code: "for(;;) { break }", options: [NEITHER] },
// not conflict with `semi-spacing`
"for (;;) { ;break; }",
{ code: "for(;;) { ; break ; }", options: [NEITHER] },
//----------------------------------------------------------------------
// case
//----------------------------------------------------------------------
"switch (a) { case 0: {} case +1: }",
"switch (a) { case 0: {} case (1): }",
{ code: "switch(a) { case 0: {}case+1: }", options: [NEITHER] },
{ code: "switch(a) { case 0: {}case(1): }", options: [NEITHER] },
{ code: "switch(a) { case 0: {} case +1: }", options: [override("case", BOTH)] },
{ code: "switch (a) { case 0: {}case+1: }", options: [override("case", NEITHER)] },
// not conflict with `block-spacing`
"switch (a) {case 0: }",
{ code: "switch(a) { case 0: }", options: [NEITHER] },
// not conflict with `semi-spacing`
"switch (a) { case 0: ;case 1: }",
{ code: "switch(a) { case 0: ; case 1: }", options: [NEITHER] },
//----------------------------------------------------------------------
// catch
//----------------------------------------------------------------------
"try {} catch (e) {}",
{ code: "try{}catch(e) {}", options: [NEITHER] },
{ code: "try{} catch (e) {}", options: [override("catch", BOTH)] },
{ code: "try {}catch(e) {}", options: [override("catch", NEITHER)] },
"try {}\ncatch (e) {}",
{ code: "try{}\ncatch(e) {}", options: [NEITHER] },
//----------------------------------------------------------------------
// class
//----------------------------------------------------------------------
{ code: "{} class Bar {}", parserOptions: { ecmaVersion: 6 } },
{ code: "(class {})", parserOptions: { ecmaVersion: 6 } },
{ code: "{}class Bar {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "(class{})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "{} class Bar {}", options: [override("class", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "{}class Bar {}", options: [override("class", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `array-bracket-spacing`
{ code: "[class {}]", parserOptions: { ecmaVersion: 6 } },
{ code: "[ class{}]", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `arrow-spacing`
{ code: "() =>class {}", parserOptions: { ecmaVersion: 6 } },
{ code: "() => class{}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
{ code: "{class Bar {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "{ class Bar {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `comma-spacing`
{ code: "(0,class {})", parserOptions: { ecmaVersion: 6 } },
{ code: "(0, class{})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `computed-property-spacing`
{ code: "a[class {}]", parserOptions: { ecmaVersion: 6 } },
{ code: "({[class {}]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ class{}]", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "({[ class{}]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
{ code: "({a:class {} })", parserOptions: { ecmaVersion: 6 } },
{ code: "({a: class{} })", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
{ code: ";class Bar {};", parserOptions: { ecmaVersion: 6 } },
{ code: "; class Bar {} ;", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-in-parens`
{ code: "( class{})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-infix-ops`
{ code: "a =class {}", parserOptions: { ecmaVersion: 6 } },
{ code: "a = class{}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-unary-ops`
{ code: "!class {}", parserOptions: { ecmaVersion: 6 } },
{ code: "! class{}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `template-curly-spacing`
{ code: "`${class {}}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ class{}}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={class {}} />", parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ class{}} />", options: [NEITHER], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// const
//----------------------------------------------------------------------
{ code: "{} const [a] = b", parserOptions: { ecmaVersion: 6 } },
{ code: "{} const {a} = b", parserOptions: { ecmaVersion: 6 } },
{ code: "{}const[a] = b", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "{}const{a} = b", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "{} const [a] = b", options: [override("const", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "{} const {a} = b", options: [override("const", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "{}const[a] = b", options: [override("const", NEITHER)], parserOptions: { ecmaVersion: 6 } },
{ code: "{}const{a} = b", options: [override("const", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
{ code: "{const a = b}", parserOptions: { ecmaVersion: 6 } },
{ code: "{ const a = b}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
{ code: ";const a = b;", parserOptions: { ecmaVersion: 6 } },
{ code: "; const a = b ;", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// continue
//----------------------------------------------------------------------
"A: for (;;) { {} continue A; }",
{ code: "A: for(;;) { {}continue A; }", options: [NEITHER] },
{ code: "A: for(;;) { {} continue A; }", options: [override("continue", BOTH)] },
{ code: "A: for (;;) { {}continue A; }", options: [override("continue", NEITHER)] },
// not conflict with `block-spacing`
"for (;;) {continue}",
{ code: "for(;;) { continue }", options: [NEITHER] },
// not conflict with `semi-spacing`
"for (;;) { ;continue; }",
{ code: "for(;;) { ; continue ; }", options: [NEITHER] },
//----------------------------------------------------------------------
// debugger
//----------------------------------------------------------------------
"{} debugger",
{ code: "{}debugger", options: [NEITHER] },
{ code: "{} debugger", options: [override("debugger", BOTH)] },
{ code: "{}debugger", options: [override("debugger", NEITHER)] },
// not conflict with `block-spacing`
"{debugger}",
{ code: "{ debugger }", options: [NEITHER] },
// not conflict with `semi-spacing`
";debugger;",
{ code: "; debugger ;", options: [NEITHER] },
//----------------------------------------------------------------------
// default
//----------------------------------------------------------------------
"switch (a) { case 0: {} default: }",
{ code: "switch(a) { case 0: {}default: }", options: [NEITHER] },
{ code: "switch(a) { case 0: {} default: }", options: [override("default", BOTH)] },
{ code: "switch (a) { case 0: {}default: }", options: [override("default", NEITHER)] },
// not conflict with `block-spacing`
"switch (a) {default:}",
{ code: "switch(a) { default: }", options: [NEITHER] },
// not conflict with `semi-spacing`
"switch (a) { case 0: ;default: }",
{ code: "switch(a) { case 0: ; default: }", options: [NEITHER] },
//----------------------------------------------------------------------
// delete
//----------------------------------------------------------------------
"{} delete foo.a",
{ code: "{}delete foo.a", options: [NEITHER] },
{ code: "{} delete foo.a", options: [override("delete", BOTH)] },
{ code: "{}delete foo.a", options: [override("delete", NEITHER)] },
// not conflict with `array-bracket-spacing`
"[delete foo.a]",
{ code: "[ delete foo.a]", options: [NEITHER] },
// not conflict with `arrow-spacing`
{ code: "(() =>delete foo.a)", parserOptions: { ecmaVersion: 6 } },
{ code: "(() => delete foo.a)", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{delete foo.a }",
{ code: "{ delete foo.a }", options: [NEITHER] },
// not conflict with `comma-spacing`
"(0,delete foo.a)",
{ code: "(0, delete foo.a)", options: [NEITHER] },
// not conflict with `computed-property-spacing`
"a[delete foo.a]",
{ code: "({[delete foo.a]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ delete foo.a]", options: [NEITHER] },
{ code: "({[ delete foo.a]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
"({a:delete foo.a })",
{ code: "({a: delete foo.a })", options: [NEITHER] },
// not conflict with `semi-spacing`
";delete foo.a",
{ code: "; delete foo.a", options: [NEITHER] },
// not conflict with `space-in-parens`
"(delete foo.a)",
{ code: "( delete foo.a)", options: [NEITHER] },
// not conflict with `space-infix-ops`
"a =delete foo.a",
{ code: "a = delete foo.a", options: [NEITHER] },
// not conflict with `space-unary-ops`
"!delete(foo.a)",
{ code: "! delete (foo.a)", options: [NEITHER] },
// not conflict with `template-curly-spacing`
{ code: "`${delete foo.a}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ delete foo.a}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={delete foo.a} />", parserOptions: { ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ delete foo.a} />", options: [NEITHER], parserOptions: { ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// do
//----------------------------------------------------------------------
"{} do {} while (true)",
{ code: "{}do{}while(true)", options: [NEITHER] },
{ code: "{} do {}while(true)", options: [override("do", BOTH)] },
{ code: "{}do{} while (true)", options: [override("do", NEITHER)] },
"{}\ndo\n{} while (true)",
{ code: "{}\ndo\n{}while(true)", options: [NEITHER] },
// not conflict with `block-spacing`
"{do {} while (true)}",
{ code: "{ do{}while(true) }", options: [NEITHER] },
// not conflict with `semi-spacing`
";do; while (true)",
{ code: "; do ;while(true)", options: [NEITHER] },
//----------------------------------------------------------------------
// else
//----------------------------------------------------------------------
"if (a) {} else {}",
"if (a) {} else if (b) {}",
"if (a) {} else (0)",
"if (a) {} else []",
"if (a) {} else +1",
"if (a) {} else \"a\"",
{ code: "if(a){}else{}", options: [NEITHER] },
{ code: "if(a){}else if(b) {}", options: [NEITHER] },
{ code: "if(a) {}else(0)", options: [NEITHER] },
{ code: "if(a) {}else[]", options: [NEITHER] },
{ code: "if(a) {}else+1", options: [NEITHER] },
{ code: "if(a) {}else\"a\"", options: [NEITHER] },
{ code: "if(a) {} else {}", options: [override("else", BOTH)] },
{ code: "if (a) {}else{}", options: [override("else", NEITHER)] },
"if (a) {}\nelse\n{}",
{ code: "if(a) {}\nelse\n{}", options: [NEITHER] },
// not conflict with `semi-spacing`
"if (a);else;",
{ code: "if(a); else ;", options: [NEITHER] },
//----------------------------------------------------------------------
// export
//----------------------------------------------------------------------
{ code: "{} export {a}", parserOptions: { sourceType: "module" } },
{ code: "{} export default a", parserOptions: { sourceType: "module" } },
{ code: "{} export * from \"a\"", parserOptions: { sourceType: "module" } },
{ code: "{}export{a}", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "{} export {a}", options: [override("export", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "{}export{a}", options: [override("export", NEITHER)], parserOptions: { sourceType: "module" } },
// not conflict with `semi-spacing`
{ code: ";export {a}", parserOptions: { sourceType: "module" } },
{ code: "; export{a}", options: [NEITHER], parserOptions: { sourceType: "module" } },
//----------------------------------------------------------------------
// extends
//----------------------------------------------------------------------
{ code: "class Bar extends [] {}", parserOptions: { ecmaVersion: 6 } },
{ code: "class Bar extends[] {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "class Bar extends [] {}", options: [override("extends", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "class Bar extends[] {}", options: [override("extends", NEITHER)], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// finally
//----------------------------------------------------------------------
"try {} finally {}",
{ code: "try{}finally{}", options: [NEITHER] },
{ code: "try{} finally {}", options: [override("finally", BOTH)] },
{ code: "try {}finally{}", options: [override("finally", NEITHER)] },
"try {}\nfinally\n{}",
{ code: "try{}\nfinally\n{}", options: [NEITHER] },
//----------------------------------------------------------------------
// for
//----------------------------------------------------------------------
"{} for (;;) {}",
"{} for (var foo in obj) {}",
{ code: "{} for (var foo of list) {}", parserOptions: { ecmaVersion: 6 } },
{ code: "{}for(;;) {}", options: [NEITHER] },
{ code: "{}for(var foo in obj) {}", options: [NEITHER] },
{ code: "{}for(var foo of list) {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "{} for (;;) {}", options: [override("for", BOTH)] },
{ code: "{} for (var foo in obj) {}", options: [override("for", BOTH)] },
{ code: "{} for (var foo of list) {}", options: [override("for", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "{}for(;;) {}", options: [override("for", NEITHER)] },
{ code: "{}for(var foo in obj) {}", options: [override("for", NEITHER)] },
{ code: "{}for(var foo of list) {}", options: [override("for", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{for (;;) {} }",
"{for (var foo in obj) {} }",
{ code: "{for (var foo of list) {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "{ for(;;) {} }", options: [NEITHER] },
{ code: "{ for(var foo in obj) {} }", options: [NEITHER] },
{ code: "{ for(var foo of list) {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
";for (;;) {}",
";for (var foo in obj) {}",
{ code: ";for (var foo of list) {}", parserOptions: { ecmaVersion: 6 } },
{ code: "; for(;;) {}", options: [NEITHER] },
{ code: "; for(var foo in obj) {}", options: [NEITHER] },
{ code: "; for(var foo of list) {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// from
//----------------------------------------------------------------------
{ code: "import {foo} from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "export {foo} from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "export * from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "import{foo}from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "export{foo}from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "export*from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "import{foo} from \"foo\"", options: [override("from", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "export{foo} from \"foo\"", options: [override("from", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "export* from \"foo\"", options: [override("from", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "import {foo}from\"foo\"", options: [override("from", NEITHER)], parserOptions: { sourceType: "module" } },
{ code: "export {foo}from\"foo\"", options: [override("from", NEITHER)], parserOptions: { sourceType: "module" } },
{ code: "export *from\"foo\"", options: [override("from", NEITHER)], parserOptions: { sourceType: "module" } },
//----------------------------------------------------------------------
// function
//----------------------------------------------------------------------
"{} function foo() {}",
{ code: "{}function foo() {}", options: [NEITHER] },
{ code: "{} function foo() {}", options: [override("function", BOTH)] },
{ code: "{}function foo() {}", options: [override("function", NEITHER)] },
// not conflict with `array-bracket-spacing`
"[function() {}]",
{ code: "[ function() {}]", options: [NEITHER] },
// not conflict with `arrow-spacing`
{ code: "(() =>function() {})", parserOptions: { ecmaVersion: 6 } },
{ code: "(() => function() {})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{function foo() {} }",
{ code: "{ function foo() {} }", options: [NEITHER] },
// not conflict with `comma-spacing`
"(0,function() {})",
{ code: "(0, function() {})", options: [NEITHER] },
// not conflict with `computed-property-spacing`
"a[function() {}]",
{ code: "({[function() {}]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ function() {}]", options: [NEITHER] },
{ code: "({[ function(){}]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `generator-star-spacing`
{ code: "function* foo() {}", parserOptions: { ecmaVersion: 6 } },
{ code: "function *foo() {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
"({a:function() {} })",
{ code: "({a: function() {} })", options: [NEITHER] },
// not conflict with `semi-spacing`
";function foo() {};",
{ code: "; function foo() {} ;", options: [NEITHER] },
/*
* not conflict with `space-before-function-paren`
* not conflict with `space-in-parens`
*/
"(function() {})",
{ code: "( function () {})", options: [NEITHER] },
// not conflict with `space-infix-ops`
"a =function() {}",
{ code: "a = function() {}", options: [NEITHER] },
// not conflict with `space-unary-ops`
"!function() {}",
{ code: "! function() {}", options: [NEITHER] },
// not conflict with `template-curly-spacing`
{ code: "`${function() {}}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ function() {}}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={function() {}} />", parserOptions: { ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ function() {}} />", options: [NEITHER], parserOptions: { ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// get
//----------------------------------------------------------------------
{ code: "({ get [b]() {} })", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} get [b]() {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} static get [b]() {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "({ get[b]() {} })", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}get[b]() {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}static get[b]() {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "({ get [b]() {} })", options: [override("get", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} get [b]() {} }", options: [override("get", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "({ get[b]() {} })", options: [override("get", NEITHER)], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}get[b]() {} }", options: [override("get", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `comma-spacing`
{ code: "({ a,get [b]() {} })", parserOptions: { ecmaVersion: 6 } },
{ code: "({ a, get[b]() {} })", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// if
//----------------------------------------------------------------------
"{} if (a) {}",
"if (a) {} else if (a) {}",
{ code: "{}if(a) {}", options: [NEITHER] },
{ code: "if(a) {}else if(a) {}", options: [NEITHER] },
{ code: "{} if (a) {}", options: [override("if", BOTH)] },
{ code: "if (a) {}else if (a) {}", options: [override("if", BOTH)] },
{ code: "{}if(a) {}", options: [override("if", NEITHER)] },
{ code: "if(a) {} else if(a) {}", options: [override("if", NEITHER)] },
// not conflict with `block-spacing`
"{if (a) {} }",
{ code: "{ if(a) {} }", options: [NEITHER] },
// not conflict with `semi-spacing`
";if (a) {}",
{ code: "; if(a) {}", options: [NEITHER] },
//----------------------------------------------------------------------
// import
//----------------------------------------------------------------------
{ code: "{} import {a} from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "{} import a from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "{} import * as a from \"a\"", parserOptions: { sourceType: "module" } },
{ code: "{}import{a}from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "{}import*as a from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
{ code: "{} import {a}from\"foo\"", options: [override("import", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "{} import *as a from\"foo\"", options: [override("import", BOTH)], parserOptions: { sourceType: "module" } },
{ code: "{}import{a} from \"foo\"", options: [override("import", NEITHER)], parserOptions: { sourceType: "module" } },
{ code: "{}import* as a from \"foo\"", options: [override("import", NEITHER)], parserOptions: { sourceType: "module" } },
// not conflict with `semi-spacing`
{ code: ";import {a} from \"foo\"", parserOptions: { sourceType: "module" } },
{ code: "; import{a}from\"foo\"", options: [NEITHER], parserOptions: { sourceType: "module" } },
//----------------------------------------------------------------------
// in
//----------------------------------------------------------------------
{ code: "for ([foo] in {foo: 0}) {}", parserOptions: { ecmaVersion: 6 } },
{ code: "for([foo]in{foo: 0}) {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "for([foo] in {foo: 0}) {}", options: [override("in", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "for ([foo]in{foo: 0}) {}", options: [override("in", NEITHER)], parserOptions: { ecmaVersion: 6 } },
{ code: "for ([foo] in ({foo: 0})) {}", parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-infix-ops`
"if (\"foo\"in{foo: 0}) {}",
{ code: "if(\"foo\" in {foo: 0}) {}", options: [NEITHER] },
//----------------------------------------------------------------------
// instanceof
//----------------------------------------------------------------------
// not conflict with `space-infix-ops`
"if (\"foo\"instanceof{foo: 0}) {}",
{ code: "if(\"foo\" instanceof {foo: 0}) {}", options: [NEITHER] },
//----------------------------------------------------------------------
// let
//----------------------------------------------------------------------
{ code: "{} let [a] = b", parserOptions: { ecmaVersion: 6 } },
{ code: "{}let[a] = b", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "{} let [a] = b", options: [override("let", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "{}let[a] = b", options: [override("let", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
{ code: "{let [a] = b }", parserOptions: { ecmaVersion: 6 } },
{ code: "{ let[a] = b }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
{ code: ";let [a] = b", parserOptions: { ecmaVersion: 6 } },
{ code: "; let[a] = b", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// new
//----------------------------------------------------------------------
"{} new foo()",
{ code: "{}new foo()", options: [NEITHER] },
{ code: "{} new foo()", options: [override("new", BOTH)] },
{ code: "{}new foo()", options: [override("new", NEITHER)] },
// not conflict with `array-bracket-spacing`
"[new foo()]",
{ code: "[ new foo()]", options: [NEITHER] },
// not conflict with `arrow-spacing`
{ code: "(() =>new foo())", parserOptions: { ecmaVersion: 6 } },
{ code: "(() => new foo())", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{new foo() }",
{ code: "{ new foo() }", options: [NEITHER] },
// not conflict with `comma-spacing`
"(0,new foo())",
{ code: "(0, new foo())", options: [NEITHER] },
// not conflict with `computed-property-spacing`
"a[new foo()]",
{ code: "({[new foo()]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ new foo()]", options: [NEITHER] },
{ code: "({[ new foo()]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
"({a:new foo() })",
{ code: "({a: new foo() })", options: [NEITHER] },
// not conflict with `semi-spacing`
";new foo()",
{ code: "; new foo()", options: [NEITHER] },
// not conflict with `space-in-parens`
"(new foo())",
{ code: "( new foo())", options: [NEITHER] },
// not conflict with `space-infix-ops`
"a =new foo()",
{ code: "a = new foo()", options: [NEITHER] },
// not conflict with `space-unary-ops`
"!new(foo)()",
{ code: "! new (foo)()", options: [NEITHER] },
// not conflict with `template-curly-spacing`
{ code: "`${new foo()}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ new foo()}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={new foo()} />", parserOptions: { ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ new foo()} />", options: [NEITHER], parserOptions: { ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// of
//----------------------------------------------------------------------
{ code: "for ([foo] of {foo: 0}) {}", parserOptions: { ecmaVersion: 6 } },
{ code: "for([foo]of{foo: 0}) {}", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "for([foo] of {foo: 0}) {}", options: [override("of", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "for ([foo]of{foo: 0}) {}", options: [override("of", NEITHER)], parserOptions: { ecmaVersion: 6 } },
{ code: "for ([foo] of ({foo: 0})) {}", parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// return
//----------------------------------------------------------------------
"function foo() { {} return +a }",
{ code: "function foo() { {}return+a }", options: [NEITHER] },
{ code: "function foo() { {} return +a }", options: [override("return", BOTH)] },
{ code: "function foo() { {}return+a }", options: [override("return", NEITHER)] },
"function foo() {\nreturn\n}",
{ code: "function foo() {\nreturn\n}", options: [NEITHER] },
// not conflict with `block-spacing`
"function foo() {return}",
{ code: "function foo() { return }", options: [NEITHER] },
// not conflict with `semi-spacing`
"function foo() { ;return; }",
{ code: "function foo() { ; return ; }", options: [NEITHER] },
//----------------------------------------------------------------------
// set
//----------------------------------------------------------------------
{ code: "({ set [b](value) {} })", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} set [b](value) {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} static set [b](value) {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "({ set[b](value) {} })", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}set[b](value) {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "({ set [b](value) {} })", options: [override("set", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} set [b](value) {} }", options: [override("set", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "({ set[b](value) {} })", options: [override("set", NEITHER)], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}set[b](value) {} }", options: [override("set", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `comma-spacing`
{ code: "({ a,set [b](value) {} })", parserOptions: { ecmaVersion: 6 } },
{ code: "({ a, set[b](value) {} })", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// static
//----------------------------------------------------------------------
{ code: "class A { a() {} static [b]() {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}static[b]() {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {} static [b]() {} }", options: [override("static", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() {}static[b]() {} }", options: [override("static", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `generator-star-spacing`
{ code: "class A { static* [a]() {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { static *[a]() {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
{ code: "class A { ;static a() {} }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { ; static a() {} }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
//----------------------------------------------------------------------
// super
//----------------------------------------------------------------------
{ code: "class A { a() { {} super[b](); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { {}super[b](); } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { {} super[b](); } }", options: [override("super", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { {}super[b](); } }", options: [override("super", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `array-bracket-spacing`
{ code: "class A { a() { [super()]; } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { [ super() ]; } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `arrow-spacing`
{ code: "class A { a() { () =>super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { () => super(); } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
{ code: "class A { a() {super()} }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { super() } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `comma-spacing`
{ code: "class A { a() { (0,super()) } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { (0, super()) } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `computed-property-spacing`
{ code: "class A { a() { ({[super()]: 0}) } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { ({[ super() ]: 0}) } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
{ code: "class A { a() { ({a:super() }) } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { ({a: super() }) } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `func-call-spacing`
{ code: "class A { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { constructor() { super (); } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
{ code: "class A { a() { ;super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { ; super() ; } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-in-parens`
{ code: "class A { a() { (super()) } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { ( super() ) } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-infix-ops`
{ code: "class A { a() { b =super() } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { b = super() } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-unary-ops`
{ code: "class A { a() { !super() } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { ! super() } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `template-curly-spacing`
{ code: "class A { a() { `${super()}` } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { a() { `${ super() }` } }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "class A { a() { <Foo onClick={super()} /> } }", parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
{ code: "class A { a() { <Foo onClick={ super() } /> } }", options: [NEITHER], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// switch
//----------------------------------------------------------------------
"{} switch (a) {}",
{ code: "{}switch(a) {}", options: [NEITHER] },
{ code: "{} switch (a) {}", options: [override("switch", BOTH)] },
{ code: "{}switch(a) {}", options: [override("switch", NEITHER)] },
// not conflict with `block-spacing`
"{switch (a) {} }",
{ code: "{ switch(a) {} }", options: [NEITHER] },
// not conflict with `semi-spacing`
";switch (a) {}",
{ code: "; switch(a) {}", options: [NEITHER] },
//----------------------------------------------------------------------
// this
//----------------------------------------------------------------------
"{} this[a]",
{ code: "{}this[a]", options: [NEITHER] },
{ code: "{} this[a]", options: [override("this", BOTH)] },
{ code: "{}this[a]", options: [override("this", NEITHER)] },
// not conflict with `array-bracket-spacing`
"[this]",
{ code: "[ this ]", options: [NEITHER] },
// not conflict with `arrow-spacing`
{ code: "(() =>this)", parserOptions: { ecmaVersion: 6 } },
{ code: "(() => this)", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{this}",
{ code: "{ this }", options: [NEITHER] },
// not conflict with `comma-spacing`
"(0,this)",
{ code: "(0, this)", options: [NEITHER] },
// not conflict with `computed-property-spacing`
"a[this]",
{ code: "({[this]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ this ]", options: [NEITHER] },
{ code: "({[ this ]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
"({a:this })",
{ code: "({a: this })", options: [NEITHER] },
// not conflict with `semi-spacing`
";this",
{ code: "; this", options: [NEITHER] },
// not conflict with `space-in-parens`
"(this)",
{ code: "( this )", options: [NEITHER] },
// not conflict with `space-infix-ops`
"a =this",
{ code: "a = this", options: [NEITHER] },
// not conflict with `space-unary-ops`
"!this",
{ code: "! this", options: [NEITHER] },
// not conflict with `template-curly-spacing`
{ code: "`${this}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ this }`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={this} />", parserOptions: { ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ this } />", options: [NEITHER], parserOptions: { ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// throw
//----------------------------------------------------------------------
"function foo() { {} throw +a }",
{ code: "function foo() { {}throw+a }", options: [NEITHER] },
{ code: "function foo() { {} throw +a }", options: [override("throw", BOTH)] },
{ code: "function foo() { {}throw+a }", options: [override("throw", NEITHER)] },
"function foo() {\nthrow a\n}",
{ code: "function foo() {\nthrow a\n}", options: [NEITHER] },
// not conflict with `block-spacing`
"function foo() {throw a }",
{ code: "function foo() { throw a }", options: [NEITHER] },
// not conflict with `semi-spacing`
"function foo() { ;throw a }",
{ code: "function foo() { ; throw a }", options: [NEITHER] },
//----------------------------------------------------------------------
// try
//----------------------------------------------------------------------
"{} try {} finally {}",
{ code: "{}try{}finally{}", options: [NEITHER] },
{ code: "{} try {}finally{}", options: [override("try", BOTH)] },
{ code: "{}try{} finally {}", options: [override("try", NEITHER)] },
// not conflict with `block-spacing`
"{try {} finally {}}",
{ code: "{ try{}finally{}}", options: [NEITHER] },
// not conflict with `semi-spacing`
";try {} finally {}",
{ code: "; try{}finally{}", options: [NEITHER] },
//----------------------------------------------------------------------
// typeof
//----------------------------------------------------------------------
"{} typeof foo",
{ code: "{}typeof foo", options: [NEITHER] },
{ code: "{} typeof foo", options: [override("typeof", BOTH)] },
{ code: "{}typeof foo", options: [override("typeof", NEITHER)] },
// not conflict with `array-bracket-spacing`
"[typeof foo]",
{ code: "[ typeof foo]", options: [NEITHER] },
// not conflict with `arrow-spacing`
{ code: "(() =>typeof foo)", parserOptions: { ecmaVersion: 6 } },
{ code: "(() => typeof foo)", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{typeof foo }",
{ code: "{ typeof foo }", options: [NEITHER] },
// not conflict with `comma-spacing`
"(0,typeof foo)",
{ code: "(0, typeof foo)", options: [NEITHER] },
// not conflict with `computed-property-spacing`
"a[typeof foo]",
{ code: "({[typeof foo]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ typeof foo]", options: [NEITHER] },
{ code: "({[ typeof foo]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
"({a:typeof foo })",
{ code: "({a: typeof foo })", options: [NEITHER] },
// not conflict with `semi-spacing`
";typeof foo",
{ code: "; typeof foo", options: [NEITHER] },
// not conflict with `space-in-parens`
"(typeof foo)",
{ code: "( typeof foo)", options: [NEITHER] },
// not conflict with `space-infix-ops`
"a =typeof foo",
{ code: "a = typeof foo", options: [NEITHER] },
// not conflict with `space-unary-ops`
"!typeof+foo",
{ code: "! typeof +foo", options: [NEITHER] },
// not conflict with `template-curly-spacing`
{ code: "`${typeof foo}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ typeof foo}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={typeof foo} />", parserOptions: { ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ typeof foo} />", options: [NEITHER], parserOptions: { ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// var
//----------------------------------------------------------------------
{ code: "{} var [a] = b", parserOptions: { ecmaVersion: 6 } },
{ code: "{}var[a] = b", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "{} var [a] = b", options: [override("var", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "{}var[a] = b", options: [override("var", NEITHER)], parserOptions: { ecmaVersion: 6 } },
"for (var foo in [1, 2, 3]) {}",
// not conflict with `block-spacing`
"{var a = b }",
{ code: "{ var a = b }", options: [NEITHER] },
// not conflict with `semi-spacing`
";var a = b",
{ code: "; var a = b", options: [NEITHER] },
//----------------------------------------------------------------------
// void
//----------------------------------------------------------------------
"{} void foo",
{ code: "{}void foo", options: [NEITHER] },
{ code: "{} void foo", options: [override("void", BOTH)] },
{ code: "{}void foo", options: [override("void", NEITHER)] },
// not conflict with `array-bracket-spacing`
"[void foo]",
{ code: "[ void foo]", options: [NEITHER] },
// not conflict with `arrow-spacing`
{ code: "(() =>void foo)", parserOptions: { ecmaVersion: 6 } },
{ code: "(() => void foo)", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `block-spacing`
"{void foo }",
{ code: "{ void foo }", options: [NEITHER] },
// not conflict with `comma-spacing`
"(0,void foo)",
{ code: "(0, void foo)", options: [NEITHER] },
// not conflict with `computed-property-spacing`
"a[void foo]",
{ code: "({[void foo]: 0})", parserOptions: { ecmaVersion: 6 } },
{ code: "a[ void foo]", options: [NEITHER] },
{ code: "({[ void foo]: 0})", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
"({a:void foo })",
{ code: "({a: void foo })", options: [NEITHER] },
// not conflict with `semi-spacing`
";void foo",
{ code: "; void foo", options: [NEITHER] },
// not conflict with `space-in-parens`
"(void foo)",
{ code: "( void foo)", options: [NEITHER] },
// not conflict with `space-infix-ops`
"a =void foo",
{ code: "a = void foo", options: [NEITHER] },
// not conflict with `space-unary-ops`
"!void+foo",
{ code: "! void +foo", options: [NEITHER] },
// not conflict with `template-curly-spacing`
{ code: "`${void foo}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ void foo}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "<Foo onClick={void foo} />", parserOptions: { ecmaFeatures: { jsx: true } } },
{ code: "<Foo onClick={ void foo} />", options: [NEITHER], parserOptions: { ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// while
//----------------------------------------------------------------------
"{} while (a) {}",
"do {} while (a)",
{ code: "{}while(a) {}", options: [NEITHER] },
{ code: "do{}while(a)", options: [NEITHER] },
{ code: "{} while (a) {}", options: [override("while", BOTH)] },
{ code: "do{} while (a)", options: [override("while", BOTH)] },
{ code: "{}while(a) {}", options: [override("while", NEITHER)] },
{ code: "do {}while(a)", options: [override("while", NEITHER)] },
"do {}\nwhile (a)",
{ code: "do{}\nwhile(a)", options: [NEITHER] },
// not conflict with `block-spacing`
"{while (a) {}}",
{ code: "{ while(a) {}}", options: [NEITHER] },
// not conflict with `semi-spacing`
";while (a);",
"do;while (a);",
{ code: "; while(a) ;", options: [NEITHER] },
{ code: "do ; while(a) ;", options: [NEITHER] },
//----------------------------------------------------------------------
// with
//----------------------------------------------------------------------
"{} with (obj) {}",
{ code: "{}with(obj) {}", options: [NEITHER] },
{ code: "{} with (obj) {}", options: [override("with", BOTH)] },
{ code: "{}with(obj) {}", options: [override("with", NEITHER)] },
// not conflict with `block-spacing`
"{with (obj) {}}",
{ code: "{ with(obj) {}}", options: [NEITHER] },
// not conflict with `semi-spacing`
";with (obj) {}",
{ code: "; with(obj) {}", options: [NEITHER] },
//----------------------------------------------------------------------
// yield
//----------------------------------------------------------------------
{ code: "function* foo() { {} yield foo }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { {}yield foo }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { {} yield foo }", options: [override("yield", BOTH)], parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { {}yield foo }", options: [override("yield", NEITHER)], parserOptions: { ecmaVersion: 6 } },
// not conflict with `array-bracket-spacing`
{ code: "function* foo() { [yield] }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { [ yield ] }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
/*
* This is invalid syntax: https://github.com/eslint/eslint/issues/5405
* not conflict with `arrow-spacing`
* {code: "function* foo() { (() =>yield foo) }", parserOptions: {ecmaVersion: 6}},
* {code: "function* foo() { (() => yield foo) }", options: [NEITHER], parserOptions: {ecmaVersion: 6}},
* not conflict with `block-spacing`
*/
{ code: "function* foo() {yield}", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { yield }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `comma-spacing`
{ code: "function* foo() { (0,yield foo) }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { (0, yield foo) }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `computed-property-spacing`
{ code: "function* foo() { a[yield] }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { ({[yield]: 0}) }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { a[ yield ] }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { ({[ yield ]: 0}) }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `key-spacing`
{ code: "function* foo() { ({a:yield foo }) }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { ({a: yield foo }) }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `semi-spacing`
{ code: "function* foo() { ;yield; }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { ; yield ; }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-in-parens`
{ code: "function* foo() { (yield) }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { ( yield ) }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-infix-ops`
{ code: "function* foo() { a =yield foo }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { a = yield foo }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `space-unary-ops`
{ code: "function* foo() { yield+foo }", parserOptions: { ecmaVersion: 6 } },
{ code: "function* foo() { yield +foo }", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `template-curly-spacing`
{ code: "`${yield}`", parserOptions: { ecmaVersion: 6 } },
{ code: "`${ yield}`", options: [NEITHER], parserOptions: { ecmaVersion: 6 } },
// not conflict with `jsx-curly-spacing`
{ code: "function* foo() { <Foo onClick={yield} /> }", parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
{ code: "function* foo() { <Foo onClick={ yield } /> }", options: [NEITHER], parserOptions: { ecmaVersion: 6, ecmaFeatures: { jsx: true } } },
//----------------------------------------------------------------------
// typescript parser
//----------------------------------------------------------------------
// class declaration don't error with decorator
{ code: "@dec class Foo {}", parser: parser("typescript-parsers/decorator-with-class") },
// get, set, async methods don't error with decorator
{ code: "class Foo { @dec get bar() {} @dec set baz() {} @dec async baw() {} }", parser: parser("typescript-parsers/decorator-with-class-methods") },
{ code: "class Foo { @dec static qux() {} @dec static get bar() {} @dec static set baz() {} @dec static async baw() {} }", parser: parser("typescript-parsers/decorator-with-static-class-methods") },
// type keywords can be used as parameters in arrow functions
{ code: "symbol => 4;", parser: parser("typescript-parsers/keyword-with-arrow-function") }
],
invalid: [
//----------------------------------------------------------------------
// as
//----------------------------------------------------------------------
{
code: "import *as a from \"foo\"",
output: "import * as a from \"foo\"",
parserOptions: { sourceType: "module" },
errors: expectedBefore("as")
},
{
code: "import* as a from\"foo\"",
output: "import*as a from\"foo\"",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBefore("as")
},
{
code: "import*as a from\"foo\"",
output: "import* as a from\"foo\"",
options: [override("as", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBefore("as")
},
{
code: "import * as a from \"foo\"",
output: "import *as a from \"foo\"",
options: [override("as", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBefore("as")
},
//----------------------------------------------------------------------
// async
//----------------------------------------------------------------------
{
code: "{}async function foo() {}",
output: "{} async function foo() {}",
parserOptions: { ecmaVersion: 8 },
errors: expectedBefore("async")
},
{
code: "{} async function foo() {}",
output: "{}async function foo() {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBefore("async")
},
{
code: "{}async function foo() {}",
output: "{} async function foo() {}",
options: [override("async", BOTH)],
parserOptions: { ecmaVersion: 8 },
errors: expectedBefore("async")
},
{
code: "{} async function foo() {}",
output: "{}async function foo() {}",
options: [override("async", NEITHER)],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBefore("async")
},
{
code: "{}async () => {}",
output: "{} async () => {}",
parserOptions: { ecmaVersion: 8 },
errors: expectedBefore("async")
},
{
code: "{} async () => {}",
output: "{}async () => {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBefore("async")
},
{
code: "{}async () => {}",
output: "{} async () => {}",
options: [override("async", BOTH)],
parserOptions: { ecmaVersion: 8 },
errors: expectedBefore("async")
},
{
code: "{} async () => {}",
output: "{}async () => {}",
options: [override("async", NEITHER)],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBefore("async")
},
{
code: "({async[b]() {}})",
output: "({async [b]() {}})",
parserOptions: { ecmaVersion: 8 },
errors: expectedAfter("async")
},
{
code: "({async [b]() {}})",
output: "({async[b]() {}})",
options: [NEITHER],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedAfter("async")
},
{
code: "({async[b]() {}})",
output: "({async [b]() {}})",
options: [override("async", BOTH)],
parserOptions: { ecmaVersion: 8 },
errors: expectedAfter("async")
},
{
code: "({async [b]() {}})",
output: "({async[b]() {}})",
options: [override("async", NEITHER)],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedAfter("async")
},
{
code: "class A {a(){}async[b]() {}}",
output: "class A {a(){} async [b]() {}}",
parserOptions: { ecmaVersion: 8 },
errors: expectedBeforeAndAfter("async")
},
{
code: "class A {a(){} async [b]() {}}",
output: "class A {a(){}async[b]() {}}",
options: [NEITHER],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBeforeAndAfter("async")
},
{
code: "class A {a(){}async[b]() {}}",
output: "class A {a(){} async [b]() {}}",
options: [override("async", BOTH)],
parserOptions: { ecmaVersion: 8 },
errors: expectedBeforeAndAfter("async")
},
{
code: "class A {a(){} async [b]() {}}",
output: "class A {a(){}async[b]() {}}",
options: [override("async", NEITHER)],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBeforeAndAfter("async")
},
//----------------------------------------------------------------------
// await
//----------------------------------------------------------------------
{
code: "async function wrap() { {}await a }",
output: "async function wrap() { {} await a }",
parserOptions: { ecmaVersion: 8 },
errors: expectedBefore("await")
},
{
code: "async function wrap() { {} await a }",
output: "async function wrap() { {}await a }",
options: [NEITHER],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBefore("await")
},
{
code: "async function wrap() { {}await a }",
output: "async function wrap() { {} await a }",
options: [override("await", BOTH)],
parserOptions: { ecmaVersion: 8 },
errors: expectedBefore("await")
},
{
code: "async function wrap() { {} await a }",
output: "async function wrap() { {}await a }",
options: [override("await", NEITHER)],
parserOptions: { ecmaVersion: 8 },
errors: unexpectedBefore("await")
},
//----------------------------------------------------------------------
// break
//----------------------------------------------------------------------
{
code: "A: for (;;) { {}break A; }",
output: "A: for (;;) { {} break A; }",
errors: expectedBefore("break")
},
{
code: "A: for(;;) { {} break A; }",
output: "A: for(;;) { {}break A; }",
options: [NEITHER],
errors: unexpectedBefore("break")
},
{
code: "A: for(;;) { {}break A; }",
output: "A: for(;;) { {} break A; }",
options: [override("break", BOTH)],
errors: expectedBefore("break")
},
{
code: "A: for (;;) { {} break A; }",
output: "A: for (;;) { {}break A; }",
options: [override("break", NEITHER)],
errors: unexpectedBefore("break")
},
//----------------------------------------------------------------------
// case
//----------------------------------------------------------------------
{
code: "switch (a) { case 0: {}case+1: }",
output: "switch (a) { case 0: {} case +1: }",
errors: expectedBeforeAndAfter("case")
},
{
code: "switch (a) { case 0: {}case(1): }",
output: "switch (a) { case 0: {} case (1): }",
errors: expectedBeforeAndAfter("case")
},
{
code: "switch(a) { case 0: {} case +1: }",
output: "switch(a) { case 0: {}case+1: }",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("case")
},
{
code: "switch(a) { case 0: {} case (1): }",
output: "switch(a) { case 0: {}case(1): }",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("case")
},
{
code: "switch(a) { case 0: {}case+1: }",
output: "switch(a) { case 0: {} case +1: }",
options: [override("case", BOTH)],
errors: expectedBeforeAndAfter("case")
},
{
code: "switch (a) { case 0: {} case +1: }",
output: "switch (a) { case 0: {}case+1: }",
options: [override("case", NEITHER)],
errors: unexpectedBeforeAndAfter("case")
},
//----------------------------------------------------------------------
// catch
//----------------------------------------------------------------------
{
code: "try {}catch(e) {}",
output: "try {} catch (e) {}",
errors: expectedBeforeAndAfter("catch")
},
{
code: "try{} catch (e) {}",
output: "try{}catch(e) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("catch")
},
{
code: "try{}catch(e) {}",
output: "try{} catch (e) {}",
options: [override("catch", BOTH)],
errors: expectedBeforeAndAfter("catch")
},
{
code: "try {} catch (e) {}",
output: "try {}catch(e) {}",
options: [override("catch", NEITHER)],
errors: unexpectedBeforeAndAfter("catch")
},
//----------------------------------------------------------------------
// class
//----------------------------------------------------------------------
{
code: "{}class Bar {}",
output: "{} class Bar {}",
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("class")
},
{
code: "(class{})",
output: "(class {})",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("class")
},
{
code: "{} class Bar {}",
output: "{}class Bar {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("class")
},
{
code: "(class {})",
output: "(class{})",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("class")
},
{
code: "{}class Bar {}",
output: "{} class Bar {}",
options: [override("class", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("class")
},
{
code: "{} class Bar {}",
output: "{}class Bar {}",
options: [override("class", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("class")
},
//----------------------------------------------------------------------
// const
//----------------------------------------------------------------------
{
code: "{}const[a] = b",
output: "{} const [a] = b",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("const")
},
{
code: "{}const{a} = b",
output: "{} const {a} = b",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("const")
},
{
code: "{} const [a] = b",
output: "{}const[a] = b",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("const")
},
{
code: "{} const {a} = b",
output: "{}const{a} = b",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("const")
},
{
code: "{}const[a] = b",
output: "{} const [a] = b",
options: [override("const", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("const")
},
{
code: "{}const{a} = b",
output: "{} const {a} = b",
options: [override("const", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("const")
},
{
code: "{} const [a] = b",
output: "{}const[a] = b",
options: [override("const", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("const")
},
{
code: "{} const {a} = b",
output: "{}const{a} = b",
options: [override("const", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("const")
},
//----------------------------------------------------------------------
// continue
//----------------------------------------------------------------------
{
code: "A: for (;;) { {}continue A; }",
output: "A: for (;;) { {} continue A; }",
errors: expectedBefore("continue")
},
{
code: "A: for(;;) { {} continue A; }",
output: "A: for(;;) { {}continue A; }",
options: [NEITHER],
errors: unexpectedBefore("continue")
},
{
code: "A: for(;;) { {}continue A; }",
output: "A: for(;;) { {} continue A; }",
options: [override("continue", BOTH)],
errors: expectedBefore("continue")
},
{
code: "A: for (;;) { {} continue A; }",
output: "A: for (;;) { {}continue A; }",
options: [override("continue", NEITHER)],
errors: unexpectedBefore("continue")
},
//----------------------------------------------------------------------
// debugger
//----------------------------------------------------------------------
{
code: "{}debugger",
output: "{} debugger",
errors: expectedBefore("debugger")
},
{
code: "{} debugger",
output: "{}debugger",
options: [NEITHER],
errors: unexpectedBefore("debugger")
},
{
code: "{}debugger",
output: "{} debugger",
options: [override("debugger", BOTH)],
errors: expectedBefore("debugger")
},
{
code: "{} debugger",
output: "{}debugger",
options: [override("debugger", NEITHER)],
errors: unexpectedBefore("debugger")
},
//----------------------------------------------------------------------
// default
//----------------------------------------------------------------------
{
code: "switch (a) { case 0: {}default: }",
output: "switch (a) { case 0: {} default: }",
errors: expectedBefore("default")
},
{
code: "switch(a) { case 0: {} default: }",
output: "switch(a) { case 0: {}default: }",
options: [NEITHER],
errors: unexpectedBefore("default")
},
{
code: "switch(a) { case 0: {}default: }",
output: "switch(a) { case 0: {} default: }",
options: [override("default", BOTH)],
errors: expectedBefore("default")
},
{
code: "switch (a) { case 0: {} default: }",
output: "switch (a) { case 0: {}default: }",
options: [override("default", NEITHER)],
errors: unexpectedBefore("default")
},
//----------------------------------------------------------------------
// delete
//----------------------------------------------------------------------
{
code: "{}delete foo.a",
output: "{} delete foo.a",
errors: expectedBefore("delete")
},
{
code: "{} delete foo.a",
output: "{}delete foo.a",
options: [NEITHER],
errors: unexpectedBefore("delete")
},
{
code: "{}delete foo.a",
output: "{} delete foo.a",
options: [override("delete", BOTH)],
errors: expectedBefore("delete")
},
{
code: "{} delete foo.a",
output: "{}delete foo.a",
options: [override("delete", NEITHER)],
errors: unexpectedBefore("delete")
},
//----------------------------------------------------------------------
// do
//----------------------------------------------------------------------
{
code: "{}do{} while (true)",
output: "{} do {} while (true)",
errors: expectedBeforeAndAfter("do")
},
{
code: "{} do {}while(true)",
output: "{}do{}while(true)",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("do")
},
{
code: "{}do{}while(true)",
output: "{} do {}while(true)",
options: [override("do", BOTH)],
errors: expectedBeforeAndAfter("do")
},
{
code: "{} do {} while (true)",
output: "{}do{} while (true)",
options: [override("do", NEITHER)],
errors: unexpectedBeforeAndAfter("do")
},
//----------------------------------------------------------------------
// else
//----------------------------------------------------------------------
{
code: "if (a) {}else{}",
output: "if (a) {} else {}",
errors: expectedBeforeAndAfter("else")
},
{
code: "if (a) {}else if (b) {}",
output: "if (a) {} else if (b) {}",
errors: expectedBefore("else")
},
{
code: "if (a) {}else(0)",
output: "if (a) {} else (0)",
errors: expectedBeforeAndAfter("else")
},
{
code: "if (a) {}else[]",
output: "if (a) {} else []",
errors: expectedBeforeAndAfter("else")
},
{
code: "if (a) {}else+1",
output: "if (a) {} else +1",
errors: expectedBeforeAndAfter("else")
},
{
code: "if (a) {}else\"a\"",
output: "if (a) {} else \"a\"",
errors: expectedBeforeAndAfter("else")
},
{
code: "if(a){} else {}",
output: "if(a){}else{}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("else")
},
{
code: "if(a){} else if(b) {}",
output: "if(a){}else if(b) {}",
options: [NEITHER],
errors: unexpectedBefore("else")
},
{
code: "if(a) {} else (0)",
output: "if(a) {}else(0)",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("else")
},
{
code: "if(a) {} else []",
output: "if(a) {}else[]",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("else")
},
{
code: "if(a) {} else +1",
output: "if(a) {}else+1",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("else")
},
{
code: "if(a) {} else \"a\"",
output: "if(a) {}else\"a\"",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("else")
},
{
code: "if(a) {}else{}",
output: "if(a) {} else {}",
options: [override("else", BOTH)],
errors: expectedBeforeAndAfter("else")
},
{
code: "if (a) {} else {}",
output: "if (a) {}else{}",
options: [override("else", NEITHER)],
errors: unexpectedBeforeAndAfter("else")
},
{
code: "if (a) {}else {}",
output: "if (a) {} else {}",
errors: expectedBefore("else")
},
{
code: "if (a) {} else{}",
output: "if (a) {} else {}",
errors: expectedAfter("else")
},
{
code: "if(a) {} else{}",
output: "if(a) {}else{}",
options: [NEITHER],
errors: unexpectedBefore("else")
},
{
code: "if(a) {}else {}",
output: "if(a) {}else{}",
options: [NEITHER],
errors: unexpectedAfter("else")
},
//----------------------------------------------------------------------
// export
//----------------------------------------------------------------------
{
code: "{}export{a}",
output: "{} export {a}",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("export")
},
{
code: "{}export default a",
output: "{} export default a",
parserOptions: { sourceType: "module" },
errors: expectedBefore("export")
},
{
code: "{}export* from \"a\"",
output: "{} export * from \"a\"",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("export")
},
{
code: "{} export {a}",
output: "{}export{a}",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("export")
},
{
code: "{}export{a}",
output: "{} export {a}",
options: [override("export", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("export")
},
{
code: "{} export {a}",
output: "{}export{a}",
options: [override("export", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("export")
},
//----------------------------------------------------------------------
// extends
//----------------------------------------------------------------------
{
code: "class Bar extends[] {}",
output: "class Bar extends [] {}",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("extends")
},
{
code: "(class extends[] {})",
output: "(class extends [] {})",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("extends")
},
{
code: "class Bar extends [] {}",
output: "class Bar extends[] {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("extends")
},
{
code: "(class extends [] {})",
output: "(class extends[] {})",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("extends")
},
{
code: "class Bar extends[] {}",
output: "class Bar extends [] {}",
options: [override("extends", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("extends")
},
{
code: "class Bar extends [] {}",
output: "class Bar extends[] {}",
options: [override("extends", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("extends")
},
{
code: "class Bar extends`}` {}",
output: "class Bar extends `}` {}",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("extends")
},
//----------------------------------------------------------------------
// finally
//----------------------------------------------------------------------
{
code: "try {}finally{}",
output: "try {} finally {}",
errors: expectedBeforeAndAfter("finally")
},
{
code: "try{} finally {}",
output: "try{}finally{}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("finally")
},
{
code: "try{}finally{}",
output: "try{} finally {}",
options: [override("finally", BOTH)],
errors: expectedBeforeAndAfter("finally")
},
{
code: "try {} finally {}",
output: "try {}finally{}",
options: [override("finally", NEITHER)],
errors: unexpectedBeforeAndAfter("finally")
},
//----------------------------------------------------------------------
// for
//----------------------------------------------------------------------
{
code: "{}for(;;) {}",
output: "{} for (;;) {}",
errors: expectedBeforeAndAfter("for")
},
{
code: "{}for(var foo in obj) {}",
output: "{} for (var foo in obj) {}",
errors: expectedBeforeAndAfter("for")
},
{
code: "{}for(var foo of list) {}",
output: "{} for (var foo of list) {}",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("for")
},
{
code: "{} for (;;) {}",
output: "{}for(;;) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("for")
},
{
code: "{} for (var foo in obj) {}",
output: "{}for(var foo in obj) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("for")
},
{
code: "{} for (var foo of list) {}",
output: "{}for(var foo of list) {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("for")
},
{
code: "{}for(;;) {}",
output: "{} for (;;) {}",
options: [override("for", BOTH)],
errors: expectedBeforeAndAfter("for")
},
{
code: "{}for(var foo in obj) {}",
output: "{} for (var foo in obj) {}",
options: [override("for", BOTH)],
errors: expectedBeforeAndAfter("for")
},
{
code: "{}for(var foo of list) {}",
output: "{} for (var foo of list) {}",
options: [override("for", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("for")
},
{
code: "{} for (;;) {}",
output: "{}for(;;) {}",
options: [override("for", NEITHER)],
errors: unexpectedBeforeAndAfter("for")
},
{
code: "{} for (var foo in obj) {}",
output: "{}for(var foo in obj) {}",
options: [override("for", NEITHER)],
errors: unexpectedBeforeAndAfter("for")
},
{
code: "{} for (var foo of list) {}",
output: "{}for(var foo of list) {}",
options: [override("for", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("for")
},
//----------------------------------------------------------------------
// from
//----------------------------------------------------------------------
{
code: "import {foo}from\"foo\"",
output: "import {foo} from \"foo\"",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("from")
},
{
code: "export {foo}from\"foo\"",
output: "export {foo} from \"foo\"",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("from")
},
{
code: "export *from\"foo\"",
output: "export * from \"foo\"",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("from")
},
{
code: "import{foo} from \"foo\"",
output: "import{foo}from\"foo\"",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("from")
},
{
code: "export{foo} from \"foo\"",
output: "export{foo}from\"foo\"",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("from")
},
{
code: "export* from \"foo\"",
output: "export*from\"foo\"",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("from")
},
{
code: "import{foo}from\"foo\"",
output: "import{foo} from \"foo\"",
options: [override("from", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("from")
},
{
code: "export{foo}from\"foo\"",
output: "export{foo} from \"foo\"",
options: [override("from", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("from")
},
{
code: "export*from\"foo\"",
output: "export* from \"foo\"",
options: [override("from", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("from")
},
{
code: "import {foo} from \"foo\"",
output: "import {foo}from\"foo\"",
options: [override("from", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("from")
},
{
code: "export {foo} from \"foo\"",
output: "export {foo}from\"foo\"",
options: [override("from", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("from")
},
{
code: "export * from \"foo\"",
output: "export *from\"foo\"",
options: [override("from", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("from")
},
//----------------------------------------------------------------------
// function
//----------------------------------------------------------------------
{
code: "{}function foo() {}",
output: "{} function foo() {}",
errors: expectedBefore("function")
},
{
code: "{} function foo() {}",
output: "{}function foo() {}",
options: [NEITHER],
errors: unexpectedBefore("function")
},
{
code: "{}function foo() {}",
output: "{} function foo() {}",
options: [override("function", BOTH)],
errors: expectedBefore("function")
},
{
code: "{} function foo() {}",
output: "{}function foo() {}",
options: [override("function", NEITHER)],
errors: unexpectedBefore("function")
},
//----------------------------------------------------------------------
// get
//----------------------------------------------------------------------
{
code: "({ get[b]() {} })",
output: "({ get [b]() {} })",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("get")
},
{
code: "class A { a() {}get[b]() {} }",
output: "class A { a() {} get [b]() {} }",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("get")
},
{
code: "class A { a() {} static get[b]() {} }",
output: "class A { a() {} static get [b]() {} }",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("get")
},
{
code: "({ get [b]() {} })",
output: "({ get[b]() {} })",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("get")
},
{
code: "class A { a() {} get [b]() {} }",
output: "class A { a() {}get[b]() {} }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("get")
},
{
code: "class A { a() {}static get [b]() {} }",
output: "class A { a() {}static get[b]() {} }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("get")
},
{
code: "({ get[b]() {} })",
output: "({ get [b]() {} })",
options: [override("get", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("get")
},
{
code: "class A { a() {}get[b]() {} }",
output: "class A { a() {} get [b]() {} }",
options: [override("get", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("get")
},
{
code: "({ get [b]() {} })",
output: "({ get[b]() {} })",
options: [override("get", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("get")
},
{
code: "class A { a() {} get [b]() {} }",
output: "class A { a() {}get[b]() {} }",
options: [override("get", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("get")
},
//----------------------------------------------------------------------
// if
//----------------------------------------------------------------------
{
code: "{}if(a) {}",
output: "{} if (a) {}",
errors: expectedBeforeAndAfter("if")
},
{
code: "if (a) {} else if(b) {}",
output: "if (a) {} else if (b) {}",
errors: expectedAfter("if")
},
{
code: "{} if (a) {}",
output: "{}if(a) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("if")
},
{
code: "if(a) {}else if (b) {}",
output: "if(a) {}else if(b) {}",
options: [NEITHER],
errors: unexpectedAfter("if")
},
{
code: "{}if(a) {}",
output: "{} if (a) {}",
options: [override("if", BOTH)],
errors: expectedBeforeAndAfter("if")
},
{
code: "if (a) {}else if(b) {}",
output: "if (a) {}else if (b) {}",
options: [override("if", BOTH)],
errors: expectedAfter("if")
},
{
code: "{} if (a) {}",
output: "{}if(a) {}",
options: [override("if", NEITHER)],
errors: unexpectedBeforeAndAfter("if")
},
{
code: "if(a) {} else if (b) {}",
output: "if(a) {} else if(b) {}",
options: [override("if", NEITHER)],
errors: unexpectedAfter("if")
},
//----------------------------------------------------------------------
// import
//----------------------------------------------------------------------
{
code: "{}import{a} from \"foo\"",
output: "{} import {a} from \"foo\"",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("import")
},
{
code: "{}import a from \"foo\"",
output: "{} import a from \"foo\"",
parserOptions: { sourceType: "module" },
errors: expectedBefore("import")
},
{
code: "{}import* as a from \"a\"",
output: "{} import * as a from \"a\"",
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("import")
},
{
code: "{} import {a}from\"foo\"",
output: "{}import{a}from\"foo\"",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("import")
},
{
code: "{} import *as a from\"foo\"",
output: "{}import*as a from\"foo\"",
options: [NEITHER],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("import")
},
{
code: "{}import{a}from\"foo\"",
output: "{} import {a}from\"foo\"",
options: [override("import", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("import")
},
{
code: "{}import*as a from\"foo\"",
output: "{} import *as a from\"foo\"",
options: [override("import", BOTH)],
parserOptions: { sourceType: "module" },
errors: expectedBeforeAndAfter("import")
},
{
code: "{} import {a} from \"foo\"",
output: "{}import{a} from \"foo\"",
options: [override("import", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("import")
},
{
code: "{} import * as a from \"foo\"",
output: "{}import* as a from \"foo\"",
options: [override("import", NEITHER)],
parserOptions: { sourceType: "module" },
errors: unexpectedBeforeAndAfter("import")
},
//----------------------------------------------------------------------
// in
//----------------------------------------------------------------------
{
code: "for ([foo]in{foo: 0}) {}",
output: "for ([foo] in {foo: 0}) {}",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("in")
},
{
code: "for([foo] in {foo: 0}) {}",
output: "for([foo]in{foo: 0}) {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("in")
},
{
code: "for([foo]in{foo: 0}) {}",
output: "for([foo] in {foo: 0}) {}",
options: [override("in", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("in")
},
{
code: "for ([foo] in {foo: 0}) {}",
output: "for ([foo]in{foo: 0}) {}",
options: [override("in", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("in")
},
//----------------------------------------------------------------------
// instanceof
//----------------------------------------------------------------------
// ignores
//----------------------------------------------------------------------
// let
//----------------------------------------------------------------------
{
code: "{}let[a] = b",
output: "{} let [a] = b",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("let")
},
{
code: "{} let [a] = b",
output: "{}let[a] = b",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("let")
},
{
code: "{}let[a] = b",
output: "{} let [a] = b",
options: [override("let", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("let")
},
{
code: "{} let [a] = b",
output: "{}let[a] = b",
options: [override("let", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("let")
},
//----------------------------------------------------------------------
// new
//----------------------------------------------------------------------
{
code: "{}new foo()",
output: "{} new foo()",
errors: expectedBefore("new")
},
{
code: "{} new foo()",
output: "{}new foo()",
options: [NEITHER],
errors: unexpectedBefore("new")
},
{
code: "{}new foo()",
output: "{} new foo()",
options: [override("new", BOTH)],
errors: expectedBefore("new")
},
{
code: "{} new foo()",
output: "{}new foo()",
options: [override("new", NEITHER)],
errors: unexpectedBefore("new")
},
//----------------------------------------------------------------------
// of
//----------------------------------------------------------------------
{
code: "for ([foo]of{foo: 0}) {}",
output: "for ([foo] of {foo: 0}) {}",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("of")
},
{
code: "for([foo] of {foo: 0}) {}",
output: "for([foo]of{foo: 0}) {}",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("of")
},
{
code: "for([foo]of{foo: 0}) {}",
output: "for([foo] of {foo: 0}) {}",
options: [override("of", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("of")
},
{
code: "for ([foo] of {foo: 0}) {}",
output: "for ([foo]of{foo: 0}) {}",
options: [override("of", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("of")
},
//----------------------------------------------------------------------
// return
//----------------------------------------------------------------------
{
code: "function foo() { {}return+a }",
output: "function foo() { {} return +a }",
errors: expectedBeforeAndAfter("return")
},
{
code: "function foo() { {} return +a }",
output: "function foo() { {}return+a }",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("return")
},
{
code: "function foo() { {}return+a }",
output: "function foo() { {} return +a }",
options: [override("return", BOTH)],
errors: expectedBeforeAndAfter("return")
},
{
code: "function foo() { {} return +a }",
output: "function foo() { {}return+a }",
options: [override("return", NEITHER)],
errors: unexpectedBeforeAndAfter("return")
},
//----------------------------------------------------------------------
// set
//----------------------------------------------------------------------
{
code: "({ set[b](value) {} })",
output: "({ set [b](value) {} })",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("set")
},
{
code: "class A { a() {}set[b](value) {} }",
output: "class A { a() {} set [b](value) {} }",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("set")
},
{
code: "class A { a() {} static set[b](value) {} }",
output: "class A { a() {} static set [b](value) {} }",
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("set")
},
{
code: "({ set [b](value) {} })",
output: "({ set[b](value) {} })",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("set")
},
{
code: "class A { a() {} set [b](value) {} }",
output: "class A { a() {}set[b](value) {} }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("set")
},
{
code: "({ set[b](value) {} })",
output: "({ set [b](value) {} })",
options: [override("set", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedAfter("set")
},
{
code: "class A { a() {}set[b](value) {} }",
output: "class A { a() {} set [b](value) {} }",
options: [override("set", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("set")
},
{
code: "({ set [b](value) {} })",
output: "({ set[b](value) {} })",
options: [override("set", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedAfter("set")
},
{
code: "class A { a() {} set [b](value) {} }",
output: "class A { a() {}set[b](value) {} }",
options: [override("set", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("set")
},
//----------------------------------------------------------------------
// static
//----------------------------------------------------------------------
{
code: "class A { a() {}static[b]() {} }",
output: "class A { a() {} static [b]() {} }",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("static")
},
{
code: "class A { a() {}static get [b]() {} }",
output: "class A { a() {} static get [b]() {} }",
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("static")
},
{
code: "class A { a() {} static [b]() {} }",
output: "class A { a() {}static[b]() {} }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("static")
},
{
code: "class A { a() {} static get[b]() {} }",
output: "class A { a() {}static get[b]() {} }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("static")
},
{
code: "class A { a() {}static[b]() {} }",
output: "class A { a() {} static [b]() {} }",
options: [override("static", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("static")
},
{
code: "class A { a() {} static [b]() {} }",
output: "class A { a() {}static[b]() {} }",
options: [override("static", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("static")
},
//----------------------------------------------------------------------
// super
//----------------------------------------------------------------------
{
code: "class A { a() { {}super[b]; } }",
output: "class A { a() { {} super[b]; } }",
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("super")
},
{
code: "class A { a() { {} super[b]; } }",
output: "class A { a() { {}super[b]; } }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("super")
},
{
code: "class A { a() { {}super[b]; } }",
output: "class A { a() { {} super[b]; } }",
options: [override("super", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("super")
},
{
code: "class A { a() { {} super[b]; } }",
output: "class A { a() { {}super[b]; } }",
options: [override("super", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("super")
},
//----------------------------------------------------------------------
// switch
//----------------------------------------------------------------------
{
code: "{}switch(a) {}",
output: "{} switch (a) {}",
errors: expectedBeforeAndAfter("switch")
},
{
code: "{} switch (a) {}",
output: "{}switch(a) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("switch")
},
{
code: "{}switch(a) {}",
output: "{} switch (a) {}",
options: [override("switch", BOTH)],
errors: expectedBeforeAndAfter("switch")
},
{
code: "{} switch (a) {}",
output: "{}switch(a) {}",
options: [override("switch", NEITHER)],
errors: unexpectedBeforeAndAfter("switch")
},
//----------------------------------------------------------------------
// this
//----------------------------------------------------------------------
{
code: "{}this[a]",
output: "{} this[a]",
errors: expectedBefore("this")
},
{
code: "{} this[a]",
output: "{}this[a]",
options: [NEITHER],
errors: unexpectedBefore("this")
},
{
code: "{}this[a]",
output: "{} this[a]",
options: [override("this", BOTH)],
errors: expectedBefore("this")
},
{
code: "{} this[a]",
output: "{}this[a]",
options: [override("this", NEITHER)],
errors: unexpectedBefore("this")
},
//----------------------------------------------------------------------
// throw
//----------------------------------------------------------------------
{
code: "function foo() { {}throw+a }",
output: "function foo() { {} throw +a }",
errors: expectedBeforeAndAfter("throw")
},
{
code: "function foo() { {} throw +a }",
output: "function foo() { {}throw+a }",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("throw")
},
{
code: "function foo() { {}throw+a }",
output: "function foo() { {} throw +a }",
options: [override("throw", BOTH)],
errors: expectedBeforeAndAfter("throw")
},
{
code: "function foo() { {} throw +a }",
output: "function foo() { {}throw+a }",
options: [override("throw", NEITHER)],
errors: unexpectedBeforeAndAfter("throw")
},
//----------------------------------------------------------------------
// try
//----------------------------------------------------------------------
{
code: "{}try{} finally {}",
output: "{} try {} finally {}",
errors: expectedBeforeAndAfter("try")
},
{
code: "{} try {}finally{}",
output: "{}try{}finally{}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("try")
},
{
code: "{}try{}finally{}",
output: "{} try {}finally{}",
options: [override("try", BOTH)],
errors: expectedBeforeAndAfter("try")
},
{
code: "{} try {} finally {}",
output: "{}try{} finally {}",
options: [override("try", NEITHER)],
errors: unexpectedBeforeAndAfter("try")
},
//----------------------------------------------------------------------
// typeof
//----------------------------------------------------------------------
{
code: "{}typeof foo",
output: "{} typeof foo",
errors: expectedBefore("typeof")
},
{
code: "{} typeof foo",
output: "{}typeof foo",
options: [NEITHER],
errors: unexpectedBefore("typeof")
},
{
code: "{}typeof foo",
output: "{} typeof foo",
options: [override("typeof", BOTH)],
errors: expectedBefore("typeof")
},
{
code: "{} typeof foo",
output: "{}typeof foo",
options: [override("typeof", NEITHER)],
errors: unexpectedBefore("typeof")
},
//----------------------------------------------------------------------
// var
//----------------------------------------------------------------------
{
code: "{}var[a] = b",
output: "{} var [a] = b",
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("var")
},
{
code: "{} var [a] = b",
output: "{}var[a] = b",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("var")
},
{
code: "{}var[a] = b",
output: "{} var [a] = b",
options: [override("var", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBeforeAndAfter("var")
},
{
code: "{} var [a] = b",
output: "{}var[a] = b",
options: [override("var", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBeforeAndAfter("var")
},
//----------------------------------------------------------------------
// void
//----------------------------------------------------------------------
{
code: "{}void foo",
output: "{} void foo",
errors: expectedBefore("void")
},
{
code: "{} void foo",
output: "{}void foo",
options: [NEITHER],
errors: unexpectedBefore("void")
},
{
code: "{}void foo",
output: "{} void foo",
options: [override("void", BOTH)],
errors: expectedBefore("void")
},
{
code: "{} void foo",
output: "{}void foo",
options: [override("void", NEITHER)],
errors: unexpectedBefore("void")
},
//----------------------------------------------------------------------
// while
//----------------------------------------------------------------------
{
code: "{}while(a) {}",
output: "{} while (a) {}",
errors: expectedBeforeAndAfter("while")
},
{
code: "do {}while(a)",
output: "do {} while (a)",
errors: expectedBeforeAndAfter("while")
},
{
code: "{} while (a) {}",
output: "{}while(a) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("while")
},
{
code: "do{} while (a)",
output: "do{}while(a)",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("while")
},
{
code: "{}while(a) {}",
output: "{} while (a) {}",
options: [override("while", BOTH)],
errors: expectedBeforeAndAfter("while")
},
{
code: "do{}while(a)",
output: "do{} while (a)",
options: [override("while", BOTH)],
errors: expectedBeforeAndAfter("while")
},
{
code: "{} while (a) {}",
output: "{}while(a) {}",
options: [override("while", NEITHER)],
errors: unexpectedBeforeAndAfter("while")
},
{
code: "do {} while (a)",
output: "do {}while(a)",
options: [override("while", NEITHER)],
errors: unexpectedBeforeAndAfter("while")
},
//----------------------------------------------------------------------
// with
//----------------------------------------------------------------------
{
code: "{}with(obj) {}",
output: "{} with (obj) {}",
errors: expectedBeforeAndAfter("with")
},
{
code: "{} with (obj) {}",
output: "{}with(obj) {}",
options: [NEITHER],
errors: unexpectedBeforeAndAfter("with")
},
{
code: "{}with(obj) {}",
output: "{} with (obj) {}",
options: [override("with", BOTH)],
errors: expectedBeforeAndAfter("with")
},
{
code: "{} with (obj) {}",
output: "{}with(obj) {}",
options: [override("with", NEITHER)],
errors: unexpectedBeforeAndAfter("with")
},
//----------------------------------------------------------------------
// yield
//----------------------------------------------------------------------
{
code: "function* foo() { {}yield foo }",
output: "function* foo() { {} yield foo }",
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("yield")
},
{
code: "function* foo() { {} yield foo }",
output: "function* foo() { {}yield foo }",
options: [NEITHER],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("yield")
},
{
code: "function* foo() { {}yield foo }",
output: "function* foo() { {} yield foo }",
options: [override("yield", BOTH)],
parserOptions: { ecmaVersion: 6 },
errors: expectedBefore("yield")
},
{
code: "function* foo() { {} yield foo }",
output: "function* foo() { {}yield foo }",
options: [override("yield", NEITHER)],
parserOptions: { ecmaVersion: 6 },
errors: unexpectedBefore("yield")
},
//----------------------------------------------------------------------
// typescript parser
//----------------------------------------------------------------------
// get, set, async decorator keywords shouldn't be detected
{
code: "class Foo { @desc({set a(value) {}, get a() {}, async c() {}}) async[foo]() {} }",
output: "class Foo { @desc({set a(value) {}, get a() {}, async c() {}}) async [foo]() {} }",
errors: expectedAfter("async"),
parser: parser("typescript-parsers/decorator-with-keywords-class-method")
}
]
});
|
$(document).ready(
function()
{
var overall_data;
var linear_structure;
var json_string;
var conversion_factor;
/*
function modbus_statistics_success( data )
{
var keys;
var temp;
var html;
var keys;
var addresses;
var count;
count = 0;
overall_data = data
linear_structure = []
$("#modbus_counter").empty();
keys = Object.keys(data)
html = "";
html += "<h3>Select to clear </h3>";
html += '<div data-role="controlgroup">';
for( i = 0; i < keys.length; i++ )
{
temp_data_string = data[keys[i]]
temp_data_string1 = JSON.parse( temp_data_string )
temp_data_object = JSON.parse( temp_data_string1 )
addresses = Object.keys( temp_data_object )
for( j = 0; j < addresses.length; j++ )
{
element_data = temp_data_object[addresses[j]]
element_data.modbus_address = addresses[j]
element_data.udp_address = keys[i]
linear_structure.push(element_data)
html += '<label for=id'+count+' >Station '+addresses[j]+" Total Msgs -->"+element_data.counts+" Retries -->"+element_data.failures+" Message Errors -->"+element_data.total_failures+" " +"</label>"
html += '<input type=checkbox id=id'+count+' />';
count = count +1
}
}
html += "</div>";
count = 0
$("#modbus_counter").append (html)
for( i = 0; i < keys.length; i++ )
{
for( j = 0; j < addresses.length; j++ )
{
$("#id"+count).checkboxradio();
$("#id"+count).checkboxradio("refresh");
count = count +1;
}
}
}
*/
$("#clear_modbus_counter").bind("click",function(event,ui)
{
var json_data = {}
json_object = {}
json_object["object_name"] = "MODBUS_STATISTICS:"+$("#interface_type").val()
var json_string = JSON.stringify(json_object);
result = confirm("Do you want to make change selected modbus counters");
if( result == true )
{
// making update
$.ajax
({
type: "POST",
url: '/ajax/delete_element',
contentType: "application/json",
dataType: 'json',
async: true,
//json object to sent to the authentication url
data: json_string,
success: function ()
{
alert("Changes Made");
load_data()
},
error: function ()
{
alert('/ajax/delete_element'+" Server Error Change not made");
}
})
}// if
});
function modbus_statistics_success( data )
{
var keys;
var temp;
var html;
var keys;
var addresses;
var count;
count = 0;
overall_data = data
$("#modbus_counter").empty();
keys = Object.keys(data)
html = "";
html += "<h3>Modbus Results for Interface "+$("#interface_type").val() +" </h3>";
html += '<ol>';
for( i = 0; i < keys.length; i++ )
{
temp_data_string = data[keys[i]]
element_data = JSON.parse( temp_data_string )
html += '<li>Address '+element_data.address+" Total Msgs -->"+element_data.counts+" Retries -->"+element_data.failures+" Message Errors -->"+element_data.total_failures+" " +"</li>"
count = count +1
}
html += "</ol>";
$("#modbus_counter").append (html)
}
function load_data(event, ui)
{
var json_data = {}
json_object = {}
json_object["hash_name"] = "MODBUS_STATISTICS:"+$("#interface_type").val()
var json_string = JSON.stringify(json_object);
$.ajax
({
type: "POST",
url: '/ajax/get_redis_all_hkeys',
dataType: 'json',
async: true,
//json object to sent to the authentication url
success: modbus_statistics_success,
contentType: "application/json",
data: json_string,
error: function ()
{
alert('/ajax/get_redis_all_hkeys'+" Server Error Change not made");
}
})
}
load_data();
$("#interface_type").bind("click",function(event,ui)
{
load_data();
});
$("#refresh").bind("click",function(event,ui)
{
load_data();
});
});
|
var iconv = require('iconv-lite'),
cmds = require('./commands');
/**
* Creates a new Printjob object that can process escpos commands
* which can then be printed with an attached USB escpos printer.
*
* @class
*/
var Printjob = function () {
this._queue = [];
}
Printjob.prototype = {
/**
* Add a string of text to the printjob.
*
* @param {string} text Text string to be added to the current printjob.
*/
text: function (text) {
this._queue.push( iconv.encode(text, 'cp437') );
return this;
},
/**
* Add new line(s) to the printjob.
*
* @param {number} [count=1] Number of new lines to be added to the current printjob.
*/
newLine: function (count) {
// DEFAULTS
count = count || 1;
var buf = new Buffer([ cmds.CTL_CR, cmds.CTL_LF ]);
for (var i = 0; i < count; i++) {
this._queue.push(buf);
}
return this;
},
pad: function (count) {
// DEFAULTS
count = count || 1;
var buf = new Buffer([ 0x1b, 0x4a, 0xff, 0x1b, 0x4a, 0xff ]);
for (var i = 0; i < count; i++) {
this._queue.push(buf);
}
return this;
},
/**
* Set text formatting for the current printjob.
*
* @param {string} [format='normal'] Text format (one of: 'normal', 'tall', 'wide')
*/
setTextFormat: function (format) {
// DEFAULTS
format = format.toLowerCase() || 'normal';
var formats = {
normal: cmds.TXT_NORMAL,
tall: cmds.TXT_2HEIGHT,
wide: cmds.TXT_2WIDTH
};
var cmd = formats[ format ];
if (cmd) {
var buf = new Buffer(cmd);
this._queue.push(buf);
}
else {
throw new Error('Text format must be one of: ', Object.keys(formats).join(', '));
}
return this;
},
/**
* Set text alignment for the current printjob.
*
* @param {string} [count='left'] Text alignment (one of: 'left', 'center', 'right')
*/
setTextAlignment: function (align) {
// DEFAULTS
align = align.toLowerCase() || 'left';
var aligns = {
left: cmds.TXT_ALIGN_LT,
center: cmds.TXT_ALIGN_CT,
right: cmds.TXT_ALIGN_RT
};
var cmd = aligns[ align ];
if (cmd) {
var buf = new Buffer(cmd);
this._queue.push(buf);
}
else {
throw new Error('Text alignment must be one of: ', Object.keys(aligns).join(', '));
}
return this;
},
/**
* Set underline for the current printjob.
*
* @param {boolean} [underline=true] Enables/disables underlined text
*/
setUnderline: function (underline) {
// DEFAULTS
if (typeof underline !== 'boolean') {
underline = true;
}
var cmd = underline ? cmds.TXT_UNDERL_ON : cmds.TXT_UNDERL_OFF;
var buf = new Buffer(cmd);
this._queue.push(buf);
return this;
},
/**
* Set text bold for the current printjob.
*
* @param {boolean} [bold=true] Enables/disables bold text
*/
setBold: function (bold) {
// DEFAULTS
if (typeof underline !== 'boolean') {
underline = true;
}
var cmd = underline ? cmds.TXT_BOLD_ON : cmds.TXT_BOLD_OFF;
var buf = new Buffer(cmd);
this._queue.push(buf);
return this;
},
/**
* Set text font for the current printjob.
*
* @param {string} [font='A'] Text font (one of: 'A', 'B')
*/
setFont: function (font) {
// DEFAULTS
font = font.toUpperCase() || 'A';
var fonts = {
A: cmds.TXT_NORMAL,
B: cmds.TXT_2HEIGHT
};
var cmd = fonts[ font ];
if (cmd) {
var buf = new Buffer(cmd);
this._queue.push(buf);
}
else {
throw new Error('Font must be one of: ', Object.keys(fonts).join(', '));
}
return this;
},
separator: function () {
var i = 0
var line = ''
var width = 42;
while (i < width) {
line += '-'
i++
}
return this.text(line);
},
/**
* Cuts paper on the current printjob.
*/
cut: function () {
var buf = new Buffer( cmds.PAPER_FULL_CUT );
this._queue.push(buf);
return this;
},
/**
* Kicks cash drawer on the current printjob.
* Default parameters are for Epson TM-88V from: http://keyhut.com/popopen.htm
*
* @param {number} [pin=2] Pin number used to send the pulse (one of: 2, 5)
* @param {number} [t1=110] Pulse ON time in ms (0 <= t1 <= 510)
* @param {number} [t2=242] Pulse OFF time in ms (0 <= t2 <= 510)
*/
cashdraw: function (pin, t1, t2) {
// DEFAULTS
pin = pin || 2;
t1 = t1 || 110;
t2 = t2 || 242;
var buf = new Buffer(5);
if (pin == 2) {
new Buffer( cmds.CD_KICK_2 ).copy(buf);
}
else if (pin == 5) {
new Buffer( cmds.CD_KICK_5 ).copy(buf);
}
else {
throw new Error('Pin must be one of: 2, 5');
}
if (t1 >= 0 && t2 >= 0 && t1 <= 242 && t2 <= 242) {
// Pulse ON/OFF times in 2ms increments
buf.writeUInt8(t1/2, 3);
buf.writeUInt8(t2/2, 4);
}
else {
throw new Error('Pulse timings must be between 0 and 242 inclusive.');
}
this._queue.push(buf);
return this;
},
printData: function () {
var init = new Buffer( cmds.HW_INIT );
var queue = this._queue.slice(0); // Clone queue
queue.unshift(init); // Prepend init command
return Buffer.concat(queue);
}
}
module.exports = Printjob;
|
/* eslint-env jest */
import path from 'path'
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
const appDir = join(__dirname, '../')
const nextConfig = join(appDir, 'next.config.js')
const addPage = async (page, content) => {
const pagePath = join(appDir, 'pages', page)
await fs.ensureDir(path.dirname(pagePath))
await fs.writeFile(pagePath, content)
}
describe('no-op export', () => {
afterEach(async () => {
await Promise.all(
['.next', 'pages', 'next.config.js', 'out'].map((file) =>
fs.remove(join(appDir, file))
)
)
})
it('should not error for all server-side pages build', async () => {
await addPage(
'_error.js',
`
import React from 'react'
export default class Error extends React.Component {
static async getInitialProps() {
return {
props: {
statusCode: 'oops'
}
}
}
render() {
return 'error page'
}
}
`
)
await addPage(
'[slug].js',
`
export const getStaticProps = () => {
return {
props: {}
}
}
export const getStaticPaths = () => {
return {
paths: [],
fallback: false
}
}
export default function Page() {
return 'page'
}
`
)
const result = await nextBuild(appDir, undefined, {
stderr: 'log',
stdout: 'log',
})
expect(result.code).toBe(0)
})
it('should not error for empty exportPathMap', async () => {
await addPage(
'index.js',
`
export default function Index() {
return 'hello world'
}
`
)
await fs.writeFile(
nextConfig,
`
module.exports = {
exportPathMap() {
return {}
}
}
`
)
const buildResult = await nextBuild(appDir, undefined, {
stderr: 'log',
stdout: 'log',
})
expect(buildResult.code).toBe(0)
const exportResult = await nextExport(appDir, {
outdir: join(appDir, 'out'),
})
expect(exportResult.code).toBe(0)
})
})
|
import React, {Component, PropTypes} from 'react';
import Paper from '../Paper';
import CardExpandable from './CardExpandable';
class Card extends Component {
static propTypes = {
/**
* Can be used to render elements inside the Card.
*/
children: PropTypes.node,
/**
* Override the inline-styles of the container element.
*/
containerStyle: PropTypes.object,
/**
* If true, this card component is expandable. Can be set on any child of the `Card` component.
*/
expandable: PropTypes.bool,
/**
* Whether this card is expanded.
* If `true` or `false` the component is controlled.
* if `null` the component is uncontrolled.
*/
expanded: PropTypes.bool,
/**
* Whether this card is initially expanded.
*/
initiallyExpanded: PropTypes.bool,
/**
* Callback function fired when the `expandable` state of the card has changed.
*
* @param {boolean} newExpandedState Represents the new `expanded` state of the card.
*/
onExpandChange: PropTypes.func,
/**
* If true, this card component will include a button to expand the card. `CardTitle`,
* `CardHeader` and `CardActions` implement `showExpandableButton`. Any child component
* of `Card` can implements `showExpandableButton` or forwards the property to a child
* component supporting it.
*/
showExpandableButton: PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
};
static defaultProps = {
expandable: false,
expanded: null,
initiallyExpanded: false,
};
state = {
expanded: null,
};
componentWillMount() {
this.setState({
expanded: this.props.expanded === null ? this.props.initiallyExpanded === true : this.props.expanded,
});
}
componentWillReceiveProps(nextProps) {
// update the state when the component is controlled.
if (nextProps.expanded !== null)
this.setState({expanded: nextProps.expanded});
}
handleExpanding = (event) => {
event.preventDefault();
const newExpandedState = !this.state.expanded;
// no automatic state update when the component is controlled
if (this.props.expanded === null) {
this.setState({expanded: newExpandedState});
}
if (this.props.onExpandChange) {
this.props.onExpandChange(newExpandedState);
}
};
render() {
const {
style,
containerStyle,
children,
expandable, // eslint-disable-line no-unused-vars
expanded: expandedProp, // eslint-disable-line no-unused-vars
initiallyExpanded, // eslint-disable-line no-unused-vars
onExpandChange, // eslint-disable-line no-unused-vars
...other,
} = this.props;
let lastElement;
const expanded = this.state.expanded;
const newChildren = React.Children.map(children, (currentChild) => {
let doClone = false;
let newChild = undefined;
const newProps = {};
let element = currentChild;
if (!currentChild || !currentChild.props) {
return null;
}
if (expanded === false && currentChild.props.expandable === true)
return;
if (currentChild.props.actAsExpander === true) {
doClone = true;
newProps.onTouchTap = this.handleExpanding;
newProps.style = Object.assign({cursor: 'pointer'}, currentChild.props.style);
}
if (currentChild.props.showExpandableButton === true) {
doClone = true;
newChild = <CardExpandable expanded={expanded} onExpanding={this.handleExpanding} />;
}
if (doClone) {
element = React.cloneElement(currentChild, newProps, currentChild.props.children, newChild);
}
return element;
}, this);
// If the last element is text or a title we should add
// 8px padding to the bottom of the card
const addBottomPadding = (lastElement && (lastElement.type.muiName === 'CardText' ||
lastElement.type.muiName === 'CardTitle'));
const mergedStyles = Object.assign({
zIndex: 1,
}, style);
const containerMergedStyles = Object.assign({
paddingBottom: addBottomPadding ? 8 : 0,
}, containerStyle);
return (
<Paper {...other} style={mergedStyles}>
<div style={containerMergedStyles}>
{newChildren}
</div>
</Paper>
);
}
}
export default Card;
|
import _ from 'lodash';
import { Validator } from 'meteor/jagi:astronomy';
const regExId = /^[23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz]{17}$/;
Validator.create({
name: 'meteorId',
isValid({ value }) {
if (Array.isArray(value)) {
return _.map(value, a => regExId.test(a)).reduce((previous, current) => previous && current, true);
}
return regExId.test(value);
},
resolveError({ name }) {
return `"${name}" is not a meteor id`;
}
});
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/*
* this represents the mobile device, and provides properties for inspecting the model, version, UUID of the
* phone, etc.
* @constructor
*/
function Device() {
this.platform = "palm";
this.version = null;
this.name = null;
this.uuid = null;
this.deviceInfo = null;
};
/*
* A direct call to return device information.
* Example:
* var deviceinfo = JSON.stringify(navigator.device.getDeviceInfo()).replace(/,/g, ', ');
*/
Device.prototype.getDeviceInfo = function() {
return this.deviceInfo;//JSON.parse(PalmSystem.deviceInfo);
};
/*
* needs to be invoked in a <script> nested within the <body> it tells WebOS that the app is ready
TODO: see if we can get this added as in a document.write so that the user doesn't have to explicitly call this method
* Dependencies: Mojo.onKeyUp
* Example:
* navigator.device.deviceReady();
*/
Device.prototype.deviceReady = function() {
// tell webOS this app is ready to show
if (window.PalmSystem) {
// setup keystroke events for forward and back gestures
document.body.addEventListener("keyup", Mojo.onKeyUp, true);
setTimeout(function() { PalmSystem.stageReady(); PalmSystem.activate(); }, 1);
alert = this.showBanner;
}
// fire deviceready event; taken straight from phonegap-iphone
// put on a different stack so it always fires after DOMContentLoaded
window.setTimeout(function () {
var e = document.createEvent('Events');
e.initEvent('deviceready');
document.dispatchEvent(e);
}, 10);
this.setUUID();
this.setDeviceInfo();
};
Device.prototype.setDeviceInfo = function() {
var parsedData = JSON.parse(PalmSystem.deviceInfo);
this.deviceInfo = parsedData;
this.version = parsedData.platformVersion;
this.name = parsedData.modelName;
};
Device.prototype.setUUID = function() {
//this is the only system property webos provides (may change?)
var that = this;
this.service = navigator.service.Request('palm://com.palm.preferences/systemProperties', {
method:"Get",
parameters:{"key": "com.palm.properties.nduid" },
onSuccess: function(result) {
that.uuid = result["com.palm.properties.nduid"];
}
});
};
if (typeof window.device == 'undefined') window.device = navigator.device = new Device();
|
/*global Stem, _, Backbone, JST, $ */
Stem.Views = Stem.Views || {};
(function () {
'use strict';
Stem.Views.SearchAsForm = Backbone.View.extend({
// Markup stored as external template.
template: JST['app/scripts/templates/searchAsForm.ejs'],
// First level element is a `<form>`.
tagName: 'form',
// Use `.search` class to get search form styles.
className: 'search',
// Listen to events that change the input or
// click on the search link to initiate a search.
events: {
'input input': 'changed',
'submit': 'submitted'
},
// Default values for options.
defaults: {
showLabel: true, // Should label be visible
theme: '' // Theme to apply
},
// Options supported by this view
// include:
// - `.theme` for a theme class
// - `.showLabel` set `false` to suppress display of search label
initialize: function (options) {
// Save any options passed to constructor.
this.options = _.extend({}, this.defaults, options);
// If the model changes, we might need to
// update the view.
this.listenTo(this.model, 'change', this.modelUpdated);
// Define a variable to track in-progress
// updates.
this.updating = false;
// Return view for method chaining.
return this;
},
render: function () {
// After normal render, add a11y `role` and
// other hints to make iOS treat the control
// as a search box (without restyling it).
this.$el.html(this.template(this.model.toJSON()))
.attr('role','search')
.attr('action', '.')
.attr('id', _.uniqueId('search_'));
// Set the initial query parameters
if (this.model.get('query')) {
this.$el.find('input').val(this.model.get('query'));
}
// If a theme has been requested, add it
// as a class.
if (this.options.theme) {
this.$el.addClass(this.options.theme);
}
// If the label should be visible, remove
// the screen-reader only class.
if (this.options.showLabel) {
this.$el.find('label').removeClass('util--sr-only');
}
// Return view for method chaining.
return this;
},
// If the user changes the query value, we
// need to update the underlying model.
changed: function(ev) {
// Get the current input value.
var query = $(ev.currentTarget).val();
// Note that we're about to start
// a model update.
this.updating = true;
// Update the model with the current query.
this.model.set('query', query);
},
// If user clicks on the search button,
// pass it up the chain so the search
// can be executed.
submitted: function(ev) {
// Trigger a submit event on this view.
this.trigger('submit', ev);
// Prevent regular form submission.
ev.preventDefault();
},
// If the model has changed due to,
// another view, we update this view.
modelUpdated: function() {
var query = this.model.get('query');
// Only update the view if it's not in
// focus to avoid messing with the users
// while they're typing. Note that we
// have multiple parallel `<input>`
// elements to handle responsive design.
// We do, however, update a view that's
// in focus if we're not in the middle
// of a model update. This update is
// needed, e.g., if the user clicks
// the back button while the focus is
// on the input.
this.$el.find('input').each(function() {
if (!$(this).is(":focus") || !this.updating) {
$(this).val(query);
}
});
// If this event was triggered by
// a model update, that update is now
// finished.
if (this.updating) {
this.updating = false;
}
}
});
})();
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require ckeditor/init
//= require_tree .
|
/// <reference path="./typings/tsd.d.ts" />
import * as React from 'react';
//https://github.com/borisyankov/DefinitelyTyped/issues/5128
React.render(React.createElement("h1", null, "Hello JSX + TypeScript + JSPM"), document.getElementById("app"));
|
// Copyright 2013 Bowery Software, LLC
/**
* @fileoverview Test Key-Value methods.
*/
// Module Dependencies.
var assert = require('assert')
var nock = require('nock')
var token = 'sample_token'
var db = require('../')(token)
// Mock data.
var users = {
steve: {
"name": "Steve Kaliski",
"email": "sjkaliski@gmail.com",
"location": "New York",
"type": "paid",
"gender": "male"
},
david: {
"name": "David Byrd",
"email": "byrd@bowery.io",
"location": "New York",
"type": "paid",
"gender": "male"
}
}
var listResponse = {
"count": 1,
"next": "/v0/users?limit=2&afterKey=002",
"results": [{value: users.steve}]
}
var page2Response = {
"count": 1,
"results": [{value: users.david}]
}
// Override http requests.
var fakeOrchestrate = nock('https://api.orchestrate.io/')
.get('/v0/users/sjkaliski%40gmail.com')
.reply(200, users.steve)
.get('/v0/users')
.reply(200, listResponse, {'Link':'</v0/users?limit=2&afterKey=002>; rel="next"'})
.put('/v0/users/byrd%40bowery.io')
.reply(201)
.put('/v0/users/byrd%40bowery.io')
.reply(201)
.delete('/v0/users/byrd%40bowery.io')
.reply(204)
.delete('/v0/users/byrd%40bowery.io?purge=true')
.reply(204)
.get('/v0/users?afterKey=002')
.reply(200, page2Response)
suite('Key-Value', function () {
test('Get value by key', function (done) {
db.get('users', 'sjkaliski@gmail.com')
.then(function (res) {
assert.equal(200, res.statusCode)
assert.deepEqual(users.steve, res.body)
done()
})
})
test('Get list of values by collection name', function (done) {
db.list('users')
.then(function (res) {
assert.equal(200, res.statusCode)
assert.deepEqual(users.steve, res.body.results[0].value)
assert.equal(true, typeof res.links.next.get == 'function')
done()
})
})
test('Store value at key', function (done) {
db.put('users', 'byrd@bowery.io', users.david)
.then(function (res) {
assert.equal(201, res.statusCode)
done()
})
})
test('Store value at key with conditional', function (done) {
db.put('users', 'byrd@bowery.io', users.david, false)
.then(function (res) {
assert.equal(201, res.statusCode)
done()
})
})
test('Remove value by key', function (done) {
db.remove('users', 'byrd@bowery.io')
.then(function (res) {
assert.equal(204, res.statusCode)
done()
})
})
test('Remove value by key and purge', function (done) {
db.remove('users', 'byrd@bowery.io', true)
.then(function (res) {
assert.equal(204, res.statusCode)
done()
})
})
test('Request collection items afterKey', function (done) {
db.list('users', {afterKey:'002'})
.then(function (res) {
assert.equal(200, res.statusCode)
assert.deepEqual(users.david, res.body.results[0].value)
done()
})
})
})
|
import financial from './financial';
import walk from './walk';
import {skipWeekends} from './filter/skipWeekends';
export default {
filter: {
skipWeekends: skipWeekends
},
financial: financial,
walk: walk
};
|
var archinfo = require('../utils/archinfo.js');
var buildmessage = require('../utils/buildmessage.js');
var buildPluginModule = require('./build-plugin.js');
var colonConverter = require('../utils/colon-converter.js');
var files = require('../fs/files.js');
var compiler = require('./compiler.js');
var linker = require('./linker.js');
var util = require('util');
var _ = require('underscore');
var Profile = require('../tool-env/profile.js').Profile;
import {sha1} from '../fs/watch.js';
import LRU from 'lru-cache';
import Fiber from 'fibers';
import {sourceMapLength} from '../utils/utils.js';
import {Console} from '../console/console.js';
import ImportScanner from './import-scanner.js';
import {cssToCommonJS} from "./css-modules.js";
import { isTestFilePath } from './test-files.js';
// This file implements the new compiler plugins added in Meteor 1.2, which are
// registered with the Plugin.registerCompiler API.
//
// Unlike legacy source handlers (Plugin.registerSourceHandler), compilers run
// in the context of an entire app. That is to say, they don't run when you run
// `meteor publish`; whenever they run, they have access to all the files of
// their type across all packages as well as the app. This allows them to
// implement cross-file and cross-package inclusion, or config files in the app
// that affect how packages are processed, among other possibilities.
//
// Compilers can specify which extensions or filenames they process. They only
// process files in packages (or the app) that directly use the plugin's package
// (or that use it indirectly via the "imply" directive); just because compiler
// plugins act on multiple packages at a time doesn't mean they automatically
// act on all packages in your app.
//
// The CompilerPluginProcessor is the main entry point to this file; it is used
// by the bundler to run all plugins on a target. It doesn't have much
// interesting state and perhaps could have just been a function.
//
// It receives an ordered list of unibuilds (essentially, packages) from the
// bundler. It turns them into an ordered list of PackageSourceBatch objects,
// each of which represents the source files in a single package. Each
// PackageSourceBatch consists of an ordered list of ResourceSlots representing
// the resources in that package. The idea here is that, because Meteor executes
// all JS files in the order produced by the bundler, we need to make sure to
// maintain the order of packages from the bundler and the order of source files
// within a package. Each ResourceSlot represents a resource (either a 'source'
// resource which will be processed by a compiler plugin, or something else like
// a static asset or some JavaScript produced by a legacy source handler), and
// when the compiler plugin calls something like `inputFile.addJavaScript` on a
// file, we replace that source file with the resource produced by the plugin.
//
// InputFile is a wrapper around ResourceSlot that is the object presented to
// the compiler in the plugin. It is part of the documented registerCompiler
// API.
// Cache the (slightly post-processed) results of linker.fullLink.
const CACHE_SIZE = process.env.METEOR_LINKER_CACHE_SIZE || 1024*1024*100;
const CACHE_DEBUG = !! process.env.METEOR_TEST_PRINT_LINKER_CACHE_DEBUG;
const LINKER_CACHE_SALT = 6; // Increment this number to force relinking.
const LINKER_CACHE = new LRU({
max: CACHE_SIZE,
// Cache is measured in bytes. We don't care about servePath.
// Key is JSONification of all options plus all hashes.
length: function (files) {
return files.reduce((soFar, current) => {
return soFar + current.data.length + sourceMapLength(current.sourceMap);
}, 0);
}
});
const serverLibPackages = {
// Make sure fibers is defined, if nothing else.
fibers: true
};
function populateServerLibPackages() {
const devBundlePath = files.getDevBundle();
const nodeModulesPath = files.pathJoin(
devBundlePath, "server-lib", "node_modules"
);
files.readdir(nodeModulesPath).forEach(packageName => {
const packagePath = files.pathJoin(nodeModulesPath, packageName);
const packageStat = files.statOrNull(packagePath);
if (packageStat && packageStat.isDirectory()) {
serverLibPackages[packageName] = true;
}
});
}
try {
populateServerLibPackages();
} catch (e) {
// At least we tried!
}
export class CompilerPluginProcessor {
constructor({
unibuilds,
arch,
sourceRoot,
isopackCache,
linkerCacheDir,
}) {
const self = this;
self.unibuilds = unibuilds;
self.arch = arch;
self.sourceRoot = sourceRoot;
self.isopackCache = isopackCache;
self.linkerCacheDir = linkerCacheDir;
if (self.linkerCacheDir) {
files.mkdir_p(self.linkerCacheDir);
}
}
runCompilerPlugins() {
const self = this;
buildmessage.assertInJob();
// plugin id -> {sourceProcessor, resourceSlots}
var sourceProcessorsWithSlots = {};
var sourceBatches = _.map(self.unibuilds, function (unibuild) {
const { pkg: { name }, arch } = unibuild;
const sourceRoot = name
&& self.isopackCache.getSourceRoot(name, arch)
|| self.sourceRoot;
return new PackageSourceBatch(unibuild, self, {
sourceRoot,
linkerCacheDir: self.linkerCacheDir
});
});
// If we failed to match sources with processors, we're done.
if (buildmessage.jobHasMessages()) {
return [];
}
// Find out which files go with which CompilerPlugins.
_.each(sourceBatches, function (sourceBatch) {
_.each(sourceBatch.resourceSlots, function (resourceSlot) {
var sourceProcessor = resourceSlot.sourceProcessor;
// Skip non-sources.
if (! sourceProcessor) {
return;
}
if (! _.has(sourceProcessorsWithSlots, sourceProcessor.id)) {
sourceProcessorsWithSlots[sourceProcessor.id] = {
sourceProcessor: sourceProcessor,
resourceSlots: []
};
}
sourceProcessorsWithSlots[sourceProcessor.id].resourceSlots.push(
resourceSlot);
});
});
// Now actually run the handlers.
_.each(sourceProcessorsWithSlots, function (data, id) {
var sourceProcessor = data.sourceProcessor;
var resourceSlots = data.resourceSlots;
var jobTitle = [
"processing files with ",
sourceProcessor.isopack.name,
" (for target ", self.arch, ")"
].join('');
Profile.time("plugin "+sourceProcessor.isopack.name, () => {
buildmessage.enterJob({
title: jobTitle
}, function () {
var inputFiles = _.map(resourceSlots, function (resourceSlot) {
return new InputFile(resourceSlot);
});
var markedMethod = buildmessage.markBoundary(
sourceProcessor.userPlugin.processFilesForTarget.bind(
sourceProcessor.userPlugin));
try {
markedMethod(inputFiles);
} catch (e) {
buildmessage.exception(e);
}
});
});
});
return sourceBatches;
}
}
class InputFile extends buildPluginModule.InputFile {
constructor(resourceSlot) {
super();
// We use underscored attributes here because this is user-visible
// code and we don't want users to be accessing anything that we don't
// document.
this._resourceSlot = resourceSlot;
}
getContentsAsBuffer() {
var self = this;
return self._resourceSlot.inputResource.data;
}
getPackageName() {
var self = this;
return self._resourceSlot.packageSourceBatch.unibuild.pkg.name;
}
getPathInPackage() {
var self = this;
return self._resourceSlot.inputResource.path;
}
getFileOptions() {
var self = this;
// XXX fileOptions only exists on some resources (of type "source"). The JS
// resources might not have this property.
return self._resourceSlot.inputResource.fileOptions || {};
}
getArch() {
return this._resourceSlot.packageSourceBatch.processor.arch;
}
getSourceHash() {
return this._resourceSlot.inputResource.hash;
}
/**
* @summary Returns the extension that matched the compiler plugin.
* The longest prefix is preferred.
* @returns {String}
*/
getExtension() {
return this._resourceSlot.inputResource.extension;
}
/**
* @summary Returns a list of symbols declared as exports in this target. The
* result of `api.export('symbol')` calls in target's control file such as
* package.js.
* @memberof InputFile
* @returns {String[]}
*/
getDeclaredExports() {
var self = this;
return self._resourceSlot.packageSourceBatch.unibuild.declaredExports;
}
/**
* @summary Returns a relative path that can be used to form error messages or
* other display properties. Can be used as an input to a source map.
* @memberof InputFile
* @returns {String}
*/
getDisplayPath() {
var self = this;
return self._resourceSlot.packageSourceBatch.unibuild.pkg._getServePath(self.getPathInPackage());
}
/**
* @summary Web targets only. Add a stylesheet to the document. Not available
* for linter build plugins.
* @param {Object} options
* @param {String} options.path The requested path for the added CSS, may not
* be satisfied if there are path conflicts.
* @param {String} options.data The content of the stylesheet that should be
* added.
* @param {String|Object} options.sourceMap A stringified JSON
* sourcemap, in case the stylesheet was generated from a different
* file.
* @memberOf InputFile
* @instance
*/
addStylesheet(options) {
var self = this;
if (options.sourceMap && typeof options.sourceMap === 'string') {
// XXX remove an anti-XSSI header? ")]}'\n"
options.sourceMap = JSON.parse(options.sourceMap);
}
self._resourceSlot.addStylesheet(options);
}
/**
* @summary Add JavaScript code. The code added will only see the
* namespaces imported by this package as runtime dependencies using
* ['api.use'](#PackageAPI-use). If the file being compiled was added
* with the bare flag, the resulting JavaScript won't be wrapped in a
* closure.
* @param {Object} options
* @param {String} options.path The path at which the JavaScript file
* should be inserted, may not be honored in case of path conflicts.
* @param {String} options.data The code to be added.
* @param {String|Object} options.sourceMap A stringified JSON
* sourcemap, in case the JavaScript file was generated from a
* different file.
* @memberOf InputFile
* @instance
*/
addJavaScript(options) {
var self = this;
if (options.sourceMap && typeof options.sourceMap === 'string') {
// XXX remove an anti-XSSI header? ")]}'\n"
options.sourceMap = JSON.parse(options.sourceMap);
}
self._resourceSlot.addJavaScript(options);
}
/**
* @summary Add a file to serve as-is to the browser or to include on
* the browser, depending on the target. On the web, it will be served
* at the exact path requested. For server targets, it can be retrieved
* using `Assets.getText` or `Assets.getBinary`.
* @param {Object} options
* @param {String} options.path The path at which to serve the asset.
* @param {Buffer|String} options.data The data that should be placed in the
* file.
* @param {String} [options.hash] Optionally, supply a hash for the output
* file.
* @memberOf InputFile
* @instance
*/
addAsset(options) {
var self = this;
self._resourceSlot.addAsset(options);
}
/**
* @summary Works in web targets only. Add markup to the `head` or `body`
* section of the document.
* @param {Object} options
* @param {String} options.section Which section of the document should
* be appended to. Can only be "head" or "body".
* @param {String} options.data The content to append.
* @memberOf InputFile
* @instance
*/
addHtml(options) {
var self = this;
self._resourceSlot.addHtml(options);
}
_reportError(message, info) {
if (this.getFileOptions().lazy === true) {
// Files with fileOptions.lazy === true were not explicitly added to
// the source batch via api.addFiles or api.mainModule, so any
// compilation errors should not be fatal until the files are
// actually imported by the ImportScanner. Attempting compilation is
// still important for lazy files that might end up being imported
// later, which is why we defang the error here, instead of avoiding
// compilation preemptively. Note also that exceptions thrown by the
// compiler will still cause build errors.
this._resourceSlot.addError(message, info);
} else {
super._reportError(message, info);
}
}
}
class ResourceSlot {
constructor(unibuildResourceInfo,
sourceProcessor,
packageSourceBatch) {
const self = this;
// XXX ideally this should be an classy object, but it's not.
self.inputResource = unibuildResourceInfo;
// Everything but JS.
self.outputResources = [];
// JS, which gets linked together at the end.
self.jsOutputResources = [];
self.sourceProcessor = sourceProcessor;
self.packageSourceBatch = packageSourceBatch;
if (self.inputResource.type === "source") {
if (sourceProcessor) {
// If we have a sourceProcessor, it will handle the adding of the
// final processed JavaScript.
} else if (self.inputResource.extension === "js") {
// If there is no sourceProcessor for a .js file, add the source
// directly to the output. #HardcodeJs
self.addJavaScript({
// XXX it's a shame to keep converting between Buffer and string, but
// files.convertToStandardLineEndings only works on strings for now
data: self.inputResource.data.toString('utf8'),
path: self.inputResource.path,
hash: self.inputResource.hash,
bare: self.inputResource.fileOptions &&
(self.inputResource.fileOptions.bare ||
// XXX eventually get rid of backward-compatibility "raw" name
// XXX COMPAT WITH 0.6.4
self.inputResource.fileOptions.raw)
});
}
} else {
if (sourceProcessor) {
throw Error("sourceProcessor for non-source? " +
JSON.stringify(unibuildResourceInfo));
}
// Any resource that isn't handled by compiler plugins just gets passed
// through.
if (self.inputResource.type === "js") {
let resource = self.inputResource;
if (! _.isString(resource.sourcePath)) {
resource.sourcePath = self.inputResource.path;
}
if (! _.isString(resource.targetPath)) {
resource.targetPath = resource.sourcePath;
}
self.jsOutputResources.push(resource);
} else {
self.outputResources.push(self.inputResource);
}
}
}
_getOption(name, options) {
if (options && _.has(options, name)) {
return options[name];
}
const fileOptions = this.inputResource.fileOptions;
return fileOptions && fileOptions[name];
}
_isLazy(options) {
let lazy = this._getOption("lazy", options);
if (typeof lazy === "boolean") {
return lazy;
}
// If file.lazy was not previously defined, mark the file lazy if
// it is contained by an imports directory. Note that any files
// contained by a node_modules directory will already have been
// marked lazy in PackageSource#_inferFileOptions. Same for
// non-test files if running (non-full-app) tests (`meteor test`)
if (!this.packageSourceBatch.useMeteorInstall) {
return false;
}
const splitPath = this.inputResource.path.split(files.pathSep);
const isInImports = splitPath.indexOf("imports") >= 0;
if (global.testCommandMetadata &&
(global.testCommandMetadata.isTest ||
global.testCommandMetadata.isAppTest)) {
// test files should always be included, if we're running app
// tests.
return isInImports && !isTestFilePath(this.inputResource.path);
} else {
return isInImports;
}
}
addStylesheet(options) {
const self = this;
if (! self.sourceProcessor) {
throw Error("addStylesheet on non-source ResourceSlot?");
}
const data = files.convertToStandardLineEndings(options.data);
const useMeteorInstall = self.packageSourceBatch.useMeteorInstall;
const sourcePath = this.inputResource.path;
const targetPath = options.path || sourcePath;
const resource = {
refreshable: true,
sourcePath,
targetPath,
servePath: self.packageSourceBatch.unibuild.pkg._getServePath(targetPath),
hash: sha1(data),
lazy: this._isLazy(options),
};
if (useMeteorInstall && resource.lazy) {
// If the current packageSourceBatch supports modules, and this CSS
// file is lazy, add it as a lazy JS module instead of adding it
// unconditionally as a CSS resource, so that it can be imported
// when needed.
resource.type = "js";
resource.data =
new Buffer(cssToCommonJS(data, resource.hash), "utf8");
self.jsOutputResources.push(resource);
} else {
// Eager CSS is added unconditionally to a combined <style> tag at
// the beginning of the <head>. If the corresponding module ever
// gets imported, its module.exports object should be an empty stub,
// rather than a <style> node added dynamically to the <head>.
self.addJavaScript({
...options,
data: "// These styles have already been applied to the document.\n",
lazy: true
});
resource.type = "css";
resource.data = new Buffer(data, 'utf8'),
// XXX do we need to call convertSourceMapPaths here like we did
// in legacy handlers?
resource.sourceMap = options.sourceMap;
self.outputResources.push(resource);
}
}
addJavaScript(options) {
const self = this;
// #HardcodeJs this gets called by constructor in the "js" case
if (! self.sourceProcessor && self.inputResource.extension !== "js") {
throw Error("addJavaScript on non-source ResourceSlot?");
}
let sourcePath = self.inputResource.path;
if (_.has(options, "sourcePath") &&
typeof options.sourcePath === "string") {
sourcePath = options.sourcePath;
}
const targetPath = options.path || sourcePath;
var data = new Buffer(
files.convertToStandardLineEndings(options.data), 'utf8');
self.jsOutputResources.push({
type: "js",
data: data,
sourcePath,
targetPath,
servePath: self.packageSourceBatch.unibuild.pkg._getServePath(targetPath),
// XXX should we allow users to be trusted and specify a hash?
hash: sha1(data),
// XXX do we need to call convertSourceMapPaths here like we did
// in legacy handlers?
sourceMap: options.sourceMap,
// intentionally preserve a possible `undefined` value for files
// in apps, rather than convert it into `false` via `!!`
lazy: self._isLazy(options),
bare: !! self._getOption("bare", options),
mainModule: !! self._getOption("mainModule", options),
});
}
addAsset(options) {
const self = this;
if (! self.sourceProcessor) {
throw Error("addAsset on non-source ResourceSlot?");
}
if (! (options.data instanceof Buffer)) {
if (_.isString(options.data)) {
options.data = new Buffer(options.data);
} else {
throw new Error("'data' option to addAsset must be a Buffer or String.");
}
}
self.outputResources.push({
type: 'asset',
data: options.data,
path: options.path,
servePath: self.packageSourceBatch.unibuild.pkg._getServePath(
options.path),
hash: sha1(options.data),
lazy: self._isLazy(options),
});
}
addHtml(options) {
const self = this;
const unibuild = self.packageSourceBatch.unibuild;
if (! archinfo.matches(unibuild.arch, "web")) {
throw new Error("Document sections can only be emitted to " +
"web targets: " + self.inputResource.path);
}
if (options.section !== "head" && options.section !== "body") {
throw new Error("'section' must be 'head' or 'body': " +
self.inputResource.path);
}
if (typeof options.data !== "string") {
throw new Error("'data' option to appendDocument must be a string: " +
self.inputResource.path);
}
self.outputResources.push({
type: options.section,
data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8'),
lazy: self._isLazy(options),
});
}
addError(message, info) {
// If this file is ever actually imported, only then will we report
// the error. Use this.jsOutputResources because that's what the
// ImportScanner deals with.
this.jsOutputResources.push({
type: "js",
sourcePath: this.inputResource.path,
targetPath: this.inputResource.path,
servePath: this.inputResource.path,
data: new Buffer(
"throw new Error(" + JSON.stringify(message) + ");\n",
"utf8"),
lazy: true,
error: { message, info },
});
}
}
export class PackageSourceBatch {
constructor(unibuild, processor, {
sourceRoot,
linkerCacheDir,
}) {
const self = this;
buildmessage.assertInJob();
self.unibuild = unibuild;
self.processor = processor;
self.sourceRoot = sourceRoot;
self.linkerCacheDir = linkerCacheDir;
self.importExtensions = [".js", ".json"];
var sourceProcessorSet = self._getSourceProcessorSet();
self.resourceSlots = [];
unibuild.resources.forEach(function (resource) {
let sourceProcessor = null;
if (resource.type === "source") {
var extension = resource.extension;
if (extension === null) {
const filename = files.pathBasename(resource.path);
sourceProcessor = sourceProcessorSet.getByFilename(filename);
if (! sourceProcessor) {
buildmessage.error(
`no plugin found for ${ resource.path } in ` +
`${ unibuild.pkg.displayName() }; a plugin for ${ filename } ` +
`was active when it was published but none is now`);
return;
// recover by ignoring
}
} else {
sourceProcessor = sourceProcessorSet.getByExtension(extension);
// If resource.extension === 'js', it's ok for there to be no
// sourceProcessor, since we #HardcodeJs in ResourceSlot.
if (! sourceProcessor && extension !== 'js') {
buildmessage.error(
`no plugin found for ${ resource.path } in ` +
`${ unibuild.pkg.displayName() }; a plugin for *.${ extension } ` +
`was active when it was published but none is now`);
return;
// recover by ignoring
}
self.addImportExtension(extension);
}
}
self.resourceSlots.push(new ResourceSlot(resource, sourceProcessor, self));
});
// Compute imports by merging the exports of all of the packages we
// use. Note that in the case of conflicting symbols, later packages get
// precedence.
//
// We don't get imports from unordered dependencies (since they
// may not be defined yet) or from
// weak/debugOnly/prodOnly/testOnly dependencies (because the
// meaning of a name shouldn't be affected by the non-local
// decision of whether or not an unrelated package in the target
// depends on something).
self.importedSymbolToPackageName = {}; // map from symbol to supplying package name
compiler.eachUsedUnibuild({
dependencies: self.unibuild.uses,
arch: self.processor.arch,
isopackCache: self.processor.isopackCache,
skipUnordered: true,
// don't import symbols from debugOnly, prodOnly and testOnly packages, because
// if the package is not linked it will cause a runtime error.
// the code must access them with `Package["my-package"].MySymbol`.
skipDebugOnly: true,
skipProdOnly: true,
skipTestOnly: true,
}, depUnibuild => {
_.each(depUnibuild.declaredExports, function (symbol) {
// Slightly hacky implementation of test-only exports.
if (! symbol.testOnly || self.unibuild.pkg.isTest) {
self.importedSymbolToPackageName[symbol.name] = depUnibuild.pkg.name;
}
});
});
self.useMeteorInstall =
_.isString(self.sourceRoot) &&
self.processor.isopackCache.uses(self.unibuild.pkg, "modules");
}
addImportExtension(extension) {
extension = extension.toLowerCase();
if (! extension.startsWith(".")) {
extension = "." + extension;
}
if (this.importExtensions.indexOf(extension) < 0) {
this.importExtensions.push(extension);
}
}
_getSourceProcessorSet() {
const self = this;
buildmessage.assertInJob();
var isopack = self.unibuild.pkg;
const activePluginPackages = compiler.getActivePluginPackages(isopack, {
uses: self.unibuild.uses,
isopackCache: self.processor.isopackCache
});
const sourceProcessorSet = new buildPluginModule.SourceProcessorSet(
isopack.displayName(), { hardcodeJs: true });
_.each(activePluginPackages, function (otherPkg) {
otherPkg.ensurePluginsInitialized();
sourceProcessorSet.merge(
otherPkg.sourceProcessors.compiler, {arch: self.processor.arch});
});
return sourceProcessorSet;
}
// Returns a map from package names to arrays of JS output files.
static computeJsOutputFilesMap(sourceBatches) {
const map = new Map;
sourceBatches.forEach(batch => {
const name = batch.unibuild.pkg.name || null;
const inputFiles = [];
batch.resourceSlots.forEach(slot => {
inputFiles.push(...slot.jsOutputResources);
});
map.set(name, {
files: inputFiles,
importExtensions: batch.importExtensions,
});
});
if (! map.has("modules")) {
// In the unlikely event that no package is using the modules
// package, then the map is already complete, and we don't need to
// do any import scanning.
return map;
}
// Append install(<name>) calls to the install-packages.js file in the
// modules package for every Meteor package name used.
map.get("modules").files.some(file => {
if (file.sourcePath !== "install-packages.js") {
return false;
}
const meteorPackageInstalls = [];
map.forEach((info, name) => {
if (! name) return;
meteorPackageInstalls.push(
"install(" + JSON.stringify(name) + ");\n"
);
});
if (meteorPackageInstalls.length === 0) {
return false;
}
file.data = new Buffer(
file.data.toString("utf8") + "\n" +
meteorPackageInstalls.join(""),
"utf8"
);
file.hash = sha1(file.data);
return true;
});
const allMissingNodeModules = Object.create(null);
// Records the subset of allMissingNodeModules that were successfully
// relocated to a source batch that could handle them.
const allRelocatedNodeModules = Object.create(null);
const scannerMap = new Map;
sourceBatches.forEach(batch => {
const name = batch.unibuild.pkg.name || null;
const isApp = ! name;
if (! batch.useMeteorInstall && ! isApp) {
// If this batch represents a package that does not use the module
// system, then we don't need to scan its dependencies.
return;
}
const nodeModulesPaths = [];
_.each(batch.unibuild.nodeModulesDirectories, (nmd, sourcePath) => {
if (! nmd.local) {
// Local node_modules directories will be found by the
// ImportScanner, but we need to tell it about any external
// node_modules directories (e.g. .npm/package/node_modules).
nodeModulesPaths.push(sourcePath);
}
});
const scanner = new ImportScanner({
name,
bundleArch: batch.processor.arch,
extensions: batch.importExtensions,
sourceRoot: batch.sourceRoot,
nodeModulesPaths,
watchSet: batch.unibuild.watchSet,
});
scanner.addInputFiles(map.get(name).files);
if (batch.useMeteorInstall) {
scanner.scanImports();
_.extend(allMissingNodeModules, scanner.allMissingNodeModules);
}
scannerMap.set(name, scanner);
});
function handleMissing(missingNodeModules) {
const missingMap = new Map;
_.each(missingNodeModules, (info, id) => {
const parts = id.split("/");
let name = null;
if (parts[0] === "meteor") {
if (parts.length > 2) {
name = parts[1];
parts[1] = ".";
id = parts.slice(1).join("/");
} else {
return;
}
}
if (! scannerMap.has(name)) {
return;
}
if (! missingMap.has(name)) {
missingMap.set(name, {});
}
const missing = missingMap.get(name);
if (! _.has(missing, id) ||
! info.possiblySpurious) {
// Allow any non-spurious identifier to replace an existing
// possibly spurious identifier.
missing[id] = info;
}
});
const nextMissingNodeModules = Object.create(null);
missingMap.forEach((ids, name) => {
const { newlyAdded, newlyMissing } =
scannerMap.get(name).addNodeModules(ids);
_.extend(allRelocatedNodeModules, newlyAdded);
_.extend(nextMissingNodeModules, newlyMissing);
});
if (! _.isEmpty(nextMissingNodeModules)) {
handleMissing(nextMissingNodeModules);
}
}
handleMissing(allMissingNodeModules);
_.each(allRelocatedNodeModules, (info, id) => {
delete allMissingNodeModules[id];
});
this._warnAboutMissingModules(allMissingNodeModules);
scannerMap.forEach((scanner, name) => {
const isApp = ! name;
if (isApp) {
const appFilesWithoutNodeModules = [];
scanner.getOutputFiles().forEach(file => {
const parts = file.installPath.split("/");
const nodeModulesIndex = parts.indexOf("node_modules");
if (nodeModulesIndex === -1 || (nodeModulesIndex === 0 &&
parts[1] === "meteor")) {
appFilesWithoutNodeModules.push(file);
} else {
// This file is going to be installed in a node_modules
// directory, so we move it to the modules bundle so that it
// can be imported by any package that uses the modules
// package. Note that this includes all files within any
// node_modules directory in the app, even though packages in
// client/node_modules will not be importable by Meteor
// packages, because it's important for all npm packages in
// the app to share the same limited scope (i.e. the scope of
// the modules package).
map.get("modules").files.push(file);
}
});
map.get(null).files = appFilesWithoutNodeModules;
} else {
map.get(name).files = scanner.getOutputFiles();
}
});
return map;
}
static _warnAboutMissingModules(missingNodeModules) {
const topLevelMissingIDs = {};
const warnings = [];
_.each(missingNodeModules, (info, id) => {
if (info.packageName) {
// Silence warnings generated by Meteor packages, since package
// authors can be trusted to test their packages, and may have
// different/better approaches to ensuring their dependencies are
// available. This blanket check makes some of the checks below
// redundant, but I would rather create a bit of dead code than
// risk introducing bugs when/if this check is reverted.
return;
}
if (info.possiblySpurious) {
// Silence warnings for missing dependencies in Browserify/Webpack
// bundles, since we can reasonably conclude at this point that
// they are false positives.
return;
}
if (id in serverLibPackages &&
archinfo.matches(info.bundleArch, "os")) {
// Packages in dev_bundle/server-lib/node_modules can always be
// resolved at runtime on the server, so we don't need to warn
// about them here.
return;
}
if (id === "meteor-node-stubs" &&
info.packageName === "modules" &&
info.parentPath.endsWith("stubs.js")) {
// Don't warn about the require("meteor-node-stubs") call in
// packages/modules/stubs.js.
return;
}
const parts = id.split("/");
if ("./".indexOf(id.charAt(0)) < 0) {
const packageDir = parts[0];
if (packageDir === "meteor") {
// Don't print warnings for uninstalled Meteor packages.
return;
}
if (packageDir === "babel-runtime") {
// Don't print warnings for babel-runtime/helpers/* modules,
// since we provide most of those.
return;
}
if (! _.has(topLevelMissingIDs, packageDir)) {
// This information will be used to recommend installing npm
// packages below.
topLevelMissingIDs[packageDir] = id;
}
if (id.startsWith("meteor-node-stubs/deps/")) {
// Instead of printing a warning that meteor-node-stubs/deps/fs
// is missing, warn about the "fs" module, but still recommend
// installing meteor-node-stubs via npm below.
id = parts.slice(2).join("/");
}
} else if (info.packageName) {
// Disable warnings about relative module resolution failures in
// Meteor packages, since there's not much the application
// developer can do about those.
return;
}
warnings.push(` ${JSON.stringify(id)} in ${
info.parentPath} (${info.bundleArch})`);
});
if (warnings.length > 0) {
Console.rawWarn("\nUnable to resolve some modules:\n\n");
warnings.forEach(text => Console.warn(text));
Console.warn();
const topLevelKeys = Object.keys(topLevelMissingIDs);
if (topLevelKeys.length > 0) {
Console.warn("If you notice problems related to these missing modules, consider running:");
Console.warn();
Console.warn(" meteor npm install --save " + topLevelKeys.join(" "));
Console.warn();
}
}
}
// Called by bundler's Target._emitResources. It returns the actual resources
// that end up in the program for this package. By this point, it knows what
// its dependencies are and what their exports are, so it can set up
// linker-style imports and exports.
getResources({
files: jsResources,
importExtensions = [".js", ".json"],
}) {
buildmessage.assertInJob();
function flatten(arrays) {
return Array.prototype.concat.apply([], arrays);
}
const resources = flatten(_.pluck(this.resourceSlots, 'outputResources'));
resources.push(...this._linkJS(jsResources || flatten(
_.pluck(this.resourceSlots, 'jsOutputResources')
), this.useMeteorInstall && {
extensions: importExtensions
}));
return resources;
}
_linkJS(jsResources, meteorInstallOptions) {
const self = this;
buildmessage.assertInJob();
var bundleArch = self.processor.arch;
// Run the linker.
const isApp = ! self.unibuild.pkg.name;
const isWeb = archinfo.matches(self.unibuild.arch, "web");
const linkerOptions = {
useGlobalNamespace: isApp,
meteorInstallOptions,
// I was confused about this, so I am leaving a comment -- the
// combinedServePath is either [pkgname].js or [pluginName]:plugin.js.
// XXX: If we change this, we can get rid of source arch names!
combinedServePath: isApp ? "/app.js" :
"/packages/" + colonConverter.convert(
self.unibuild.pkg.name +
(self.unibuild.kind === "main" ? "" : (":" + self.unibuild.kind)) +
".js"),
name: self.unibuild.pkg.name || null,
declaredExports: _.pluck(self.unibuild.declaredExports, 'name'),
imports: self.importedSymbolToPackageName,
// XXX report an error if there is a package called global-imports
importStubServePath: isApp && '/packages/global-imports.js',
includeSourceMapInstructions: isWeb,
noLineNumbers: !isWeb
};
const cacheKey = sha1(JSON.stringify({
LINKER_CACHE_SALT,
linkerOptions,
files: jsResources.map((inputFile) => {
return {
hash: inputFile.hash,
installPath: inputFile.installPath,
sourceMap: !! inputFile.sourceMap,
mainModule: inputFile.mainModule,
imported: inputFile.imported,
lazy: inputFile.lazy,
bare: inputFile.bare,
};
})
}));
{
const inMemoryCached = LINKER_CACHE.get(cacheKey);
if (inMemoryCached) {
if (CACHE_DEBUG) {
console.log('LINKER IN-MEMORY CACHE HIT:',
linkerOptions.name, bundleArch);
}
return inMemoryCached;
}
}
const cacheFilename = self.linkerCacheDir && files.pathJoin(
self.linkerCacheDir, cacheKey + '.cache');
// The return value from _linkJS includes Buffers, but we want everything to
// be JSON for writing to the disk cache. This function converts the string
// version to the Buffer version.
function bufferifyJSONReturnValue(resources) {
resources.forEach((r) => {
r.data = new Buffer(r.data, 'utf8');
});
}
if (cacheFilename) {
let diskCached = null;
try {
diskCached = files.readJSONOrNull(cacheFilename);
} catch (e) {
// Ignore JSON parse errors; pretend there was no cache.
if (!(e instanceof SyntaxError)) {
throw e;
}
}
if (diskCached && diskCached instanceof Array) {
// Fix the non-JSON part of our return value.
bufferifyJSONReturnValue(diskCached);
if (CACHE_DEBUG) {
console.log('LINKER DISK CACHE HIT:', linkerOptions.name, bundleArch);
}
// Add the bufferized value of diskCached to the in-memory LRU cache
// so we don't have to go to disk next time.
LINKER_CACHE.set(cacheKey, diskCached);
return diskCached;
}
}
if (CACHE_DEBUG) {
console.log('LINKER CACHE MISS:', linkerOptions.name, bundleArch);
}
// nb: linkedFiles might be aliased to an entry in LINKER_CACHE, so don't
// mutate anything from it.
let canCache = true;
let linkedFiles = null;
buildmessage.enterJob('linking', () => {
linkedFiles = linker.fullLink(jsResources, linkerOptions);
if (buildmessage.jobHasMessages()) {
canCache = false;
}
});
// Add each output as a resource
const ret = linkedFiles.map((file) => {
const sm = (typeof file.sourceMap === 'string')
? JSON.parse(file.sourceMap) : file.sourceMap;
return {
type: "js",
// This is a string... but we will convert it to a Buffer
// before returning from the method (but after writing
// to cache).
data: file.source,
servePath: file.servePath,
sourceMap: sm
};
});
let retAsJSON;
if (canCache && cacheFilename) {
retAsJSON = JSON.stringify(ret);
}
// Convert strings to buffers, now that we've serialized it.
bufferifyJSONReturnValue(ret);
if (canCache) {
LINKER_CACHE.set(cacheKey, ret);
if (cacheFilename) {
// Write asynchronously.
Fiber(() => files.writeFileAtomically(cacheFilename, retAsJSON)).run();
}
}
return ret;
}
}
_.each([
"getResources",
"_linkJS",
], method => {
const proto = PackageSourceBatch.prototype;
proto[method] = Profile(
"PackageSourceBatch#" + method,
proto[method]
);
});
// static methods to measure in profile
_.each([
"computeJsOutputFilesMap"
], method => {
PackageSourceBatch[method] = Profile(
"PackageSourceBatch." + method,
PackageSourceBatch[method]);
});
|
import styled from 'styled-components';
const Body = styled.p`
color: black;
width: 85%;
&:hover, &:active, &:focus {
color: #FF80AB;
}
`;
export default Body;
|
define(function(){
function Product(name, type, amount){
this.name = name || 'Producto';
this.type = type || 'Tipo';
this.amount = amount || 'Costo';
}
return Product;
});
|
// > Spec Header
{
$id: 'header',
$specs: [],
[uuid-header]: {
$module: 'ui/basic/header',
$params: { heading: '2' }
},
header: {
$module: 'view/header',
$params: [{
views: ['$bone![uuid-header]']
}]
}
}
// > Spec Footer
{
$id: 'footer',
$specs: [],
[uuid-paragraph]: {
$module: 'ui/basic/paragraph',
$params: { content: 'Copyright' }
},
footer: {
$module: 'view/footer',
$params: [{
views: ['$bone![uuid-paragraph]']
}]
}
}
// > Spec Main
requires views.pages.breadcrumb.BreadCrumbItem
{
$id: 'main',
$specs: ['header', 'footer'],
[uuid-container]: {
$module: 'ui/container',
$params: { cls: 'content' }
},
breadcrumbs: {
$module: 'view/common/breadcrumbs',
$params: { type: BreadCrumbItem }
},
$actions: [
{ '$bone!application.render': [] }
]
}
// > Spec Home
{
$id: 'home',
$specs: ['main'],
[uuid-header]: {
$module: 'ui/basic/header',
$params: {
heading: 5,
title: 'Home'
}
},
home: {
$module: 'view/pages/home',
$params: {
views: ['$bone!header', '$bone!footer', '$bone![uuid-header]']
}
},
$actions: [
{ '$bone!home.add': [] }
]
}
|
const DrawCard = require('../../drawcard.js');
class RenlyBaratheon extends DrawCard {
setupCardAbilities(ability) {
this.persistentEffect({
targetController: 'current',
effect: ability.effects.reduceFirstMarshalledCardCostEachRound(1, card => (
card.getType() === 'character' &&
!card.isFaction('baratheon')
))
});
}
}
RenlyBaratheon.code = '02007';
module.exports = RenlyBaratheon;
|
/** @jsx react.DOM */
"use strict";
var react = require('react');
var App = require('./components/App');
react.renderComponent(
App(),
document.body
);
|
var db = require( '../config' );
require( './tip' );
require( './ingredient' );
require( './ingredientstep' );
require( './tool' );
require( './steptool' );
require( './user' );
require( './stepuser' );
var Step = db.Model.extend( {
tableName: 'steps',
ingredients: function () {
return this.belongsToMany( 'Ingredient' ).through( 'IngredientStep' ).withPivot( 'qty' );
},
tools: function () {
return this.belongsToMany( 'Tool' ).through( 'StepTool' );
},
tips: function () {
return this.hasMany( 'Tip' );
},
done: function () {
return this.belongsToMany( 'User' ).through( 'StepUser' ).withPivot( 'done' );
}
}, {
newStep: function ( options ) {
return new this( options ).save();
},
fetchStepbyId: function ( id ) {
return new this( { id: id } ).fetch( {
require: true,
withRelated: [
'ingredients',
'tools',
'tips'
],
});
},
});
module.exports = db.model( 'Step', Step ); |
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Search = mongoose.model('Search');
/**
* Globals
*/
var user, search;
/**
* Unit tests
*/
describe('Search Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
search = new Search({
name: 'Search Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return search.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
search.name = '';
return search.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Search.remove().exec();
User.remove().exec();
done();
});
}); |
var keystone = require('keystone'),
Types = keystone.Field.Types;
var Consultingservice = new keystone.List('Consultingservice', {
autokey: { from: 'name', path: 'key' }
});
Consultingservice.add({
consultingService:{type:String},
consultingServiceimage:{ type: Types.CloudinaryImage},
consultingServicetext:{ type: Types.Textarea, initial: true },
});
/**
Registration
============
*/
Consultingservice.addPattern('standard meta');
Consultingservice.register(); |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var Debug = require('./Debug-a8010bfa.js');
require('./turn-order-f57ce2a9.js');
require('immer');
require('./reducer-85e302af.js');
require('flatted');
require('./ai-69af8a6d.js');
exports.Debug = Debug.Debug;
|
$(document).ready(
function()
{
var ref_flow_meter;
var conversion_factor_array;
var conversion_factor_index;
var conversion_factor;
var g,h,i
var alarm_data;
var queue_interval_id;
var nintervalId;
var data = [];
var t = new Date();
for (var i = 100; i >= 0 ; i--)
{
var x = new Date(t.getTime() - i * 60000);
data.push([x,0]);
}
var hh = new Dygraph(document.getElementById("div_g"), data,
{
width : $(window).width(),
height : $(window).height()*.65,
drawPoints: true,
showRoller: true,
valueRange: [0, 40 ],
labels: ['Time', 'GPM']
});
var strip_chart_update = function(data)
{
hh.updateOptions( { 'file': data } );
}
$("#flow_meter" ).bind( "change", function(event, ui)
{
ref_flow_meter = $("#flow_meter")[0].selectedIndex +1;
conversion_factor_index = $("#flow_meter")[0].selectedIndex;
conversion_factor = conversion_factor_array[ conversion_factor_index ];
ajax_request();
});
var ajax_success = function(data)
{
var temp
var temp_1
var tempDate
tempDate = new Date()
temp = data;
temp_2 = [];
var t = new Date();
for ( i = 0; i < data.length ; i++)
{
var x = new Date(t.getTime() - (data.length -i) * 60000);
temp_2.push([x,Number(temp[i])*conversion_factor ]);
}
strip_chart_update( temp_2 )
}
var ajax_request = function()
{
var data_object;
var data_string;
var data_object = ref_flow_meter;
data_string = JSON.stringify( data_object );
$.ajax
({
type: "GET",
url: '/ajax/get_flow_queue_data',
dataType: 'json',
async: true,
//json object to sent to the authentication url
data: data_string,
success: ajax_success,
error: function ()
{
alert('/ajax/get_flow_queue_data'+" Server Error Request Not Successful");
}
})
}
function flow_sensor_success( data )
{
var length;
var i;
var flow_meter
flow_meter = $("#flow_meter");
length = data.length;
flow_meter.empty()
ref_flow_meter = 1;
conversion_factor_array = []
for( i= 0; i < length; i++ )
{
flow_meter.append('<option value='+(i+1)+'>'+data[i][0]+'</option>');
conversion_factor_array.push(data[i][1])
}
conversion_factor_index = 0;
conversion_factor = conversion_factor_array[ conversion_factor_index ];
flow_meter.selectedIndex = 0;
flow_meter.selectmenu();
flow_meter.selectmenu("refresh");
ajax_request();
}
var flow_sensor_request = function()
{
$.ajax
({
type: "GET",
url: '/ajax/flow_sensor_names',
dataType: 'json',
async: true,
//json object to sent to the authentication url
data: [],
success: flow_sensor_success,
error: function ()
{
alert('/ajax/flow_sensor_names'+" Server Error Request Not Successful");
}
})
}
flow_sensor_request();
$("#back").button();
$("#refresh").bind("click",function(event,ui)
{
ajax_request();
});
})
|
"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 _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var React = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _clsx = _interopRequireDefault(require("clsx"));
var _withStyles = _interopRequireDefault(require("../styles/withStyles"));
var _ListContext = _interopRequireDefault(require("./ListContext"));
var styles = {
/* Styles applied to the root element. */
root: {
listStyle: 'none',
margin: 0,
padding: 0,
position: 'relative'
},
/* Styles applied to the root element if `disablePadding={false}`. */
padding: {
paddingTop: 8,
paddingBottom: 8
},
/* Styles applied to the root element if dense. */
dense: {},
/* Styles applied to the root element if a `subheader` is provided. */
subheader: {
paddingTop: 0
}
};
exports.styles = styles;
var List = /*#__PURE__*/React.forwardRef(function List(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'ul' : _props$component,
_props$dense = props.dense,
dense = _props$dense === void 0 ? false : _props$dense,
_props$disablePadding = props.disablePadding,
disablePadding = _props$disablePadding === void 0 ? false : _props$disablePadding,
subheader = props.subheader,
other = (0, _objectWithoutProperties2.default)(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]);
var context = React.useMemo(function () {
return {
dense: dense
};
}, [dense]);
return /*#__PURE__*/React.createElement(_ListContext.default.Provider, {
value: context
}, /*#__PURE__*/React.createElement(Component, (0, _extends2.default)({
className: (0, _clsx.default)(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader),
ref: ref
}, other), subheader, children));
});
process.env.NODE_ENV !== "production" ? List.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.elementType,
/**
* If `true`, compact vertical padding designed for keyboard and mouse input will be used for
* the list and list items.
* The prop is available to descendant components as the `dense` context.
*/
dense: _propTypes.default.bool,
/**
* If `true`, vertical padding will be removed from the list.
*/
disablePadding: _propTypes.default.bool,
/**
* The content of the subheader, normally `ListSubheader`.
*/
subheader: _propTypes.default.node
} : void 0;
var _default = (0, _withStyles.default)(styles, {
name: 'MuiList'
})(List);
exports.default = _default; |
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import { isFragment } from 'react-is';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
display: 'flex',
justifyContent: 'center',
height: 56,
backgroundColor: theme.palette.background.paper
}
};
};
var BottomNavigation = React.forwardRef(function BottomNavigation(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
onChange = props.onChange,
_props$showLabels = props.showLabels,
showLabels = _props$showLabels === void 0 ? false : _props$showLabels,
value = props.value,
other = _objectWithoutProperties(props, ["children", "classes", "className", "component", "onChange", "showLabels", "value"]);
return React.createElement(Component, _extends({
className: clsx(classes.root, className),
ref: ref
}, other), React.Children.map(children, function (child, childIndex) {
if (!React.isValidElement(child)) {
return null;
}
if (process.env.NODE_ENV !== 'production') {
if (isFragment(child)) {
console.error(["Material-UI: the BottomNavigation component doesn't accept a Fragment as a child.", 'Consider providing an array instead.'].join('\n'));
}
}
var childValue = child.props.value === undefined ? childIndex : child.props.value;
return React.cloneElement(child, {
selected: childValue === value,
showLabel: child.props.showLabel !== undefined ? child.props.showLabel : showLabels,
value: childValue,
onChange: onChange
});
}));
});
process.env.NODE_ENV !== "production" ? BottomNavigation.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.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* Callback fired when the value changes.
*
* @param {object} event The event source of the callback.
* @param {any} value We default to the index of the child.
*/
onChange: PropTypes.func,
/**
* If `true`, all `BottomNavigationAction`s will show their labels.
* By default, only the selected `BottomNavigationAction` will show its label.
*/
showLabels: PropTypes.bool,
/**
* The value of the currently selected `BottomNavigationAction`.
*/
value: PropTypes.any
} : void 0;
export default withStyles(styles, {
name: 'MuiBottomNavigation'
})(BottomNavigation); |
/**
* rcmSwitchUserAdmin
*/
angular.module('rcmSwitchUser').directive(
'rcmSwitchUserAdmin',
[
'rcmSwitchUserAdminService',
function (
rcmSwitchUserAdminService
) {
return {
link: rcmSwitchUserAdminService.link,
scope: rcmSwitchUserAdminService.scope,
template: '' +
'<rcm-switch-user-switch-to-user' +
' loading="loading"' +
' is-su="isSu"' +
' impersonated-user="impersonatedUser"' +
' switch-back-method="switchBackMethod"' +
' show-switch-to-user-name-field="propShowSwitchToUserNameField"' +
' switch-to-user-name="propSwitchToUserName"' +
' switch-to-user-name-button-label="propSwitchToUserNameButtonLabel"' +
' switch-back-button-label="propSwitchBackButtonLabel"' +
' su-user-password="suUserPassword"' +
' switch-user-info-content-prefix="propSwitchUserInfoContentPrefix"' +
' message="message"' +
' on-switch-to="switchTo"' +
' on-switch-back="switchBack"' +
'>' +
'</rcm-switch-user-switch-to-user>'
}
}
]
);
|
(function($) {
function checkCorrection(ev, ui) {
var feedbackShowCorrection = $('input[name=show_correction]:checkbox:checked').val();
var inputSolution = $('input[name=show_solution]:checkbox');
var inputSolutionParent = inputSolution.parent().parent().parent();
var inputAnswerFeedback = $('input[name=answer_feedback_option]:checkbox');
var inputAnswerFeedbackParent = inputAnswerFeedback.parent().parent().parent();
if (feedbackShowCorrection == 1) {
inputSolutionParent.show();
inputAnswerFeedbackParent.show();
} else {
inputSolution.prop('checked', false);
inputSolutionParent.hide();
inputAnswerFeedback.prop('checked', false);
inputAnswerFeedbackParent.hide();
$('select[name=show_answer_feedback]').val(1);
}
checkAnswerFeedback();
}
function checkFeedback(ev, ui) {
var feedbackShowScore = $('input[name=show_score]:checkbox:checked').val();
var feedbackShowCorrection = $('input[name=show_correction]:checkbox:checked').val();
var feedbackShowSolution = $('input[name=show_solution]:checkbox:checked').val();
var feedbackShowAnswerFeedback = $('input[name=answer_feedback_option]:checkbox:checked').val();
var selectFeedbackLocation = $('select[name=feedback_location]');
var row = selectFeedbackLocation.parent().parent().parent();
if (feedbackShowScore == 1 || feedbackShowCorrection == 1 || feedbackShowSolution == 1 || feedbackShowAnswerFeedback == 1) {
row.show();
} else if (feedbackShowScore != 1 && feedbackShowCorrection != 1 && feedbackShowSolution != 1 && feedbackShowAnswerFeedback != 1) {
selectFeedbackLocation.val(1);
row.hide();
}
}
function checkAnswerFeedback(ev, ui) {
var feedbackShowAnswerFeedback = $('input[name=answer_feedback_option]:checkbox:checked').val();
if (feedbackShowAnswerFeedback == 1) {
$("span#answer_feedback_enabled").show();
} else if (feedbackShowAnswerFeedback != 1) {
$("span#answer_feedback_enabled").hide();
}
}
function checkSolution(ev, ui) {
var feedbackShowSolution = $('input[name=show_solution]:checkbox:checked').val();
if (feedbackShowSolution == 1) {
$('select[name=show_answer_feedback] option').show();
} else if (feedbackShowSolution != 1) {
$('select[name=show_answer_feedback]').val(1);
$('select[name=show_answer_feedback] option[value!="1"][value!="2"]').hide();
}
}
$(document).ready(function() {
$(document).on('click', 'input[name=show_correction]:checkbox', checkCorrection);
checkCorrection();
$(document).on('click', 'input[name=show_score]:checkbox, input[name=show_correction]:checkbox, input[name=show_solution]:checkbox, input[name=answer_feedback_option]:checkbox', checkFeedback);
checkFeedback();
$(document).on('click', 'input[name=answer_feedback_option]:checkbox', checkAnswerFeedback);
checkAnswerFeedback();
$(document).on('click', 'input[name=show_solution]:checkbox', checkSolution);
checkSolution();
});
})(jQuery); |
/**!
*
* Copyright (c) 2015-2016 Cisco Systems, Inc. See LICENSE file.
*/
'use strict';
require('./client/services/avatar');
require('./client/services/board');
require('./client/services/bot');
require('./client/services/conversation');
require('./client/services/encryption');
require('./client/services/feature');
require('./client/services/flagging');
require('./client/services/metrics');
require('./client/services/support');
require('./client/services/search');
require('./client/services/team');
require('./client/services/mashups');
require('./client/services/user');
var Spark = require('./spark-core');
module.exports = Spark;
|
'use strict';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $parseMinErr = minErr('$parse');
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor('alert("evil JS code")')
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
// native objects.
//
// See https://docs.angularjs.org/guide/security
function ensureSafeMemberName(name, fullExpression) {
if (name === "__defineGetter__" || name === "__defineSetter__"
|| name === "__lookupGetter__" || name === "__lookupSetter__"
|| name === "__proto__") {
throw $parseMinErr('isecfld',
'Attempting to access a disallowed field in Angular expressions! '
+ 'Expression: {0}', fullExpression);
}
return name;
}
function getStringValue(name) {
// Property names must be strings. This means that non-string objects cannot be used
// as keys in an object. Any non-string object, including a number, is typecasted
// into a string via the toString method.
// -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
//
// So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
// to a string. It's not always possible. If `name` is an object and its `toString` method is
// 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
//
// TypeError: Cannot convert object to primitive value
//
// For performance reasons, we don't catch this error here and allow it to propagate up the call
// stack. Note that you'll get the same error in JavaScript if you try to access a property using
// such a 'broken' object as a key.
return name + '';
}
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isWindow(obj)
obj.window === obj) {
throw $parseMinErr('isecwindow',
'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isElement(obj)
obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// block Object so that we can't get hold of dangerous Object.* methods
obj === Object) {
throw $parseMinErr('isecobj',
'Referencing Object in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
return obj;
}
var CALL = Function.prototype.call;
var APPLY = Function.prototype.apply;
var BIND = Function.prototype.bind;
function ensureSafeFunction(obj, fullExpression) {
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (obj === CALL || obj === APPLY || obj === BIND) {
throw $parseMinErr('isecff',
'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
}
function ensureSafeAssignContext(obj, fullExpression) {
if (obj) {
if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
throw $parseMinErr('isecaf',
'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
}
}
}
var OPERATORS = createMap();
forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
/////////////////////////////////////////
/**
* @constructor
*/
var Lexer = function(options) {
this.options = options;
};
Lexer.prototype = {
constructor: Lexer,
lex: function(text) {
this.text = text;
this.index = 0;
this.tokens = [];
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (ch === '"' || ch === "'") {
this.readString(ch);
} else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
this.readNumber();
} else if (this.isIdentifierStart(this.peekMultichar())) {
this.readIdent();
} else if (this.is(ch, '(){}[].,;:?')) {
this.tokens.push({index: this.index, text: ch});
this.index++;
} else if (this.isWhitespace(ch)) {
this.index++;
} else {
var ch2 = ch + this.peek();
var ch3 = ch2 + this.peek(2);
var op1 = OPERATORS[ch];
var op2 = OPERATORS[ch2];
var op3 = OPERATORS[ch3];
if (op1 || op2 || op3) {
var token = op3 ? ch3 : (op2 ? ch2 : ch);
this.tokens.push({index: this.index, text: token, operator: true});
this.index += token.length;
} else {
this.throwError('Unexpected next character ', this.index, this.index + 1);
}
}
}
return this.tokens;
},
is: function(ch, chars) {
return chars.indexOf(ch) !== -1;
},
peek: function(i) {
var num = i || 1;
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
},
isNumber: function(ch) {
return ('0' <= ch && ch <= '9') && typeof ch === "string";
},
isWhitespace: function(ch) {
// IE treats non-breaking space as \u00A0
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
},
isIdentifierStart: function(ch) {
return this.options.isIdentifierStart ?
this.options.isIdentifierStart(ch, this.codePointAt(ch)) :
this.isValidIdentifierStart(ch);
},
isValidIdentifierStart: function(ch) {
return ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' === ch || ch === '$');
},
isIdentifierContinue: function(ch) {
return this.options.isIdentifierContinue ?
this.options.isIdentifierContinue(ch, this.codePointAt(ch)) :
this.isValidIdentifierContinue(ch);
},
isValidIdentifierContinue: function(ch, cp) {
return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch);
},
codePointAt: function(ch) {
if (ch.length === 1) return ch.charCodeAt(0);
/*jshint bitwise: false*/
return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00;
/*jshint bitwise: true*/
},
peekMultichar: function() {
var ch = this.text.charAt(this.index);
var peek = this.peek();
if (!peek) {
return ch;
}
var cp1 = ch.charCodeAt(0);
var cp2 = peek.charCodeAt(0);
if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) {
return ch + peek;
}
return ch;
},
isExpOperator: function(ch) {
return (ch === '-' || ch === '+' || this.isNumber(ch));
},
throwError: function(error, start, end) {
end = end || this.index;
var colStr = (isDefined(start)
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
: ' ' + end);
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
error, colStr, this.text);
},
readNumber: function() {
var number = '';
var start = this.index;
while (this.index < this.text.length) {
var ch = lowercase(this.text.charAt(this.index));
if (ch === '.' || this.isNumber(ch)) {
number += ch;
} else {
var peekCh = this.peek();
if (ch === 'e' && this.isExpOperator(peekCh)) {
number += ch;
} else if (this.isExpOperator(ch) &&
peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) === 'e') {
number += ch;
} else if (this.isExpOperator(ch) &&
(!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) === 'e') {
this.throwError('Invalid exponent');
} else {
break;
}
}
this.index++;
}
this.tokens.push({
index: start,
text: number,
constant: true,
value: Number(number)
});
},
readIdent: function() {
var start = this.index;
this.index += this.peekMultichar().length;
while (this.index < this.text.length) {
var ch = this.peekMultichar();
if (!this.isIdentifierContinue(ch)) {
break;
}
this.index += ch.length;
}
this.tokens.push({
index: start,
text: this.text.slice(start, this.index),
identifier: true
});
},
readString: function(quote) {
var start = this.index;
this.index++;
var string = '';
var rawString = quote;
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i)) {
this.throwError('Invalid unicode escape [\\u' + hex + ']');
}
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
string = string + (rep || ch);
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
this.index++;
this.tokens.push({
index: start,
text: rawString,
constant: true,
value: string
});
return;
} else {
string += ch;
}
this.index++;
}
this.throwError('Unterminated quote', start);
}
};
var AST = function(lexer, options) {
this.lexer = lexer;
this.options = options;
};
AST.Program = 'Program';
AST.ExpressionStatement = 'ExpressionStatement';
AST.AssignmentExpression = 'AssignmentExpression';
AST.ConditionalExpression = 'ConditionalExpression';
AST.LogicalExpression = 'LogicalExpression';
AST.BinaryExpression = 'BinaryExpression';
AST.UnaryExpression = 'UnaryExpression';
AST.CallExpression = 'CallExpression';
AST.MemberExpression = 'MemberExpression';
AST.Identifier = 'Identifier';
AST.Literal = 'Literal';
AST.ArrayExpression = 'ArrayExpression';
AST.Property = 'Property';
AST.ObjectExpression = 'ObjectExpression';
AST.ThisExpression = 'ThisExpression';
AST.LocalsExpression = 'LocalsExpression';
// Internal use only
AST.NGValueParameter = 'NGValueParameter';
AST.prototype = {
ast: function(text) {
this.text = text;
this.tokens = this.lexer.lex(text);
var value = this.program();
if (this.tokens.length !== 0) {
this.throwError('is an unexpected token', this.tokens[0]);
}
return value;
},
program: function() {
var body = [];
while (true) {
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
body.push(this.expressionStatement());
if (!this.expect(';')) {
return { type: AST.Program, body: body};
}
}
},
expressionStatement: function() {
return { type: AST.ExpressionStatement, expression: this.filterChain() };
},
filterChain: function() {
var left = this.expression();
var token;
while ((token = this.expect('|'))) {
left = this.filter(left);
}
return left;
},
expression: function() {
return this.assignment();
},
assignment: function() {
var result = this.ternary();
if (this.expect('=')) {
result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
}
return result;
},
ternary: function() {
var test = this.logicalOR();
var alternate;
var consequent;
if (this.expect('?')) {
alternate = this.expression();
if (this.consume(':')) {
consequent = this.expression();
return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
}
}
return test;
},
logicalOR: function() {
var left = this.logicalAND();
while (this.expect('||')) {
left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
}
return left;
},
logicalAND: function() {
var left = this.equality();
while (this.expect('&&')) {
left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
}
return left;
},
equality: function() {
var left = this.relational();
var token;
while ((token = this.expect('==','!=','===','!=='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
}
return left;
},
relational: function() {
var left = this.additive();
var token;
while ((token = this.expect('<', '>', '<=', '>='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
}
return left;
},
additive: function() {
var left = this.multiplicative();
var token;
while ((token = this.expect('+','-'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
}
return left;
},
multiplicative: function() {
var left = this.unary();
var token;
while ((token = this.expect('*','/','%'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
}
return left;
},
unary: function() {
var token;
if ((token = this.expect('+', '-', '!'))) {
return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
} else {
return this.primary();
}
},
primary: function() {
var primary;
if (this.expect('(')) {
primary = this.filterChain();
this.consume(')');
} else if (this.expect('[')) {
primary = this.arrayDeclaration();
} else if (this.expect('{')) {
primary = this.object();
} else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
primary = copy(this.selfReferential[this.consume().text]);
} else if (this.options.literals.hasOwnProperty(this.peek().text)) {
primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
} else if (this.peek().identifier) {
primary = this.identifier();
} else if (this.peek().constant) {
primary = this.constant();
} else {
this.throwError('not a primary expression', this.peek());
}
var next;
while ((next = this.expect('(', '[', '.'))) {
if (next.text === '(') {
primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
this.consume(')');
} else if (next.text === '[') {
primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
this.consume(']');
} else if (next.text === '.') {
primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
} else {
this.throwError('IMPOSSIBLE');
}
}
return primary;
},
filter: function(baseExpression) {
var args = [baseExpression];
var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
while (this.expect(':')) {
args.push(this.expression());
}
return result;
},
parseArguments: function() {
var args = [];
if (this.peekToken().text !== ')') {
do {
args.push(this.expression());
} while (this.expect(','));
}
return args;
},
identifier: function() {
var token = this.consume();
if (!token.identifier) {
this.throwError('is not a valid identifier', token);
}
return { type: AST.Identifier, name: token.text };
},
constant: function() {
// TODO check that it is a constant
return { type: AST.Literal, value: this.consume().value };
},
arrayDeclaration: function() {
var elements = [];
if (this.peekToken().text !== ']') {
do {
if (this.peek(']')) {
// Support trailing commas per ES5.1.
break;
}
elements.push(this.expression());
} while (this.expect(','));
}
this.consume(']');
return { type: AST.ArrayExpression, elements: elements };
},
object: function() {
var properties = [], property;
if (this.peekToken().text !== '}') {
do {
if (this.peek('}')) {
// Support trailing commas per ES5.1.
break;
}
property = {type: AST.Property, kind: 'init'};
if (this.peek().constant) {
property.key = this.constant();
property.computed = false;
this.consume(':');
property.value = this.expression();
} else if (this.peek().identifier) {
property.key = this.identifier();
property.computed = false;
if (this.peek(':')) {
this.consume(':');
property.value = this.expression();
} else {
property.value = property.key;
}
} else if (this.peek('[')) {
this.consume('[');
property.key = this.expression();
this.consume(']');
property.computed = true;
this.consume(':');
property.value = this.expression();
} else {
this.throwError("invalid key", this.peek());
}
properties.push(property);
} while (this.expect(','));
}
this.consume('}');
return {type: AST.ObjectExpression, properties: properties };
},
throwError: function(msg, token) {
throw $parseMinErr('syntax',
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
},
consume: function(e1) {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
var token = this.expect(e1);
if (!token) {
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
return token;
},
peekToken: function() {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
return this.tokens[0];
},
peek: function(e1, e2, e3, e4) {
return this.peekAhead(0, e1, e2, e3, e4);
},
peekAhead: function(i, e1, e2, e3, e4) {
if (this.tokens.length > i) {
var token = this.tokens[i];
var t = token.text;
if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
},
expect: function(e1, e2, e3, e4) {
var token = this.peek(e1, e2, e3, e4);
if (token) {
this.tokens.shift();
return token;
}
return false;
},
selfReferential: {
'this': {type: AST.ThisExpression },
'$locals': {type: AST.LocalsExpression }
}
};
function ifDefined(v, d) {
return typeof v !== 'undefined' ? v : d;
}
function plusFn(l, r) {
if (typeof l === 'undefined') return r;
if (typeof r === 'undefined') return l;
return l + r;
}
function isStateless($filter, filterName) {
var fn = $filter(filterName);
return !fn.$stateful;
}
function findConstantAndWatchExpressions(ast, $filter) {
var allConstants;
var argsToWatch;
switch (ast.type) {
case AST.Program:
allConstants = true;
forEach(ast.body, function(expr) {
findConstantAndWatchExpressions(expr.expression, $filter);
allConstants = allConstants && expr.expression.constant;
});
ast.constant = allConstants;
break;
case AST.Literal:
ast.constant = true;
ast.toWatch = [];
break;
case AST.UnaryExpression:
findConstantAndWatchExpressions(ast.argument, $filter);
ast.constant = ast.argument.constant;
ast.toWatch = ast.argument.toWatch;
break;
case AST.BinaryExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
break;
case AST.LogicalExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.ConditionalExpression:
findConstantAndWatchExpressions(ast.test, $filter);
findConstantAndWatchExpressions(ast.alternate, $filter);
findConstantAndWatchExpressions(ast.consequent, $filter);
ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.Identifier:
ast.constant = false;
ast.toWatch = [ast];
break;
case AST.MemberExpression:
findConstantAndWatchExpressions(ast.object, $filter);
if (ast.computed) {
findConstantAndWatchExpressions(ast.property, $filter);
}
ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
ast.toWatch = [ast];
break;
case AST.CallExpression:
allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
argsToWatch = [];
forEach(ast.arguments, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
break;
case AST.AssignmentExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = [ast];
break;
case AST.ArrayExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.elements, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ObjectExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.properties, function(property) {
findConstantAndWatchExpressions(property.value, $filter);
allConstants = allConstants && property.value.constant && !property.computed;
if (!property.value.constant) {
argsToWatch.push.apply(argsToWatch, property.value.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ThisExpression:
ast.constant = false;
ast.toWatch = [];
break;
case AST.LocalsExpression:
ast.constant = false;
ast.toWatch = [];
break;
}
}
function getInputs(body) {
if (body.length !== 1) return;
var lastExpression = body[0].expression;
var candidate = lastExpression.toWatch;
if (candidate.length !== 1) return candidate;
return candidate[0] !== lastExpression ? candidate : undefined;
}
function isAssignable(ast) {
return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
}
function assignableAST(ast) {
if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
}
}
function isLiteral(ast) {
return ast.body.length === 0 ||
ast.body.length === 1 && (
ast.body[0].expression.type === AST.Literal ||
ast.body[0].expression.type === AST.ArrayExpression ||
ast.body[0].expression.type === AST.ObjectExpression);
}
function isConstant(ast) {
return ast.constant;
}
function ASTCompiler(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTCompiler.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.state = {
nextId: 0,
filters: {},
expensiveChecks: expensiveChecks,
fn: {vars: [], body: [], own: {}},
assign: {vars: [], body: [], own: {}},
inputs: []
};
findConstantAndWatchExpressions(ast, self.$filter);
var extra = '';
var assignable;
this.stage = 'assign';
if ((assignable = assignableAST(ast))) {
this.state.computing = 'assign';
var result = this.nextId();
this.recurse(assignable, result);
this.return_(result);
extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
}
var toWatch = getInputs(ast.body);
self.stage = 'inputs';
forEach(toWatch, function(watch, key) {
var fnKey = 'fn' + key;
self.state[fnKey] = {vars: [], body: [], own: {}};
self.state.computing = fnKey;
var intoId = self.nextId();
self.recurse(watch, intoId);
self.return_(intoId);
self.state.inputs.push(fnKey);
watch.watchId = key;
});
this.state.computing = 'fn';
this.stage = 'main';
this.recurse(ast);
var fnString =
// The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
// This is a workaround for this until we do a better job at only removing the prefix only when we should.
'"' + this.USE + ' ' + this.STRICT + '";\n' +
this.filterPrefix() +
'var fn=' + this.generateFunction('fn', 's,l,a,i') +
extra +
this.watchFns() +
'return fn;';
/* jshint -W054 */
var fn = (new Function('$filter',
'ensureSafeMemberName',
'ensureSafeObject',
'ensureSafeFunction',
'getStringValue',
'ensureSafeAssignContext',
'ifDefined',
'plus',
'text',
fnString))(
this.$filter,
ensureSafeMemberName,
ensureSafeObject,
ensureSafeFunction,
getStringValue,
ensureSafeAssignContext,
ifDefined,
plusFn,
expression);
/* jshint +W054 */
this.state = this.stage = undefined;
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
USE: 'use',
STRICT: 'strict',
watchFns: function() {
var result = [];
var fns = this.state.inputs;
var self = this;
forEach(fns, function(name) {
result.push('var ' + name + '=' + self.generateFunction(name, 's'));
});
if (fns.length) {
result.push('fn.inputs=[' + fns.join(',') + '];');
}
return result.join('');
},
generateFunction: function(name, params) {
return 'function(' + params + '){' +
this.varsPrefix(name) +
this.body(name) +
'};';
},
filterPrefix: function() {
var parts = [];
var self = this;
forEach(this.state.filters, function(id, filter) {
parts.push(id + '=$filter(' + self.escape(filter) + ')');
});
if (parts.length) return 'var ' + parts.join(',') + ';';
return '';
},
varsPrefix: function(section) {
return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
},
body: function(section) {
return this.state[section].body.join('');
},
recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var left, right, self = this, args, expression, computed;
recursionFn = recursionFn || noop;
if (!skipWatchIdCheck && isDefined(ast.watchId)) {
intoId = intoId || this.nextId();
this.if_('i',
this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
);
return;
}
switch (ast.type) {
case AST.Program:
forEach(ast.body, function(expression, pos) {
self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
if (pos !== ast.body.length - 1) {
self.current().body.push(right, ';');
} else {
self.return_(right);
}
});
break;
case AST.Literal:
expression = this.escape(ast.value);
this.assign(intoId, expression);
recursionFn(intoId || expression);
break;
case AST.UnaryExpression:
this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.BinaryExpression:
this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
if (ast.operator === '+') {
expression = this.plus(left, right);
} else if (ast.operator === '-') {
expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
} else {
expression = '(' + left + ')' + ast.operator + '(' + right + ')';
}
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.LogicalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.left, intoId);
self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
recursionFn(intoId);
break;
case AST.ConditionalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.test, intoId);
self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
recursionFn(intoId);
break;
case AST.Identifier:
intoId = intoId || this.nextId();
if (nameId) {
nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
nameId.computed = false;
nameId.name = ast.name;
}
ensureSafeMemberName(ast.name);
self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
function() {
self.if_(self.stage === 'inputs' || 's', function() {
if (create && create !== 1) {
self.if_(
self.not(self.nonComputedMember('s', ast.name)),
self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
}
self.assign(intoId, self.nonComputedMember('s', ast.name));
});
}, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
self.addEnsureSafeObject(intoId);
}
recursionFn(intoId);
break;
case AST.MemberExpression:
left = nameId && (nameId.context = this.nextId()) || this.nextId();
intoId = intoId || this.nextId();
self.recurse(ast.object, left, undefined, function() {
self.if_(self.notNull(left), function() {
if (create && create !== 1) {
self.addEnsureSafeAssignContext(left);
}
if (ast.computed) {
right = self.nextId();
self.recurse(ast.property, right);
self.getStringValue(right);
self.addEnsureSafeMemberName(right);
if (create && create !== 1) {
self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
}
expression = self.ensureSafeObject(self.computedMember(left, right));
self.assign(intoId, expression);
if (nameId) {
nameId.computed = true;
nameId.name = right;
}
} else {
ensureSafeMemberName(ast.property.name);
if (create && create !== 1) {
self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
}
expression = self.nonComputedMember(left, ast.property.name);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
expression = self.ensureSafeObject(expression);
}
self.assign(intoId, expression);
if (nameId) {
nameId.computed = false;
nameId.name = ast.property.name;
}
}
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
}, !!create);
break;
case AST.CallExpression:
intoId = intoId || this.nextId();
if (ast.filter) {
right = self.filter(ast.callee.name);
args = [];
forEach(ast.arguments, function(expr) {
var argument = self.nextId();
self.recurse(expr, argument);
args.push(argument);
});
expression = right + '(' + args.join(',') + ')';
self.assign(intoId, expression);
recursionFn(intoId);
} else {
right = self.nextId();
left = {};
args = [];
self.recurse(ast.callee, right, left, function() {
self.if_(self.notNull(right), function() {
self.addEnsureSafeFunction(right);
forEach(ast.arguments, function(expr) {
self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
args.push(self.ensureSafeObject(argument));
});
});
if (left.name) {
if (!self.state.expensiveChecks) {
self.addEnsureSafeObject(left.context);
}
expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
} else {
expression = right + '(' + args.join(',') + ')';
}
expression = self.ensureSafeObject(expression);
self.assign(intoId, expression);
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
});
}
break;
case AST.AssignmentExpression:
right = this.nextId();
left = {};
if (!isAssignable(ast.left)) {
throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
}
this.recurse(ast.left, undefined, left, function() {
self.if_(self.notNull(left.context), function() {
self.recurse(ast.right, right);
self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
self.addEnsureSafeAssignContext(left.context);
expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
self.assign(intoId, expression);
recursionFn(intoId || expression);
});
}, 1);
break;
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) {
args.push(argument);
});
});
expression = '[' + args.join(',') + ']';
this.assign(intoId, expression);
recursionFn(intoId || expression);
break;
case AST.ObjectExpression:
args = [];
computed = false;
forEach(ast.properties, function(property) {
if (property.computed) {
computed = true;
}
});
if (computed) {
intoId = intoId || this.nextId();
this.assign(intoId, '{}');
forEach(ast.properties, function(property) {
if (property.computed) {
left = self.nextId();
self.recurse(property.key, left);
} else {
left = property.key.type === AST.Identifier ?
property.key.name :
('' + property.key.value);
}
right = self.nextId();
self.recurse(property.value, right);
self.assign(self.member(intoId, left, property.computed), right);
});
} else {
forEach(ast.properties, function(property) {
self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) {
args.push(self.escape(
property.key.type === AST.Identifier ? property.key.name :
('' + property.key.value)) +
':' + expr);
});
});
expression = '{' + args.join(',') + '}';
this.assign(intoId, expression);
}
recursionFn(intoId || expression);
break;
case AST.ThisExpression:
this.assign(intoId, 's');
recursionFn(intoId || 's');
break;
case AST.LocalsExpression:
this.assign(intoId, 'l');
recursionFn(intoId || 'l');
break;
case AST.NGValueParameter:
this.assign(intoId, 'v');
recursionFn(intoId || 'v');
break;
}
},
getHasOwnProperty: function(element, property) {
var key = element + '.' + property;
var own = this.current().own;
if (!own.hasOwnProperty(key)) {
own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
}
return own[key];
},
assign: function(id, value) {
if (!id) return;
this.current().body.push(id, '=', value, ';');
return id;
},
filter: function(filterName) {
if (!this.state.filters.hasOwnProperty(filterName)) {
this.state.filters[filterName] = this.nextId(true);
}
return this.state.filters[filterName];
},
ifDefined: function(id, defaultValue) {
return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
},
plus: function(left, right) {
return 'plus(' + left + ',' + right + ')';
},
return_: function(id) {
this.current().body.push('return ', id, ';');
},
if_: function(test, alternate, consequent) {
if (test === true) {
alternate();
} else {
var body = this.current().body;
body.push('if(', test, '){');
alternate();
body.push('}');
if (consequent) {
body.push('else{');
consequent();
body.push('}');
}
}
},
not: function(expression) {
return '!(' + expression + ')';
},
notNull: function(expression) {
return expression + '!=null';
},
nonComputedMember: function(left, right) {
var SAFE_IDENTIFIER = /[$_a-zA-Z][$_a-zA-Z0-9]*/;
var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
if (SAFE_IDENTIFIER.test(right)) {
return left + '.' + right;
} else {
return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
}
},
computedMember: function(left, right) {
return left + '[' + right + ']';
},
member: function(left, right, computed) {
if (computed) return this.computedMember(left, right);
return this.nonComputedMember(left, right);
},
addEnsureSafeObject: function(item) {
this.current().body.push(this.ensureSafeObject(item), ';');
},
addEnsureSafeMemberName: function(item) {
this.current().body.push(this.ensureSafeMemberName(item), ';');
},
addEnsureSafeFunction: function(item) {
this.current().body.push(this.ensureSafeFunction(item), ';');
},
addEnsureSafeAssignContext: function(item) {
this.current().body.push(this.ensureSafeAssignContext(item), ';');
},
ensureSafeObject: function(item) {
return 'ensureSafeObject(' + item + ',text)';
},
ensureSafeMemberName: function(item) {
return 'ensureSafeMemberName(' + item + ',text)';
},
ensureSafeFunction: function(item) {
return 'ensureSafeFunction(' + item + ',text)';
},
getStringValue: function(item) {
this.assign(item, 'getStringValue(' + item + ')');
},
ensureSafeAssignContext: function(item) {
return 'ensureSafeAssignContext(' + item + ',text)';
},
lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var self = this;
return function() {
self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
};
},
lazyAssign: function(id, value) {
var self = this;
return function() {
self.assign(id, value);
};
},
stringEscapeRegex: /[^ a-zA-Z0-9]/g,
stringEscapeFn: function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
},
escape: function(value) {
if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
if (isNumber(value)) return value.toString();
if (value === true) return 'true';
if (value === false) return 'false';
if (value === null) return 'null';
if (typeof value === 'undefined') return 'undefined';
throw $parseMinErr('esc', 'IMPOSSIBLE');
},
nextId: function(skip, init) {
var id = 'v' + (this.state.nextId++);
if (!skip) {
this.current().vars.push(id + (init ? '=' + init : ''));
}
return id;
},
current: function() {
return this.state[this.state.computing];
}
};
function ASTInterpreter(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTInterpreter.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.expression = expression;
this.expensiveChecks = expensiveChecks;
findConstantAndWatchExpressions(ast, self.$filter);
var assignable;
var assign;
if ((assignable = assignableAST(ast))) {
assign = this.recurse(assignable);
}
var toWatch = getInputs(ast.body);
var inputs;
if (toWatch) {
inputs = [];
forEach(toWatch, function(watch, key) {
var input = self.recurse(watch);
watch.input = input;
inputs.push(input);
watch.watchId = key;
});
}
var expressions = [];
forEach(ast.body, function(expression) {
expressions.push(self.recurse(expression.expression));
});
var fn = ast.body.length === 0 ? noop :
ast.body.length === 1 ? expressions[0] :
function(scope, locals) {
var lastValue;
forEach(expressions, function(exp) {
lastValue = exp(scope, locals);
});
return lastValue;
};
if (assign) {
fn.assign = function(scope, value, locals) {
return assign(scope, locals, value);
};
}
if (inputs) {
fn.inputs = inputs;
}
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
recurse: function(ast, context, create) {
var left, right, self = this, args, expression;
if (ast.input) {
return this.inputs(ast.input, ast.watchId);
}
switch (ast.type) {
case AST.Literal:
return this.value(ast.value, context);
case AST.UnaryExpression:
right = this.recurse(ast.argument);
return this['unary' + ast.operator](right, context);
case AST.BinaryExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.LogicalExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.ConditionalExpression:
return this['ternary?:'](
this.recurse(ast.test),
this.recurse(ast.alternate),
this.recurse(ast.consequent),
context
);
case AST.Identifier:
ensureSafeMemberName(ast.name, self.expression);
return self.identifier(ast.name,
self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
context, create, self.expression);
case AST.MemberExpression:
left = this.recurse(ast.object, false, !!create);
if (!ast.computed) {
ensureSafeMemberName(ast.property.name, self.expression);
right = ast.property.name;
}
if (ast.computed) right = this.recurse(ast.property);
return ast.computed ?
this.computedMember(left, right, context, create, self.expression) :
this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
case AST.CallExpression:
args = [];
forEach(ast.arguments, function(expr) {
args.push(self.recurse(expr));
});
if (ast.filter) right = this.$filter(ast.callee.name);
if (!ast.filter) right = this.recurse(ast.callee, true);
return ast.filter ?
function(scope, locals, assign, inputs) {
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(args[i](scope, locals, assign, inputs));
}
var value = right.apply(undefined, values, inputs);
return context ? {context: undefined, name: undefined, value: value} : value;
} :
function(scope, locals, assign, inputs) {
var rhs = right(scope, locals, assign, inputs);
var value;
if (rhs.value != null) {
ensureSafeObject(rhs.context, self.expression);
ensureSafeFunction(rhs.value, self.expression);
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
}
value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
}
return context ? {value: value} : value;
};
case AST.AssignmentExpression:
left = this.recurse(ast.left, true, 1);
right = this.recurse(ast.right);
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
ensureSafeObject(lhs.value, self.expression);
ensureSafeAssignContext(lhs.context);
lhs.context[lhs.name] = rhs;
return context ? {value: rhs} : rhs;
};
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
args.push(self.recurse(expr));
});
return function(scope, locals, assign, inputs) {
var value = [];
for (var i = 0; i < args.length; ++i) {
value.push(args[i](scope, locals, assign, inputs));
}
return context ? {value: value} : value;
};
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
if (property.computed) {
args.push({key: self.recurse(property.key),
computed: true,
value: self.recurse(property.value)
});
} else {
args.push({key: property.key.type === AST.Identifier ?
property.key.name :
('' + property.key.value),
computed: false,
value: self.recurse(property.value)
});
}
});
return function(scope, locals, assign, inputs) {
var value = {};
for (var i = 0; i < args.length; ++i) {
if (args[i].computed) {
value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs);
} else {
value[args[i].key] = args[i].value(scope, locals, assign, inputs);
}
}
return context ? {value: value} : value;
};
case AST.ThisExpression:
return function(scope) {
return context ? {value: scope} : scope;
};
case AST.LocalsExpression:
return function(scope, locals) {
return context ? {value: locals} : locals;
};
case AST.NGValueParameter:
return function(scope, locals, assign) {
return context ? {value: assign} : assign;
};
}
},
'unary+': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = +arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary-': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = -arg;
} else {
arg = -0;
}
return context ? {value: arg} : arg;
};
},
'unary!': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = !argument(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary+': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = plusFn(lhs, rhs);
return context ? {value: arg} : arg;
};
},
'binary-': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
return context ? {value: arg} : arg;
};
},
'binary*': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary/': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary%': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary===': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
/* jshint eqeqeq:false */
var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
/* jshint eqeqeq:false */
var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary&&': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary||': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'ternary?:': function(test, alternate, consequent, context) {
return function(scope, locals, assign, inputs) {
var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
value: function(value, context) {
return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
},
identifier: function(name, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var base = locals && (name in locals) ? locals : scope;
if (create && create !== 1 && base && !(base[name])) {
base[name] = {};
}
var value = base ? base[name] : undefined;
if (expensiveChecks) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: base, name: name, value: value};
} else {
return value;
}
};
},
computedMember: function(left, right, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs;
var value;
if (lhs != null) {
rhs = right(scope, locals, assign, inputs);
rhs = getStringValue(rhs);
ensureSafeMemberName(rhs, expression);
if (create && create !== 1) {
ensureSafeAssignContext(lhs);
if (lhs && !(lhs[rhs])) {
lhs[rhs] = {};
}
}
value = lhs[rhs];
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: rhs, value: value};
} else {
return value;
}
};
},
nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
if (create && create !== 1) {
ensureSafeAssignContext(lhs);
if (lhs && !(lhs[right])) {
lhs[right] = {};
}
}
var value = lhs != null ? lhs[right] : undefined;
if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: right, value: value};
} else {
return value;
}
};
},
inputs: function(input, watchId) {
return function(scope, value, locals, inputs) {
if (inputs) return inputs[watchId];
return input(scope, value, locals);
};
}
};
/**
* @constructor
*/
var Parser = function(lexer, $filter, options) {
this.lexer = lexer;
this.$filter = $filter;
this.options = options;
this.ast = new AST(lexer, options);
this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
new ASTCompiler(this.ast, $filter);
};
Parser.prototype = {
constructor: Parser,
parse: function(text) {
return this.astCompiler.compile(text, this.options.expensiveChecks);
}
};
function isPossiblyDangerousMemberName(name) {
return name === 'constructor';
}
var objectValueOf = Object.prototype.valueOf;
function getValueOf(value) {
return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}
///////////////////////////////////
/**
* @ngdoc service
* @name $parse
* @kind function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* ```js
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* ```
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
/**
* @ngdoc provider
* @name $parseProvider
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
var cacheDefault = createMap();
var cacheExpensive = createMap();
var literals = {
'true': true,
'false': false,
'null': null,
'undefined': undefined
};
var identStart, identContinue;
/**
* @ngdoc method
* @name $parseProvider#addLiteral
* @description
*
* Configure $parse service to add literal values that will be present as literal at expressions.
*
* @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
* @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
*
**/
this.addLiteral = function(literalName, literalValue) {
literals[literalName] = literalValue;
};
/**
* @ngdoc method
* @name $parseProvider#setIdentifierFns
* @description
*
* Allows defining the set of characters that are allowed in Angular expressions. The function
* `identifierStart` will get called to know if a given character is a valid character to be the
* first character for an identifier. The function `identifierContinue` will get called to know if
* a given character is a valid character to be a follow-up identifier character. The functions
* `identifierStart` and `identifierContinue` will receive as arguments the single character to be
* identifier and the character code point. These arguments will be `string` and `numeric`. Keep in
* mind that the `string` parameter can be two characters long depending on the character
* representation. It is expected for the function to return `true` or `false`, whether that
* character is allowed or not.
*
* Since this function will be called extensivelly, keep the implementation of these functions fast,
* as the performance of these functions have a direct impact on the expressions parsing speed.
*
* @param {function=} identifierStart The function that will decide whether the given character is
* a valid identifier start character.
* @param {function=} identifierContinue The function that will decide whether the given character is
* a valid identifier continue character.
*/
this.setIdentifierFns = function(identifierStart, identifierContinue) {
identStart = identifierStart;
identContinue = identifierContinue;
return this;
};
this.$get = ['$filter', function($filter) {
var noUnsafeEval = csp().noUnsafeEval;
var $parseOptions = {
csp: noUnsafeEval,
expensiveChecks: false,
literals: copy(literals),
isIdentifierStart: isFunction(identStart) && identStart,
isIdentifierContinue: isFunction(identContinue) && identContinue
},
$parseOptionsExpensive = {
csp: noUnsafeEval,
expensiveChecks: true,
literals: copy(literals),
isIdentifierStart: isFunction(identStart) && identStart,
isIdentifierContinue: isFunction(identContinue) && identContinue
};
var runningChecksEnabled = false;
$parse.$$runningExpensiveChecks = function() {
return runningChecksEnabled;
};
return $parse;
function $parse(exp, interceptorFn, expensiveChecks) {
var parsedExpression, oneTime, cacheKey;
expensiveChecks = expensiveChecks || runningChecksEnabled;
switch (typeof exp) {
case 'string':
exp = exp.trim();
cacheKey = exp;
var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
parsedExpression = cache[cacheKey];
if (!parsedExpression) {
if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
oneTime = true;
exp = exp.substring(2);
}
var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
var lexer = new Lexer(parseOptions);
var parser = new Parser(lexer, $filter, parseOptions);
parsedExpression = parser.parse(exp);
if (parsedExpression.constant) {
parsedExpression.$$watchDelegate = constantWatchDelegate;
} else if (oneTime) {
parsedExpression.$$watchDelegate = parsedExpression.literal ?
oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
} else if (parsedExpression.inputs) {
parsedExpression.$$watchDelegate = inputsWatchDelegate;
}
if (expensiveChecks) {
parsedExpression = expensiveChecksInterceptor(parsedExpression);
}
cache[cacheKey] = parsedExpression;
}
return addInterceptor(parsedExpression, interceptorFn);
case 'function':
return addInterceptor(exp, interceptorFn);
default:
return addInterceptor(noop, interceptorFn);
}
}
function expensiveChecksInterceptor(fn) {
if (!fn) return fn;
expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
expensiveCheckFn.constant = fn.constant;
expensiveCheckFn.literal = fn.literal;
for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
}
expensiveCheckFn.inputs = fn.inputs;
return expensiveCheckFn;
function expensiveCheckFn(scope, locals, assign, inputs) {
var expensiveCheckOldValue = runningChecksEnabled;
runningChecksEnabled = true;
try {
return fn(scope, locals, assign, inputs);
} finally {
runningChecksEnabled = expensiveCheckOldValue;
}
}
}
function expressionInputDirtyCheck(newValue, oldValueOfValue) {
if (newValue == null || oldValueOfValue == null) { // null/undefined
return newValue === oldValueOfValue;
}
if (typeof newValue === 'object') {
// attempt to convert the value to a primitive type
// TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
// be cheaply dirty-checked
newValue = getValueOf(newValue);
if (typeof newValue === 'object') {
// objects/arrays are not supported - deep-watching them would be too expensive
return false;
}
// fall-through to the primitive equality check
}
//Primitive or NaN
return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
}
function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
var inputExpressions = parsedExpression.inputs;
var lastResult;
if (inputExpressions.length === 1) {
var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
inputExpressions = inputExpressions[0];
return scope.$watch(function expressionInputWatch(scope) {
var newInputValue = inputExpressions(scope);
if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
oldInputValueOf = newInputValue && getValueOf(newInputValue);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
var oldInputValueOfValues = [];
var oldInputValues = [];
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
oldInputValues[i] = null;
}
return scope.$watch(function expressionInputsWatch(scope) {
var changed = false;
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
var newInputValue = inputExpressions[i](scope);
if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
oldInputValues[i] = newInputValue;
oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
}
}
if (changed) {
lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
var unwatch, lastValue;
if (parsedExpression.inputs) {
return unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
} else {
return unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
}
function oneTimeWatch(scope) {
return parsedExpression(scope);
}
function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener(value, old, scope);
}
if (isDefined(value)) {
scope.$$postDigest(function() {
if (isDefined(lastValue)) {
unwatch();
}
});
}
}
}
function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener(value, old, scope);
}
if (isAllDefined(value)) {
scope.$$postDigest(function() {
if (isAllDefined(lastValue)) unwatch();
});
}
}, objectEquality);
function isAllDefined(value) {
var allDefined = true;
forEach(value, function(val) {
if (!isDefined(val)) allDefined = false;
});
return allDefined;
}
}
function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch;
return unwatch = scope.$watch(function constantWatch(scope) {
unwatch();
return parsedExpression(scope);
}, listener, objectEquality);
}
function addInterceptor(parsedExpression, interceptorFn) {
if (!interceptorFn) return parsedExpression;
var watchDelegate = parsedExpression.$$watchDelegate;
var useInputs = false;
var regularWatch =
watchDelegate !== oneTimeLiteralWatchDelegate &&
watchDelegate !== oneTimeWatchDelegate;
var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
return interceptorFn(value, scope, locals);
} : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
var value = parsedExpression(scope, locals, assign, inputs);
var result = interceptorFn(value, scope, locals);
// we only return the interceptor's result if the
// initial value is defined (for bind-once)
return isDefined(value) ? result : value;
};
// Propagate $$watchDelegates other then inputsWatchDelegate
useInputs = !parsedExpression.inputs;
if (parsedExpression.$$watchDelegate &&
parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
fn.$$watchDelegate = parsedExpression.$$watchDelegate;
fn.inputs = parsedExpression.inputs;
} else if (!interceptorFn.$stateful) {
// If there is an interceptor, but no watchDelegate then treat the interceptor like
// we treat filters - it is assumed to be a pure function unless flagged with $stateful
fn.$$watchDelegate = inputsWatchDelegate;
fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
}
return fn;
}
}];
}
|
"use strict";var sjcl={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message};this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message};this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message};this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message};this.message=a}}};
sjcl.cipher.aes=function(a){this.s[0][0][0]||this.O();var b,c,d,e,f=this.s[0][4],g=this.s[1];b=a.length;var h=1;if(4!==b&&6!==b&&8!==b)throw new sjcl.exception.invalid("invalid aes key size");this.b=[d=a.slice(0),e=[]];for(a=b;a<4*b+28;a++){c=d[a-1];if(0===a%b||8===b&&4===a%b)c=f[c>>>24]<<24^f[c>>16&255]<<16^f[c>>8&255]<<8^f[c&255],0===a%b&&(c=c<<8^c>>>24^h<<24,h=h<<1^283*(h>>7));d[a]=d[a-b]^c}for(b=0;a;b++,a--)c=d[b&3?a:a-4],e[b]=4>=a||4>b?c:g[0][f[c>>>24]]^g[1][f[c>>16&255]]^g[2][f[c>>8&255]]^g[3][f[c&
255]]};
sjcl.cipher.aes.prototype={encrypt:function(a){return t(this,a,0)},decrypt:function(a){return t(this,a,1)},s:[[[],[],[],[],[]],[[],[],[],[],[]]],O:function(){var a=this.s[0],b=this.s[1],c=a[4],d=b[4],e,f,g,h=[],k=[],l,n,m,p;for(e=0;0x100>e;e++)k[(h[e]=e<<1^283*(e>>7))^e]=e;for(f=g=0;!c[f];f^=l||1,g=k[g]||1)for(m=g^g<<1^g<<2^g<<3^g<<4,m=m>>8^m&255^99,c[f]=m,d[m]=f,n=h[e=h[l=h[f]]],p=0x1010101*n^0x10001*e^0x101*l^0x1010100*f,n=0x101*h[m]^0x1010100*m,e=0;4>e;e++)a[e][f]=n=n<<24^n>>>8,b[e][m]=p=p<<24^p>>>8;for(e=
0;5>e;e++)a[e]=a[e].slice(0),b[e]=b[e].slice(0)}};
function t(a,b,c){if(4!==b.length)throw new sjcl.exception.invalid("invalid aes block size");var d=a.b[c],e=b[0]^d[0],f=b[c?3:1]^d[1],g=b[2]^d[2];b=b[c?1:3]^d[3];var h,k,l,n=d.length/4-2,m,p=4,r=[0,0,0,0];h=a.s[c];a=h[0];var q=h[1],v=h[2],w=h[3],x=h[4];for(m=0;m<n;m++)h=a[e>>>24]^q[f>>16&255]^v[g>>8&255]^w[b&255]^d[p],k=a[f>>>24]^q[g>>16&255]^v[b>>8&255]^w[e&255]^d[p+1],l=a[g>>>24]^q[b>>16&255]^v[e>>8&255]^w[f&255]^d[p+2],b=a[b>>>24]^q[e>>16&255]^v[f>>8&255]^w[g&255]^d[p+3],p+=4,e=h,f=k,g=l;for(m=
0;4>m;m++)r[c?3&-m:m]=x[e>>>24]<<24^x[f>>16&255]<<16^x[g>>8&255]<<8^x[b&255]^d[p++],h=e,e=f,f=g,g=b,b=h;return r}
sjcl.bitArray={bitSlice:function(a,b,c){a=sjcl.bitArray.$(a.slice(b/32),32-(b&31)).slice(1);return void 0===c?a:sjcl.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return((b+c-1^b)&-32?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<<c)-1},concat:function(a,b){if(0===a.length||0===b.length)return a.concat(b);var c=a[a.length-1],d=sjcl.bitArray.getPartial(c);return 32===d?a.concat(b):sjcl.bitArray.$(b,d,c|0,a.slice(0,a.length-1))},bitLength:function(a){var b=a.length;return 0===
b?0:32*(b-1)+sjcl.bitArray.getPartial(a[b-1])},clamp:function(a,b){if(32*a.length<b)return a;a=a.slice(0,Math.ceil(b/32));var c=a.length;b=b&31;0<c&&b&&(a[c-1]=sjcl.bitArray.partial(b,a[c-1]&2147483648>>b-1,1));return a},partial:function(a,b,c){return 32===a?b:(c?b|0:b<<32-a)+0x10000000000*a},getPartial:function(a){return Math.round(a/0x10000000000)||32},equal:function(a,b){if(sjcl.bitArray.bitLength(a)!==sjcl.bitArray.bitLength(b))return!1;var c=0,d;for(d=0;d<a.length;d++)c|=a[d]^b[d];return 0===
c},$:function(a,b,c,d){var e;e=0;for(void 0===d&&(d=[]);32<=b;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0;e<a.length;e++)d.push(c|a[e]>>>b),c=a[e]<<32-b;e=a.length?a[a.length-1]:0;a=sjcl.bitArray.getPartial(e);d.push(sjcl.bitArray.partial(b+a&31,32<b+a?c:d.pop(),1));return d},i:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]},byteswapM:function(a){var b,c;for(b=0;b<a.length;++b)c=a[b],a[b]=c>>>24|c>>>8&0xff00|(c&0xff00)<<8|c<<24;return a}};
sjcl.codec.utf8String={fromBits:function(a){var b="",c=sjcl.bitArray.bitLength(a),d,e;for(d=0;d<c/8;d++)0===(d&3)&&(e=a[d/4]),b+=String.fromCharCode(e>>>24),e<<=8;return decodeURIComponent(escape(b))},toBits:function(a){a=unescape(encodeURIComponent(a));var b=[],c,d=0;for(c=0;c<a.length;c++)d=d<<8|a.charCodeAt(c),3===(c&3)&&(b.push(d),d=0);c&3&&b.push(sjcl.bitArray.partial(8*(c&3),d));return b}};
sjcl.codec.hex={fromBits:function(a){var b="",c;for(c=0;c<a.length;c++)b+=((a[c]|0)+0xf00000000000).toString(16).substr(4);return b.substr(0,sjcl.bitArray.bitLength(a)/4)},toBits:function(a){var b,c=[],d;a=a.replace(/\s|0x/g,"");d=a.length;a=a+"00000000";for(b=0;b<a.length;b+=8)c.push(parseInt(a.substr(b,8),16)^0);return sjcl.bitArray.clamp(c,4*d)}};
sjcl.codec.base32={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",X:"0123456789ABCDEFGHIJKLMNOPQRSTUV",BITS:32,BASE:5,REMAINING:27,fromBits:function(a,b,c){var d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f="",g=0,h=sjcl.codec.base32.B,k=0,l=sjcl.bitArray.bitLength(a);c&&(h=sjcl.codec.base32.X);for(c=0;f.length*d<l;)f+=h.charAt((k^a[c]>>>g)>>>e),g<d?(k=a[c]<<d-g,g+=e,c++):(k<<=d,g-=d);for(;f.length&7&&!b;)f+="=";return f},toBits:function(a,b){a=a.replace(/\s|=/g,"").toUpperCase();var c=sjcl.codec.base32.BITS,
d=sjcl.codec.base32.BASE,e=sjcl.codec.base32.REMAINING,f=[],g,h=0,k=sjcl.codec.base32.B,l=0,n,m="base32";b&&(k=sjcl.codec.base32.X,m="base32hex");for(g=0;g<a.length;g++){n=k.indexOf(a.charAt(g));if(0>n){if(!b)try{return sjcl.codec.base32hex.toBits(a)}catch(p){}throw new sjcl.exception.invalid("this isn't "+m+"!");}h>e?(h-=e,f.push(l^n>>>h),l=n<<c-h):(h+=d,l^=n<<c-h)}h&56&&f.push(sjcl.bitArray.partial(h&56,l,1));return f}};
sjcl.codec.base32hex={fromBits:function(a,b){return sjcl.codec.base32.fromBits(a,b,1)},toBits:function(a){return sjcl.codec.base32.toBits(a,1)}};
sjcl.codec.base64={B:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",fromBits:function(a,b,c){var d="",e=0,f=sjcl.codec.base64.B,g=0,h=sjcl.bitArray.bitLength(a);c&&(f=f.substr(0,62)+"-_");for(c=0;6*d.length<h;)d+=f.charAt((g^a[c]>>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;d.length&3&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c=[],d,e=0,f=sjcl.codec.base64.B,g=0,h;b&&(f=f.substr(0,62)+"-_");for(d=0;d<a.length;d++){h=f.indexOf(a.charAt(d));
if(0>h)throw new sjcl.exception.invalid("this isn't base64!");26<e?(e-=26,c.push(g^h>>>e),g=h<<32-e):(e+=6,g^=h<<32-e)}e&56&&c.push(sjcl.bitArray.partial(e&56,g,1));return c}};sjcl.codec.base64url={fromBits:function(a){return sjcl.codec.base64.fromBits(a,1,1)},toBits:function(a){return sjcl.codec.base64.toBits(a,1)}};sjcl.hash.sha256=function(a){this.b[0]||this.O();a?(this.F=a.F.slice(0),this.A=a.A.slice(0),this.l=a.l):this.reset()};sjcl.hash.sha256.hash=function(a){return(new sjcl.hash.sha256).update(a).finalize()};
sjcl.hash.sha256.prototype={blockSize:512,reset:function(){this.F=this.Y.slice(0);this.A=[];this.l=0;return this},update:function(a){"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));var b,c=this.A=sjcl.bitArray.concat(this.A,a);b=this.l;a=this.l=b+sjcl.bitArray.bitLength(a);if(0x1fffffffffffff<a)throw new sjcl.exception.invalid("Cannot hash more than 2^53 - 1 bits");if("undefined"!==typeof Uint32Array){var d=new Uint32Array(c),e=0;for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,d.subarray(16*e,
16*(e+1))),e+=1;c.splice(0,16*e)}else for(b=512+b-(512+b&0x1ff);b<=a;b+=512)u(this,c.splice(0,16));return this},finalize:function(){var a,b=this.A,c=this.F,b=sjcl.bitArray.concat(b,[sjcl.bitArray.partial(1,1)]);for(a=b.length+2;a&15;a++)b.push(0);b.push(Math.floor(this.l/0x100000000));for(b.push(this.l|0);b.length;)u(this,b.splice(0,16));this.reset();return c},Y:[],b:[],O:function(){function a(a){return 0x100000000*(a-Math.floor(a))|0}for(var b=0,c=2,d,e;64>b;c++){e=!0;for(d=2;d*d<=c;d++)if(0===c%d){e=
!1;break}e&&(8>b&&(this.Y[b]=a(Math.pow(c,.5))),this.b[b]=a(Math.pow(c,1/3)),b++)}}};
function u(a,b){var c,d,e,f=a.F,g=a.b,h=f[0],k=f[1],l=f[2],n=f[3],m=f[4],p=f[5],r=f[6],q=f[7];for(c=0;64>c;c++)16>c?d=b[c]:(d=b[c+1&15],e=b[c+14&15],d=b[c&15]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+b[c&15]+b[c+9&15]|0),d=d+q+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(r^m&(p^r))+g[c],q=r,r=p,p=m,m=n+d|0,n=l,l=k,k=h,h=d+(k&l^n&(k^l))+(k>>>2^k>>>13^k>>>22^k<<30^k<<19^k<<10)|0;f[0]=f[0]+h|0;f[1]=f[1]+k|0;f[2]=f[2]+l|0;f[3]=f[3]+n|0;f[4]=f[4]+m|0;f[5]=f[5]+p|0;f[6]=f[6]+r|0;f[7]=
f[7]+q|0}
sjcl.mode.ccm={name:"ccm",G:[],listenProgress:function(a){sjcl.mode.ccm.G.push(a)},unListenProgress:function(a){a=sjcl.mode.ccm.G.indexOf(a);-1<a&&sjcl.mode.ccm.G.splice(a,1)},fa:function(a){var b=sjcl.mode.ccm.G.slice(),c;for(c=0;c<b.length;c+=1)b[c](a)},encrypt:function(a,b,c,d,e){var f,g=b.slice(0),h=sjcl.bitArray,k=h.bitLength(c)/8,l=h.bitLength(g)/8;e=e||64;d=d||[];if(7>k)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(f=2;4>f&&l>>>8*f;f++);f<15-k&&(f=15-k);c=h.clamp(c,
8*(15-f));b=sjcl.mode.ccm.V(a,b,c,d,e,f);g=sjcl.mode.ccm.C(a,g,c,b,e,f);return h.concat(g.data,g.tag)},decrypt:function(a,b,c,d,e){e=e||64;d=d||[];var f=sjcl.bitArray,g=f.bitLength(c)/8,h=f.bitLength(b),k=f.clamp(b,h-e),l=f.bitSlice(b,h-e),h=(h-e)/8;if(7>g)throw new sjcl.exception.invalid("ccm: iv must be at least 7 bytes");for(b=2;4>b&&h>>>8*b;b++);b<15-g&&(b=15-g);c=f.clamp(c,8*(15-b));k=sjcl.mode.ccm.C(a,k,c,l,e,b);a=sjcl.mode.ccm.V(a,k.data,c,d,e,b);if(!f.equal(k.tag,a))throw new sjcl.exception.corrupt("ccm: tag doesn't match");
return k.data},na:function(a,b,c,d,e,f){var g=[],h=sjcl.bitArray,k=h.i;d=[h.partial(8,(b.length?64:0)|d-2<<2|f-1)];d=h.concat(d,c);d[3]|=e;d=a.encrypt(d);if(b.length)for(c=h.bitLength(b)/8,65279>=c?g=[h.partial(16,c)]:0xffffffff>=c&&(g=h.concat([h.partial(16,65534)],[c])),g=h.concat(g,b),b=0;b<g.length;b+=4)d=a.encrypt(k(d,g.slice(b,b+4).concat([0,0,0])));return d},V:function(a,b,c,d,e,f){var g=sjcl.bitArray,h=g.i;e/=8;if(e%2||4>e||16<e)throw new sjcl.exception.invalid("ccm: invalid tag length");
if(0xffffffff<d.length||0xffffffff<b.length)throw new sjcl.exception.bug("ccm: can't deal with 4GiB or more data");c=sjcl.mode.ccm.na(a,d,c,e,g.bitLength(b)/8,f);for(d=0;d<b.length;d+=4)c=a.encrypt(h(c,b.slice(d,d+4).concat([0,0,0])));return g.clamp(c,8*e)},C:function(a,b,c,d,e,f){var g,h=sjcl.bitArray;g=h.i;var k=b.length,l=h.bitLength(b),n=k/50,m=n;c=h.concat([h.partial(8,f-1)],c).concat([0,0,0]).slice(0,4);d=h.bitSlice(g(d,a.encrypt(c)),0,e);if(!k)return{tag:d,data:[]};for(g=0;g<k;g+=4)g>n&&(sjcl.mode.ccm.fa(g/
k),n+=m),c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,l)}}};
sjcl.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");var g,h=sjcl.mode.ocb2.S,k=sjcl.bitArray,l=k.i,n=[0,0,0,0];c=h(a.encrypt(c));var m,p=[];d=d||[];e=e||64;for(g=0;g+4<b.length;g+=4)m=b.slice(g,g+4),n=l(n,m),p=p.concat(l(c,a.encrypt(l(c,m)))),c=h(c);m=b.slice(g);b=k.bitLength(m);g=a.encrypt(l(c,[0,0,0,b]));m=k.clamp(l(m.concat([0,0,0]),g),b);n=l(n,l(m.concat([0,0,0]),g));n=a.encrypt(l(n,l(c,h(c))));
d.length&&(n=l(n,f?d:sjcl.mode.ocb2.pmac(a,d)));return p.concat(k.concat(m,k.clamp(n,e)))},decrypt:function(a,b,c,d,e,f){if(128!==sjcl.bitArray.bitLength(c))throw new sjcl.exception.invalid("ocb iv must be 128 bits");e=e||64;var g=sjcl.mode.ocb2.S,h=sjcl.bitArray,k=h.i,l=[0,0,0,0],n=g(a.encrypt(c)),m,p,r=sjcl.bitArray.bitLength(b)-e,q=[];d=d||[];for(c=0;c+4<r/32;c+=4)m=k(n,a.decrypt(k(n,b.slice(c,c+4)))),l=k(l,m),q=q.concat(m),n=g(n);p=r-32*c;m=a.encrypt(k(n,[0,0,0,p]));m=k(m,h.clamp(b.slice(c),p).concat([0,
0,0]));l=k(l,m);l=a.encrypt(k(l,k(n,g(n))));d.length&&(l=k(l,f?d:sjcl.mode.ocb2.pmac(a,d)));if(!h.equal(h.clamp(l,e),h.bitSlice(b,r)))throw new sjcl.exception.corrupt("ocb: tag doesn't match");return q.concat(h.clamp(m,p))},pmac:function(a,b){var c,d=sjcl.mode.ocb2.S,e=sjcl.bitArray,f=e.i,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4<b.length;c+=4)h=d(h),g=f(g,a.encrypt(f(h,b.slice(c,c+4))));c=b.slice(c);128>e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0]));g=f(g,c);
return a.encrypt(f(d(f(h,d(h))),g))},S:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}};
sjcl.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);b=sjcl.bitArray;d=d||[];a=sjcl.mode.gcm.C(!0,a,f,d,c,e||128);return b.concat(a.data,a.tag)},decrypt:function(a,b,c,d,e){var f=b.slice(0),g=sjcl.bitArray,h=g.bitLength(f);e=e||128;d=d||[];e<=h?(b=g.bitSlice(f,h-e),f=g.bitSlice(f,0,h-e)):(b=f,f=[]);a=sjcl.mode.gcm.C(!1,a,f,d,c,e);if(!g.equal(a.tag,b))throw new sjcl.exception.corrupt("gcm: tag doesn't match");return a.data},ka:function(a,b){var c,d,e,f,g,h=sjcl.bitArray.i;e=[0,0,
0,0];f=b.slice(0);for(c=0;128>c;c++){(d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f));g=0!==(f[3]&1);for(d=3;0<d;d--)f[d]=f[d]>>>1|(f[d-1]&1)<<31;f[0]>>>=1;g&&(f[0]^=-0x1f000000)}return e},j:function(a,b,c){var d,e=c.length;b=b.slice(0);for(d=0;d<e;d+=4)b[0]^=0xffffffff&c[d],b[1]^=0xffffffff&c[d+1],b[2]^=0xffffffff&c[d+2],b[3]^=0xffffffff&c[d+3],b=sjcl.mode.gcm.ka(b,a);return b},C:function(a,b,c,d,e,f){var g,h,k,l,n,m,p,r,q=sjcl.bitArray;m=c.length;p=q.bitLength(c);r=q.bitLength(d);h=q.bitLength(e);
g=b.encrypt([0,0,0,0]);96===h?(e=e.slice(0),e=q.concat(e,[1])):(e=sjcl.mode.gcm.j(g,[0,0,0,0],e),e=sjcl.mode.gcm.j(g,e,[0,0,Math.floor(h/0x100000000),h&0xffffffff]));h=sjcl.mode.gcm.j(g,[0,0,0,0],d);n=e.slice(0);d=h.slice(0);a||(d=sjcl.mode.gcm.j(g,h,c));for(l=0;l<m;l+=4)n[3]++,k=b.encrypt(n),c[l]^=k[0],c[l+1]^=k[1],c[l+2]^=k[2],c[l+3]^=k[3];c=q.clamp(c,p);a&&(d=sjcl.mode.gcm.j(g,h,c));a=[Math.floor(r/0x100000000),r&0xffffffff,Math.floor(p/0x100000000),p&0xffffffff];d=sjcl.mode.gcm.j(g,d,a);k=b.encrypt(e);
d[0]^=k[0];d[1]^=k[1];d[2]^=k[2];d[3]^=k[3];return{tag:q.bitSlice(d,0,f),data:c}}};sjcl.misc.hmac=function(a,b){this.W=b=b||sjcl.hash.sha256;var c=[[],[]],d,e=b.prototype.blockSize/32;this.w=[new b,new b];a.length>e&&(a=b.hash(a));for(d=0;d<e;d++)c[0][d]=a[d]^909522486,c[1][d]=a[d]^1549556828;this.w[0].update(c[0]);this.w[1].update(c[1]);this.R=new b(this.w[0])};
sjcl.misc.hmac.prototype.encrypt=sjcl.misc.hmac.prototype.mac=function(a){if(this.aa)throw new sjcl.exception.invalid("encrypt on already updated hmac called!");this.update(a);return this.digest(a)};sjcl.misc.hmac.prototype.reset=function(){this.R=new this.W(this.w[0]);this.aa=!1};sjcl.misc.hmac.prototype.update=function(a){this.aa=!0;this.R.update(a)};sjcl.misc.hmac.prototype.digest=function(){var a=this.R.finalize(),a=(new this.W(this.w[1])).update(a).finalize();this.reset();return a};
sjcl.misc.pbkdf2=function(a,b,c,d,e){c=c||1E4;if(0>d||0>c)throw new sjcl.exception.invalid("invalid params to pbkdf2");"string"===typeof a&&(a=sjcl.codec.utf8String.toBits(a));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));e=e||sjcl.misc.hmac;a=new e(a);var f,g,h,k,l=[],n=sjcl.bitArray;for(k=1;32*l.length<(d||1);k++){e=f=a.encrypt(n.concat(b,[k]));for(g=1;g<c;g++)for(f=a.encrypt(f),h=0;h<f.length;h++)e[h]^=f[h];l=l.concat(e)}d&&(l=n.clamp(l,d));return l};
sjcl.prng=function(a){this.c=[new sjcl.hash.sha256];this.m=[0];this.P=0;this.H={};this.N=0;this.U={};this.Z=this.f=this.o=this.ha=0;this.b=[0,0,0,0,0,0,0,0];this.h=[0,0,0,0];this.L=void 0;this.M=a;this.D=!1;this.K={progress:{},seeded:{}};this.u=this.ga=0;this.I=1;this.J=2;this.ca=0x10000;this.T=[0,48,64,96,128,192,0x100,384,512,768,1024];this.da=3E4;this.ba=80};
sjcl.prng.prototype={randomWords:function(a,b){var c=[],d;d=this.isReady(b);var e;if(d===this.u)throw new sjcl.exception.notReady("generator isn't seeded");if(d&this.J){d=!(d&this.I);e=[];var f=0,g;this.Z=e[0]=(new Date).valueOf()+this.da;for(g=0;16>g;g++)e.push(0x100000000*Math.random()|0);for(g=0;g<this.c.length&&(e=e.concat(this.c[g].finalize()),f+=this.m[g],this.m[g]=0,d||!(this.P&1<<g));g++);this.P>=1<<this.c.length&&(this.c.push(new sjcl.hash.sha256),this.m.push(0));this.f-=f;f>this.o&&(this.o=
f);this.P++;this.b=sjcl.hash.sha256.hash(this.b.concat(e));this.L=new sjcl.cipher.aes(this.b);for(d=0;4>d&&(this.h[d]=this.h[d]+1|0,!this.h[d]);d++);}for(d=0;d<a;d+=4)0===(d+1)%this.ca&&y(this),e=z(this),c.push(e[0],e[1],e[2],e[3]);y(this);return c.slice(0,a)},setDefaultParanoia:function(a,b){if(0===a&&"Setting paranoia=0 will ruin your security; use it only for testing"!==b)throw new sjcl.exception.invalid("Setting paranoia=0 will ruin your security; use it only for testing");this.M=a},addEntropy:function(a,
b,c){c=c||"user";var d,e,f=(new Date).valueOf(),g=this.H[c],h=this.isReady(),k=0;d=this.U[c];void 0===d&&(d=this.U[c]=this.ha++);void 0===g&&(g=this.H[c]=0);this.H[c]=(this.H[c]+1)%this.c.length;switch(typeof a){case "number":void 0===b&&(b=1);this.c[g].update([d,this.N++,1,b,f,1,a|0]);break;case "object":c=Object.prototype.toString.call(a);if("[object Uint32Array]"===c){e=[];for(c=0;c<a.length;c++)e.push(a[c]);a=e}else for("[object Array]"!==c&&(k=1),c=0;c<a.length&&!k;c++)"number"!==typeof a[c]&&
(k=1);if(!k){if(void 0===b)for(c=b=0;c<a.length;c++)for(e=a[c];0<e;)b++,e=e>>>1;this.c[g].update([d,this.N++,2,b,f,a.length].concat(a))}break;case "string":void 0===b&&(b=a.length);this.c[g].update([d,this.N++,3,b,f,a.length]);this.c[g].update(a);break;default:k=1}if(k)throw new sjcl.exception.bug("random: addEntropy only supports number, array of numbers or string");this.m[g]+=b;this.f+=b;h===this.u&&(this.isReady()!==this.u&&A("seeded",Math.max(this.o,this.f)),A("progress",this.getProgress()))},
isReady:function(a){a=this.T[void 0!==a?a:this.M];return this.o&&this.o>=a?this.m[0]>this.ba&&(new Date).valueOf()>this.Z?this.J|this.I:this.I:this.f>=a?this.J|this.u:this.u},getProgress:function(a){a=this.T[a?a:this.M];return this.o>=a?1:this.f>a?1:this.f/a},startCollectors:function(){if(!this.D){this.a={loadTimeCollector:B(this,this.ma),mouseCollector:B(this,this.oa),keyboardCollector:B(this,this.la),accelerometerCollector:B(this,this.ea),touchCollector:B(this,this.qa)};if(window.addEventListener)window.addEventListener("load",
this.a.loadTimeCollector,!1),window.addEventListener("mousemove",this.a.mouseCollector,!1),window.addEventListener("keypress",this.a.keyboardCollector,!1),window.addEventListener("devicemotion",this.a.accelerometerCollector,!1),window.addEventListener("touchmove",this.a.touchCollector,!1);else if(document.attachEvent)document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector);else throw new sjcl.exception.bug("can't attach event");
this.D=!0}},stopCollectors:function(){this.D&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,!1),window.removeEventListener("mousemove",this.a.mouseCollector,!1),window.removeEventListener("keypress",this.a.keyboardCollector,!1),window.removeEventListener("devicemotion",this.a.accelerometerCollector,!1),window.removeEventListener("touchmove",this.a.touchCollector,!1)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",
this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.D=!1)},addEventListener:function(a,b){this.K[a][this.ga++]=b},removeEventListener:function(a,b){var c,d,e=this.K[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;c<f.length;c++)d=f[c],delete e[d]},la:function(){C(this,1)},oa:function(a){var b,c;try{b=a.x||a.clientX||a.offsetX||0,c=a.y||a.clientY||a.offsetY||0}catch(d){c=b=0}0!=b&&0!=c&&this.addEntropy([b,c],2,"mouse");C(this,0)},qa:function(a){a=
a.touches[0]||a.changedTouches[0];this.addEntropy([a.pageX||a.clientX,a.pageY||a.clientY],1,"touch");C(this,0)},ma:function(){C(this,2)},ea:function(a){a=a.accelerationIncludingGravity.x||a.accelerationIncludingGravity.y||a.accelerationIncludingGravity.z;if(window.orientation){var b=window.orientation;"number"===typeof b&&this.addEntropy(b,1,"accelerometer")}a&&this.addEntropy(a,2,"accelerometer");C(this,0)}};
function A(a,b){var c,d=sjcl.random.K[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;c<e.length;c++)e[c](b)}function C(a,b){"undefined"!==typeof window&&window.performance&&"function"===typeof window.performance.now?a.addEntropy(window.performance.now(),b,"loadtime"):a.addEntropy((new Date).valueOf(),b,"loadtime")}function y(a){a.b=z(a).concat(z(a));a.L=new sjcl.cipher.aes(a.b)}function z(a){for(var b=0;4>b&&(a.h[b]=a.h[b]+1|0,!a.h[b]);b++);return a.L.encrypt(a.h)}
function B(a,b){return function(){b.apply(a,arguments)}}sjcl.random=new sjcl.prng(6);
a:try{var D,E,F,G;if(G="undefined"!==typeof module&&module.exports){var H;try{H=require("crypto")}catch(a){H=null}G=E=H}if(G&&E.randomBytes)D=E.randomBytes(128),D=new Uint32Array((new Uint8Array(D)).buffer),sjcl.random.addEntropy(D,1024,"crypto['randomBytes']");else if("undefined"!==typeof window&&"undefined"!==typeof Uint32Array){F=new Uint32Array(32);if(window.crypto&&window.crypto.getRandomValues)window.crypto.getRandomValues(F);else if(window.msCrypto&&window.msCrypto.getRandomValues)window.msCrypto.getRandomValues(F);
else break a;sjcl.random.addEntropy(F,1024,"crypto['getRandomValues']")}}catch(a){"undefined"!==typeof window&&window.console&&(console.log("There was an error collecting entropy from the browser:"),console.log(a))}
sjcl.json={defaults:{v:1,iter:1E4,ks:128,ts:64,mode:"ccm",adata:"",cipher:"aes"},ja:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json,f=e.g({iv:sjcl.random.randomWords(4,0)},e.defaults),g;e.g(f,c);c=f.adata;"string"===typeof f.salt&&(f.salt=sjcl.codec.base64.toBits(f.salt));"string"===typeof f.iv&&(f.iv=sjcl.codec.base64.toBits(f.iv));if(!sjcl.mode[f.mode]||!sjcl.cipher[f.cipher]||"string"===typeof a&&100>=f.iter||64!==f.ts&&96!==f.ts&&128!==f.ts||128!==f.ks&&192!==f.ks&&0x100!==f.ks||2>f.iv.length||
4<f.iv.length)throw new sjcl.exception.invalid("json encrypt: invalid parameters");"string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,f),a=g.key.slice(0,f.ks/32),f.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.publicKey&&(g=a.kem(),f.kemtag=g.tag,a=g.key.slice(0,f.ks/32));"string"===typeof b&&(b=sjcl.codec.utf8String.toBits(b));"string"===typeof c&&(f.adata=c=sjcl.codec.utf8String.toBits(c));g=new sjcl.cipher[f.cipher](a);e.g(d,f);d.key=a;f.ct="ccm"===f.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&
b instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.encrypt(g,b,f.iv,c,f.ts):sjcl.mode[f.mode].encrypt(g,b,f.iv,c,f.ts);return f},encrypt:function(a,b,c,d){var e=sjcl.json,f=e.ja.apply(e,arguments);return e.encode(f)},ia:function(a,b,c,d){c=c||{};d=d||{};var e=sjcl.json;b=e.g(e.g(e.g({},e.defaults),b),c,!0);var f,g;f=b.adata;"string"===typeof b.salt&&(b.salt=sjcl.codec.base64.toBits(b.salt));"string"===typeof b.iv&&(b.iv=sjcl.codec.base64.toBits(b.iv));if(!sjcl.mode[b.mode]||!sjcl.cipher[b.cipher]||"string"===
typeof a&&100>=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&0x100!==b.ks||!b.iv||2>b.iv.length||4<b.iv.length)throw new sjcl.exception.invalid("json decrypt: invalid parameters");"string"===typeof a?(g=sjcl.misc.cachedPbkdf2(a,b),a=g.key.slice(0,b.ks/32),b.salt=g.salt):sjcl.ecc&&a instanceof sjcl.ecc.elGamal.secretKey&&(a=a.unkem(sjcl.codec.base64.toBits(b.kemtag)).slice(0,b.ks/32));"string"===typeof f&&(f=sjcl.codec.utf8String.toBits(f));g=new sjcl.cipher[b.cipher](a);f="ccm"===
b.mode&&sjcl.arrayBuffer&&sjcl.arrayBuffer.ccm&&b.ct instanceof ArrayBuffer?sjcl.arrayBuffer.ccm.decrypt(g,b.ct,b.iv,b.tag,f,b.ts):sjcl.mode[b.mode].decrypt(g,b.ct,b.iv,f,b.ts);e.g(d,b);d.key=a;return 1===c.raw?f:sjcl.codec.utf8String.fromBits(f)},decrypt:function(a,b,c,d){var e=sjcl.json;return e.ia(a,e.decode(b),c,d)},encode:function(a){var b,c="{",d="";for(b in a)if(a.hasOwnProperty(b)){if(!b.match(/^[a-z0-9]+$/i))throw new sjcl.exception.invalid("json encode: invalid property name");c+=d+'"'+
b+'":';d=",";switch(typeof a[b]){case "number":case "boolean":c+=a[b];break;case "string":c+='"'+escape(a[b])+'"';break;case "object":c+='"'+sjcl.codec.base64.fromBits(a[b],0)+'"';break;default:throw new sjcl.exception.bug("json encode: unsupported type");}}return c+"}"},decode:function(a){a=a.replace(/\s/g,"");if(!a.match(/^\{.*\}$/))throw new sjcl.exception.invalid("json decode: this isn't json!");a=a.replace(/^\{|\}$/g,"").split(/,/);var b={},c,d;for(c=0;c<a.length;c++){if(!(d=a[c].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i)))throw new sjcl.exception.invalid("json decode: this isn't json!");
null!=d[3]?b[d[2]]=parseInt(d[3],10):null!=d[4]?b[d[2]]=d[2].match(/^(ct|adata|salt|iv)$/)?sjcl.codec.base64.toBits(d[4]):unescape(d[4]):null!=d[5]&&(b[d[2]]="true"===d[5])}return b},g:function(a,b,c){void 0===a&&(a={});if(void 0===b)return a;for(var d in b)if(b.hasOwnProperty(d)){if(c&&void 0!==a[d]&&a[d]!==b[d])throw new sjcl.exception.invalid("required parameter overridden");a[d]=b[d]}return a},sa:function(a,b){var c={},d;for(d in a)a.hasOwnProperty(d)&&a[d]!==b[d]&&(c[d]=a[d]);return c},ra:function(a,
b){var c={},d;for(d=0;d<b.length;d++)void 0!==a[b[d]]&&(c[b[d]]=a[b[d]]);return c}};sjcl.encrypt=sjcl.json.encrypt;sjcl.decrypt=sjcl.json.decrypt;sjcl.misc.pa={};sjcl.misc.cachedPbkdf2=function(a,b){var c=sjcl.misc.pa,d;b=b||{};d=b.iter||1E3;c=c[a]=c[a]||{};d=c[d]=c[d]||{firstSalt:b.salt&&b.salt.length?b.salt.slice(0):sjcl.random.randomWords(2,0)};c=void 0===b.salt?d.firstSalt:b.salt;d[c]=d[c]||sjcl.misc.pbkdf2(a,c,b.iter);return{key:d[c].slice(0),salt:c.slice(0)}};
"undefined"!==typeof module&&module.exports&&(module.exports=sjcl);"function"===typeof define&&define([],function(){return sjcl}); |
export { default } from './TableCell';
|
version https://git-lfs.github.com/spec/v1
oid sha256:04f2d611408cbea533a052f39f087a218fec031783e0d508f118ca0db86785f0
size 2964
|
/*
* Module dependencies.
*/
var t = require('t');
var FormView = require('form-view');
var template = require('./signup-form');
var title = require('title');
/**
* Expose SignupForm.
*/
module.exports = SignupForm;
/**
* Proposal Comments view
*
* @return {SignupForm} `SignupForm` instance.
* @api public
*/
function SignupForm (reference) {
if (!(this instanceof SignupForm)) {
return new SignupForm(reference);
};
FormView.call(this, template, { reference: reference });
}
/**
* Inherit from `FormView`
*/
FormView(SignupForm);
SignupForm.prototype.switchOn = function() {
this.on('success', this.bound('showSuccess'));
};
/**
* Show success message
*/
SignupForm.prototype.showSuccess = function() {
var form = this.find('#signup-form');
var success = this.find('#signup-message');
var welcomeMessage = this.find('#signup-message h1');
var firstName = this.get('firstName');
var lastName = this.get('lastName');
var fullname = firstName + ' ' + lastName;
title(t('Signup complete'));
var message = t("Welcome, {name}!", { name: fullname });
welcomeMessage.html(message);
form.addClass('hide');
success.removeClass('hide');
}
|
define(['jquery'], function($) {
function Library() {
// Returns true or false if the specified element exists.
this.elExists = function(name) {
return $('#' + name).length > 0;
};
// Converts 123456789 into 123,456,789.
this.formatNum = function(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
this.reduceNum = function(number) {
if (number >= 100000000000000000 || number <= -100000000000000000) {
//101Q
return Math.floor(number/1000000000000000) + 'Q';
}
else if (number >= 1000000000000000 || number <= -1000000000000000) {
//75.3Q
return (Math.floor(number/100000000000000) / 10) + 'Q';
}
else if (number >= 100000000000000 || number <= -100000000000000) {
//101T
return Math.floor(number/1000000000000) + 'T';
}
else if (number >= 1000000000000 || number <= -1000000000000) {
//75.3T
return (Math.floor(number/100000000000) / 10) + 'T';
}
else if (number >= 100000000000 || number <= -100000000000) {
//101B
return Math.floor(number/1000000000) + 'B';
}
else if (number >= 1000000000 || number <= -1000000000) {
//75.3B
return (Math.floor(number/100000000) / 10) + 'B';
}
else if (number >= 100000000 || number <= -100000000) {
//101M
return Math.floor(number/1000000) + 'M';
}
else if (number >= 1000000 || number <= -1000000) {
//75.3M
return (Math.floor(number/100000) / 10) + 'M';
}
else if (number >= 10000 || number <= -10000) {
//123k
return Math.floor(number/1000) + 'k';
}
else {
//8765
return Math.floor(number) || "0";
}
},
// take an array of day:hour:minute:second arrival time and convert to UST
//
this.formatDateEarliestToUST = function(inArray) {
var seconds = (((inArray[0] * 24 + inArray[1]) * 60) + inArray[2]) * 60 + inArray[3];
var arrivalTime = Date.now() + seconds * 1000;
return arrivalTime.toUTCString();
};
// take an array of day:hour:minute:second arrival time and convert to the browsers localtime
this.formatDateEarliestToLocal = function(inArray) {
var utcString = this.formatDateEarliestToUST(inArray);
var arrivalTime = Date(utcString);
return arrivalTime.toString();
};
// This was stolen straight from the original Lacuna Web Client.
this.formatTime = function(input) {
if (input < 0) {
return '';
}
var secondsInDay = 60 * 60 * 24,
secondsInHour = 60 * 60,
day = Math.floor(input / secondsInDay),
hleft = input % secondsInDay,
hour = Math.floor(hleft / secondsInHour),
sleft = hleft % secondsInHour,
min = Math.floor(sleft / 60),
seconds = Math.floor(sleft % 60);
if (day > 0) {
return [day, this.lengthen(hour), this.lengthen(min), this.lengthen(seconds)].join(':');
}
else if (hour > 0) {
return [hour, this.lengthen(min), this.lengthen(seconds)].join(':');
}
else {
return [this.lengthen(min), this.lengthen(seconds)].join(':');
}
};
this.lengthen = function(number) {
number = number.toString();
if (number.length === 1) {
return "0" + number;
}
else {
return number;
}
};
this.upperFirstChar = function(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
};
this.foodTypes = [
"algae",
"apple",
"bean",
"beetle",
"burger",
"bread",
"cheese",
"chip",
"cider",
"corn",
"fungus",
"lapis",
"meal",
"milk",
"pancake",
"pie",
"potato",
"root",
"shake",
"soup",
"syrup",
"wheat"
];
this.oreTypes = [
"anthracite",
"bauxite",
"beryl",
"chromite",
"chalcopyrite",
"fluorite",
"galena",
"goethite",
"gold",
"gypsum",
"halite",
"kerogen",
"magnetite",
"methane",
"monazite",
"rutile",
"sulfur",
"trona",
"uraninite",
"zircon"
];
// function to return an interval with notification
// 'millis' is the time in milliseconds between notifications
// 'count' is the number of times to iterate.
//
this.notifyTimer = function(millis, count) {
var deferred = $.Deferred();
if (count <= 0) {
deferred.reject("Negative repeat count "+count);
}
var iteration = 0;
var id = setInterval(function() {
deferred.notify(++iteration, count);
if (iteration >= count) {
clearInterval(id);
deferred.resolve();
}
}, millis);
return deferred.promise();
};
// function to notify forever (well, at least until it goes out of scope)
//
this.notifyTimerInfinite = function(millis) {
var deferred = $.Deferred();
var iteration = 0;
var id = setInterval(function() {
deferred.notify(++iteration);
}, millis);
return deferred.promise();
};
}
return new Library();
});
|
/*!
* jQuery JavaScript Library v1.9.1 -ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-deprecated
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-3-15
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<9
// For `typeof node.method` instead of `node.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.9.1 -ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-deprecated",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support, all, a,
input, select, fragment,
opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: div.firstChild.nodeType === 3,
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: a.getAttribute("href") === "/a",
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
checkOn: !!input.value,
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: document.compatMode === "CSS1Compat",
// Will be defined later
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var i, l, thisCache,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
// Try to fetch any internally stored data first
return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
}
this.each(function() {
jQuery.data( this, key, value );
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
hooks.cur = fn;
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, notxml, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
// In IE9+, Flash objects don't have .getAttribute (#12945)
// Support: IE9+
if ( typeof elem.getAttribute !== core_strundefined ) {
ret = elem.getAttribute( name );
}
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( rboolean.test( name ) ) {
// Set corresponding property to false for boolean attributes
// Also clear defaultChecked/defaultSelected (if appropriate) for IE<8
if ( !getSetAttribute && ruseDefault.test( name ) ) {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
} else {
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
var
// Use .prop to determine if this attribute is understood as boolean
prop = jQuery.prop( elem, name ),
// Fetch it accordingly
attr = typeof prop === "boolean" && elem.getAttribute( name ),
detail = typeof prop === "boolean" ?
getSetInput && getSetAttribute ?
attr != null :
// oldIE fabricates an empty string for missing boolean attributes
// and conflates checked/selected into attroperties
ruseDefault.test( name ) ?
elem[ jQuery.camelCase( "default-" + name ) ] :
!!attr :
// fetch an attribute node for properties not recognized as boolean
elem.getAttributeNode( name );
return detail && detail.value !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
// fix oldIE value attroperty
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return jQuery.nodeName( elem, "input" ) ?
// Ignore the value *property* by using defaultValue
elem.defaultValue :
ret && ret.specified ? ret.value : undefined;
},
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret == null ? undefined : ret;
}
});
});
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
event.isTrigger = true;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur != this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
}
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== document.activeElement && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === document.activeElement && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /^[^{]+\{\s*\[native code/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
while ( (elem = this[i++]) ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, ret, self,
len = this.length;
if ( typeof selector !== "string" ) {
self = this;
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
ret = [];
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, this[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = ( this.selector ? this.selector + " " : "" ) + selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true) );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, false, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
var isFunc = jQuery.isFunction( value );
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( !isFunc && typeof value !== "string" ) {
value = jQuery( value ).not( this ).detach();
}
return this.domManip( [ value ], true, function( elem ) {
var next = this.nextSibling,
parent = this.parentNode;
if ( parent ) {
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
});
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, table ? self.html() : undefined );
}
self.domManip( args, table, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
node,
i
);
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery.ajax({
url: node.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
var attr = elem.getAttributeNode("type");
elem.type = ( attr && attr.specified ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.hover = function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
};
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: replace with regexp /(uid=)(\d+)/ returns
es5id: 15.5.4.11_A3_T2
description: replaceValue is "$11" + '15'
---*/
var __str = 'uid=31';
var __re = /(uid=)(\d+)/;
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__str.replace(__re, "$11" + '15')!=='uid=115') {
$ERROR('#1: var __str = \'uid=31\'; var __re = /(uid=)(\d+)/; __str.replace(__re, "$11" + \'15\')===\'uid=115\'. Actual: '+__str.replace(__re, "$11" + '15'));
}
//
//////////////////////////////////////////////////////////////////////////////
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
If the argument len is a Number and ToUint32(len) is not equal to len,
a RangeError exception is thrown
es5id: 15.4.2.2_A2.2_T2
description: Use try statement. len = NaN, +/-Infinity
---*/
//CHECK#1
try {
new Array(NaN);
$ERROR('#1.1: new Array(NaN) throw RangeError. Actual: ' + (new Array(NaN)));
} catch(e) {
if ((e instanceof RangeError) !== true) {
$ERROR('#1.2: new Array(NaN) throw RangeError. Actual: ' + (e));
}
}
//CHECK#2
try {
new Array(Number.POSITIVE_INFINITY);
$ERROR('#2.1: new Array(Number.POSITIVE_INFINITY) throw RangeError. Actual: ' + (new Array(Number.POSITIVE_INFINITY)));
} catch(e) {
if ((e instanceof RangeError) !== true) {
$ERROR('#2.2: new Array(Number.POSITIVE_INFINITY) throw RangeError. Actual: ' + (e));
}
}
//CHECK#3
try {
new Array(Number.NEGATIVE_INFINITY);
$ERROR('#3.1: new Array(Number.NEGATIVE_INFINITY) throw RangeError. Actual: ' + (new Array(Number.NEGATIVE_INFINITY)));
} catch(e) {
if ((e instanceof RangeError) !== true) {
$ERROR('#3.2: new Array(Number.NEGATIVE_INFINITY) throw RangeError. Actual: ' + (e));
}
}
|
it("should handle the pug loader correctly", function() {
expect(require("!pug-loader?self!../_resources/template.pug")({ abc: "abc" })).toBe("<p>selfabc</p><h1>included</h1>");
expect(require("../_resources/template.pug")({ abc: "abc" })).toBe("<p>abc</p><h1>included</h1>");
});
|
/**
* a HUD container and child items
*/
game.HUD = game.HUD || {};
game.HUD.Container = me.ObjectContainer.extend({
init: function() {
// call the constructor
this.parent();
// persistent across level change
this.isPersistent = true;
// non collidable
this.collidable = false;
// make sure our object is always draw first
this.z = Infinity;
// give a name
this.name = "HUD";
// add our child score object at the right-bottom position
this.addChild(new game.HUD.ScoreItem(630, 440));
}
});
/**
* a basic HUD item to display score
*/
game.HUD.ScoreItem = me.Renderable.extend( {
/**
* constructor
*/
init: function(x, y) {
// call the parent constructor
// (size does not matter here)
this.parent(new me.Vector2d(x, y), 10, 10);
// create a font
this.font = new me.BitmapFont("32x32_font", 32);
this.font.set("right");
// local copy of the global score
this.score = -1;
// make sure we use screen coordinates
this.floating = true;
},
/**
* update function
*/
update : function () {
// we don't do anything fancy here, so just
// return true if the score has been updated
if (this.score !== game.data.score) {
this.score = game.data.score;
return true;
}
return false;
},
/**
* draw the score
*/
draw : function (context) {
this.font.draw (context, game.data.score, this.pos.x, this.pos.y);
}
});
|
/*
* volume.js: OpenStack Block Storage volume
*
* (C) 2014 Rackspace
* Ken Perkins
* MIT LICENSE
*
*/
var util = require('util'),
base = require('../../core/base'),
_ = require('lodash');
var Volume = exports.Volume = function Volume(client, details) {
base.Model.call(this, client, details);
};
util.inherits(Volume, base.Model);
Volume.prototype._setProperties = function (details) {
this.id = details.id;
this.status = details.status;
this.name = details.name || details['display_name'];
this.description = details.description || details['display_description'];
this.createdAt = details['created_at'];
this.size = details.size;
this.volumeType = details.volumeType || details['volume_type'];
this.attachments = details.attachments;
this.snapshotId = details.snapshotId || details['snapshot_id'];
};
Volume.prototype.toJSON = function () {
return _.pick(this, ['id', 'status', 'name', 'description', 'createdAt',
'size', 'volumeType', 'attachments', 'snapshotId']);
};
|
/* ===========================================================
* trumbowyg.table.custom.js v2.0
* Table plugin for Trumbowyg
* http://alex-d.github.com/Trumbowyg
* ===========================================================
* Author : Sven Dunemann [dunemann@forelabs.eu]
*/
(function ($) {
'use strict';
var defaultOptions = {
rows: 8,
columns: 8,
styler: 'table'
};
$.extend(true, $.trumbowyg, {
langs: {
// jshint camelcase:false
en: {
table: 'Insert table',
tableAddRow: 'Add row',
tableAddRowAbove: 'Add row above',
tableAddColumnLeft: 'Add column to the left',
tableAddColumn: 'Add column to the right',
tableDeleteRow: 'Delete row',
tableDeleteColumn: 'Delete column',
tableDestroy: 'Delete table',
error: 'Error'
},
cs: {
table: 'Vytvořit příkaz Table',
tableAddRow: 'Přidat řádek',
tableAddRowAbove: 'Přidat řádek',
tableAddColumnLeft: 'Přidat sloupec',
tableAddColumn: 'Přidat sloupec',
error: 'Chyba'
},
da: {
table: 'Indsæt tabel',
tableAddRow: 'Tilføj række',
tableAddRowAbove: 'Tilføj række',
tableAddColumnLeft: 'Tilføj kolonne',
tableAddColumn: 'Tilføj kolonne',
tableDeleteRow: 'Slet række',
tableDeleteColumn: 'Slet kolonne',
tableDestroy: 'Slet tabel',
error: 'Fejl'
},
de: {
table: 'Tabelle einfügen',
tableAddRow: 'Zeile hinzufügen',
tableAddRowAbove: 'Zeile hinzufügen',
tableAddColumnLeft: 'Spalte hinzufügen',
tableAddColumn: 'Spalte hinzufügen',
tableDeleteRow: 'Zeile löschen',
tableDeleteColumn: 'Spalte löschen',
tableDestroy: 'Tabelle löschen',
error: 'Error'
},
fr: {
table: 'Insérer un tableau',
tableAddRow: 'Ajouter des lignes',
tableAddRowAbove: 'Ajouter des lignes',
tableAddColumnLeft: 'Ajouter des colonnes',
tableAddColumn: 'Ajouter des colonnes',
tableDeleteRow: 'Effacer la ligne',
tableDeleteColumn: 'Effacer la colonne',
tableDestroy: 'Effacer le tableau',
error: 'Erreur'
},
hu: {
table: 'Táblázat beszúrás',
tableAddRow: 'Sor hozzáadás',
tableAddRowAbove: 'Sor beszúrás fönt',
tableAddColumnLeft: 'Sor beszúrás balra',
tableAddColumn: 'Sor beszúrás jobbra',
tableDeleteRow: 'Sor törlés',
tableDeleteColumn: 'Oszlop törlés',
tableDestroy: 'Táblázat törlés',
error: 'Hiba'
},
id: {
table: 'Sisipkan tabel',
tableAddRow: 'Sisipkan baris',
tableAddRowAbove: 'Sisipkan baris',
tableAddColumnLeft: 'Sisipkan kolom',
tableAddColumn: 'Sisipkan kolom',
tableDeleteRow: 'Hapus baris',
tableDeleteColumn: 'Hapus kolom',
tableDestroy: 'Hapus tabel',
error: 'Galat'
},
ja: {
table: '表の挿入',
tableAddRow: '行の追加',
tableAddRowAbove: '行の追加',
tableAddColumnLeft: '列の追加',
tableAddColumn: '列の追加',
error: 'エラー'
},
ko: {
table: '표 넣기',
tableAddRow: '줄 추가',
tableAddRowAbove: '줄 추가',
tableAddColumnLeft: '칸 추가',
tableAddColumn: '칸 추가',
tableDeleteRow: '줄 삭제',
tableDeleteColumn: '칸 삭제',
tableDestroy: '표 지우기',
error: '에러'
},
pt_br: {
table: 'Inserir tabela',
tableAddRow: 'Adicionar linha',
tableAddRowAbove: 'Adicionar linha',
tableAddColumnLeft: 'Adicionar coluna',
tableAddColumn: 'Adicionar coluna',
tableDeleteRow: 'Deletar linha',
tableDeleteColumn: 'Deletar coluna',
tableDestroy: 'Deletar tabela',
error: 'Erro'
},
ru: {
table: 'Вставить таблицу',
tableAddRow: 'Добавить строку',
tableAddRowAbove: 'Добавить строку',
tableAddColumnLeft: 'Добавить столбец',
tableAddColumn: 'Добавить столбец',
tableDeleteRow: 'Удалить строку',
tableDeleteColumn: 'Удалить столбец',
tableDestroy: 'Удалить таблицу',
error: 'Ошибка'
},
sk: {
table: 'Vytvoriť tabuľky',
tableAddRow: 'Pridať riadok',
tableAddRowAbove: 'Pridať riadok',
tableAddColumnLeft: 'Pridať stĺpec',
tableAddColumn: 'Pridať stĺpec',
error: 'Chyba'
},
tr: {
table: 'Tablo ekle',
tableAddRow: 'Satır ekle',
tableAddRowAbove: 'Satır ekle',
tableAddColumnLeft: 'Kolon ekle',
tableAddColumn: 'Kolon ekle',
error: 'Hata'
},
zh_tw: {
table: '插入表格',
tableAddRow: '加入行',
tableAddRowAbove: '加入行',
tableAddColumnLeft: '加入列',
tableAddColumn: '加入列',
tableDeleteRow: '刪除行',
tableDeleteColumn: '刪除列',
tableDestroy: '刪除表格',
error: '錯誤'
},
// jshint camelcase:true
},
plugins: {
table: {
init: function (t) {
t.o.plugins.table = $.extend(true, {}, defaultOptions, t.o.plugins.table || {});
var buildButtonDef = {
fn: function () {
t.saveRange();
var btnName = 'table';
var dropdownPrefix = t.o.prefix + 'dropdown',
dropdownOptions = { // the dropdown
class: dropdownPrefix + '-' + btnName + ' ' + dropdownPrefix + ' ' + t.o.prefix + 'fixed-top'
};
dropdownOptions['data-' + dropdownPrefix] = btnName;
var $dropdown = $('<div/>', dropdownOptions);
if (t.$box.find('.' + dropdownPrefix + '-' + btnName).length === 0) {
t.$box.append($dropdown.hide());
} else {
$dropdown = t.$box.find('.' + dropdownPrefix + '-' + btnName);
}
// clear dropdown
$dropdown.html('');
// when active table show AddRow / AddColumn
if (t.$box.find('.' + t.o.prefix + 'table-button').hasClass(t.o.prefix + 'active-button')) {
$dropdown.append(t.buildSubBtn('tableAddRowAbove'));
$dropdown.append(t.buildSubBtn('tableAddRow'));
$dropdown.append(t.buildSubBtn('tableAddColumnLeft'));
$dropdown.append(t.buildSubBtn('tableAddColumn'));
$dropdown.append(t.buildSubBtn('tableDeleteRow'));
$dropdown.append(t.buildSubBtn('tableDeleteColumn'));
$dropdown.append(t.buildSubBtn('tableDestroy'));
} else {
var tableSelect = $('<table/>');
$('<tbody/>').appendTo(tableSelect);
for (var i = 0; i < t.o.plugins.table.rows; i += 1) {
var row = $('<tr/>').appendTo(tableSelect);
for (var j = 0; j < t.o.plugins.table.columns; j += 1) {
$('<td/>').appendTo(row);
}
}
tableSelect.find('td').on('mouseover', tableAnimate);
tableSelect.find('td').on('mousedown', tableBuild);
$dropdown.append(tableSelect);
$dropdown.append($('<div class="trumbowyg-table-size">1x1</div>'));
}
t.dropdown(btnName);
}
};
var tableAnimate = function(columnEvent) {
var column = $(columnEvent.target),
table = column.closest('table'),
colIndex = this.cellIndex,
rowIndex = this.parentNode.rowIndex;
// reset all columns
table.find('td').removeClass('active');
for (var i = 0; i <= rowIndex; i += 1) {
for (var j = 0; j <= colIndex; j += 1) {
table.find('tr:nth-of-type('+(i+1)+')').find('td:nth-of-type('+(j+1)+')').addClass('active');
}
}
// set label
table.next('.trumbowyg-table-size').html((colIndex+1) + 'x' + (rowIndex+1));
};
var tableBuild = function() {
t.saveRange();
var tabler = $('<table/>');
$('<tbody/>').appendTo(tabler);
if (t.o.plugins.table.styler) {
tabler.attr('class', t.o.plugins.table.styler);
}
var colIndex = this.cellIndex,
rowIndex = this.parentNode.rowIndex;
for (var i = 0; i <= rowIndex; i += 1) {
var row = $('<tr></tr>').appendTo(tabler);
for (var j = 0; j <= colIndex; j += 1) {
$('<td/>').appendTo(row);
}
}
t.range.deleteContents();
t.range.insertNode(tabler[0]);
t.$c.trigger('tbwchange');
};
var addRow = {
title: t.lang.tableAddRow,
text: t.lang.tableAddRow,
ico: 'row-below',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode;
var focusedRow = $(node).closest('tr');
var table = $(node).closest('table');
if(table.length > 0) {
var row = $('<tr/>');
// add columns according to current columns count
for (var i = 0; i < table.find('tr')[0].childElementCount; i += 1) {
$('<td/>').appendTo(row);
}
// add row to table
focusedRow.after(row);
}
t.syncCode();
}
};
var addRowAbove = {
title: t.lang.tableAddRowAbove,
text: t.lang.tableAddRowAbove,
ico: 'row-above',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode;
var focusedRow = $(node).closest('tr');
var table = $(node).closest('table');
if(table.length > 0) {
var row = $('<tr/>');
// add columns according to current columns count
for (var i = 0; i < table.find('tr')[0].childElementCount; i += 1) {
$('<td/>').appendTo(row);
}
// add row to table
focusedRow.before(row);
}
t.syncCode();
}
};
var addColumn = {
title: t.lang.tableAddColumn,
text: t.lang.tableAddColumn,
ico: 'col-right',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode;
var focusedCol = $(node).closest('td');
var table = $(node).closest('table');
var focusedColIdx = focusedCol.index();
if(table.length > 0) {
$(table).find('tr').each(function() {
$($(this).children()[focusedColIdx]).after('<td></td>');
});
}
t.syncCode();
}
};
var addColumnLeft = {
title: t.lang.tableAddColumnLeft,
text: t.lang.tableAddColumnLeft,
ico: 'col-left',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode;
var focusedCol = $(node).closest('td');
var table = $(node).closest('table');
var focusedColIdx = focusedCol.index();
if(table.length > 0) {
$(table).find('tr').each(function() {
$($(this).children()[focusedColIdx]).before('<td></td>');
});
}
t.syncCode();
}
};
var destroy = {
title: t.lang.tableDestroy,
text: t.lang.tableDestroy,
ico: 'table-delete',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode,
table = $(node).closest('table');
table.remove();
t.syncCode();
}
};
var deleteRow = {
title: t.lang.tableDeleteRow,
text: t.lang.tableDeleteRow,
ico: 'row-delete',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode,
row = $(node).closest('tr');
row.remove();
t.syncCode();
}
};
var deleteColumn = {
title: t.lang.tableDeleteColumn,
text: t.lang.tableDeleteColumn,
ico: 'col-delete',
fn: function () {
t.saveRange();
var node = t.doc.getSelection().focusNode,
table = $(node).closest('table'),
td = $(node).closest('td'),
cellIndex = td.index();
$(table).find('tr').each(function() {
$(this).find('td:eq(' + cellIndex + ')').remove();
});
t.syncCode();
}
};
t.addBtnDef('table', buildButtonDef);
t.addBtnDef('tableAddRowAbove', addRowAbove);
t.addBtnDef('tableAddRow', addRow);
t.addBtnDef('tableAddColumnLeft', addColumnLeft);
t.addBtnDef('tableAddColumn', addColumn);
t.addBtnDef('tableDeleteRow', deleteRow);
t.addBtnDef('tableDeleteColumn', deleteColumn);
t.addBtnDef('tableDestroy', destroy);
}
}
}
});
})(jQuery);
|
define({
label: {
foo: 'hello'
}
}); |
import { withAmp, useAmp } from 'next/amp'
function Home() {
const config = {}
return <h1>My AMP Page</h1>
}
export const config = {
foo: 'bar',
}
export default withAmp(Home)
|
/* Tabulator v4.2.0 (c) Oliver Folkerd */
var Persistence = function Persistence(table) {
this.table = table; //hold Tabulator object
this.mode = "";
this.id = "";
this.persistProps = ["field", "width", "visible"];
};
//setup parameters
Persistence.prototype.initialize = function (mode, id) {
//determine persistent layout storage type
this.mode = mode !== true ? mode : typeof window.localStorage !== 'undefined' ? "local" : "cookie";
//set storage tag
this.id = "tabulator-" + (id || this.table.element.getAttribute("id") || "");
};
//load saved definitions
Persistence.prototype.load = function (type, current) {
var data = this.retreiveData(type);
if (current) {
data = data ? this.mergeDefinition(current, data) : current;
}
return data;
};
//retreive data from memory
Persistence.prototype.retreiveData = function (type) {
var data = "",
id = this.id + (type === "columns" ? "" : "-" + type);
switch (this.mode) {
case "local":
data = localStorage.getItem(id);
break;
case "cookie":
//find cookie
var cookie = document.cookie,
cookiePos = cookie.indexOf(id + "="),
end = void 0;
//if cookie exists, decode and load column data into tabulator
if (cookiePos > -1) {
cookie = cookie.substr(cookiePos);
end = cookie.indexOf(";");
if (end > -1) {
cookie = cookie.substr(0, end);
}
data = cookie.replace(id + "=", "");
}
break;
default:
console.warn("Persistance Load Error - invalid mode selected", this.mode);
}
return data ? JSON.parse(data) : false;
};
//merge old and new column defintions
Persistence.prototype.mergeDefinition = function (oldCols, newCols) {
var self = this,
output = [];
// oldCols = oldCols || [];
newCols = newCols || [];
newCols.forEach(function (column, to) {
var from = self._findColumn(oldCols, column);
if (from) {
from.width = column.width;
from.visible = column.visible;
if (from.columns) {
from.columns = self.mergeDefinition(from.columns, column.columns);
}
output.push(from);
}
});
oldCols.forEach(function (column, i) {
var from = self._findColumn(newCols, column);
if (!from) {
if (output.length > i) {
output.splice(i, 0, column);
} else {
output.push(column);
}
}
});
return output;
};
//find matching columns
Persistence.prototype._findColumn = function (columns, subject) {
var type = subject.columns ? "group" : subject.field ? "field" : "object";
return columns.find(function (col) {
switch (type) {
case "group":
return col.title === subject.title && col.columns.length === subject.columns.length;
break;
case "field":
return col.field === subject.field;
break;
case "object":
return col === subject;
break;
}
});
};
//save data
Persistence.prototype.save = function (type) {
var data = {};
switch (type) {
case "columns":
data = this.parseColumns(this.table.columnManager.getColumns());
break;
case "filter":
data = this.table.modules.filter.getFilters();
break;
case "sort":
data = this.validateSorters(this.table.modules.sort.getSort());
break;
}
var id = this.id + (type === "columns" ? "" : "-" + type);
this.saveData(id, data);
};
//ensure sorters contain no function data
Persistence.prototype.validateSorters = function (data) {
data.forEach(function (item) {
item.column = item.field;
delete item.field;
});
return data;
};
//save data to chosed medium
Persistence.prototype.saveData = function (id, data) {
data = JSON.stringify(data);
switch (this.mode) {
case "local":
localStorage.setItem(id, data);
break;
case "cookie":
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 10000);
//save cookie
document.cookie = id + "=" + data + "; expires=" + expireDate.toUTCString();
break;
default:
console.warn("Persistance Save Error - invalid mode selected", this.mode);
}
};
//build premission list
Persistence.prototype.parseColumns = function (columns) {
var self = this,
definitions = [];
columns.forEach(function (column) {
var def = {};
if (column.isGroup) {
def.title = column.getDefinition().title;
def.columns = self.parseColumns(column.getColumns());
} else {
def.title = column.getDefinition().title;
def.field = column.getField();
def.width = column.getWidth();
def.visible = column.visible;
}
definitions.push(def);
});
return definitions;
};
Tabulator.prototype.registerModule("persistence", Persistence); |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
(function(){CKEDITOR.plugins.add("selectall",{lang:"af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn",icons:"selectall",hidpi:!0,init:function(b){b.addCommand("selectAll",{modes:{wysiwyg:1,source:1},exec:function(a){var b=a.editable();if(b.is("textarea"))a=b.$,CKEDITOR.env.ie?a.createTextRange().execCommand("SelectAll"):(a.selectionStart=
0,a.selectionEnd=a.value.length),a.focus();else{if(b.is("body"))a.document.$.execCommand("SelectAll",!1,null);else{var c=a.createRange();c.selectNodeContents(b);c.select()}a.forceNextSelectionCheck();a.selectionChange()}},canUndo:!1});b.ui.addButton&&b.ui.addButton("SelectAll",{label:b.lang.selectall.toolbar,command:"selectAll",toolbar:"selection,10"})}})})(); |
(function (global, factory) {
if (typeof exports === "object" && exports) {
factory(exports); // CommonJS
} else if (typeof define === "function" && define.amd) {
define(['exports'], factory); // AMD
} else {
global.crossDomainHttp = factory(); // <script>
}
}(this, function (exports) {
/*常量*/
_count = 0,
_OVERTIME = {
"errCode": 404,
"errorMsg": "超时"
},
/*Regular Expression*/
_RE_READY_STATE = /loaded|complete|undefined/,
/*节点操作*/
_doc = document,
_head = _doc.head ||
_doc.getElementsByTagName("head")[0] ||
_doc.documentElement,
_body = _doc.body ||
_doc.getElementsByTagName("body")[0] ||
_doc.documentElement,
_createElement = function (element, parent, params) {
var tempnode = _doc.createElement(element),
i;
for(i in params){
if(params.hasOwnProperty(i)){
tempnode.setAttribute(i, params[i]);
}
}
parent.appendChild(tempnode);
return tempnode;
},
/*默认设置*/
_config = {
"method": "GET",
"jsonp": true, // True or False, 默认为 True
"charset": "utf-8",
"timeout": 2500, // 默认10秒超时
"data": {},
"callback": function(){},
"callbackHandler": ""
};
var crossDomainHttp = function (url, config) {
var getMode, cbName, timer,
node, iframe, form,
cfg = {}, i;
$.extend(cfg, _config, config);
cfg.method = cfg.method.toUpperCase();
// debugger;
if (cfg.method === "POST") {
cbName = cfg.data.callback ? cfg.data.callback.split('.')[1] : [cfg.method, _count++].join("_");
iframe = _createElement("iframe", _body, {
"style": "display: none",
"id": ["iframe", _count].join("_"),
"name": ["iframe", _count].join("_")
});
form = _createElement("form", _body, {
"method": "post",
"action": url,
"target": ["iframe", _count].join("_")
});
if(!("_callback" in cfg.data) && !("callback" in cfg.data)){
cfg.data._callback = cbName;
}
for(i in cfg.data){
if(cfg.data.hasOwnProperty(i)){
_createElement("input", form, {
"type": "hidden",
"name": i,
"value": cfg.data[i]
});
}
}
window[cbName] = function(data){
cfg.callback(data);
clearTimeout(timer);
_body.removeChild(iframe);
_body.removeChild(form);
iframe = undefined;
form = undefined;
};
form.submit();
timer = setTimeout(function(){
window[cbName](_OVERTIME);
}, cfg.timeout);
} else if (cfg.method === "GET") {
cbName = [cfg.method, _count++].join("_");
getMode = /callback=\?/.test(url), // 有callback为True,否则为False
node = _doc.createElement("script");
node.id = cbName;
node.async = true;
node.charset = cfg.charset;
node.onload = node.onerror = node.onreadystatechange = function() {
if (_RE_READY_STATE.test(node.readyState)) {
window[cbName](); // #TOTEST
}
};
node.src = getMode ? url.replace("callback=?", "callback=" + cbName) : url;
window[cbName] = function(data){
clearTimeout(timer);
node.onload = node.onerror = node.onreadystatechange = null;
_head.removeChild(node);
node = undefined;
cfg.callback(data);
};
_head.appendChild(node);
timer = setTimeout(function(){
window[cbName](_OVERTIME);
window[cbName] = null;
}, cfg.timeout);
}
};
window.postCallback=function(data){
return data;
};
return crossDomainHttp;
}));
/* |xGv00|0d6fe5e8ecc18db06fbffe35f75c277b */ |
import React, { Component } from 'react';
import Container from './Container';
import CustomDragLayer from './CustomDragLayer';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
@DragDropContext(HTML5Backend)
export default class DragAroundCustomDragLayer extends Component {
constructor(props) {
super(props);
this.handleSnapToGridAfterDropChange = this.handleSnapToGridAfterDropChange.bind(this);
this.handleSnapToGridWhileDraggingChange = this.handleSnapToGridWhileDraggingChange.bind(this);
this.state = {
snapToGridAfterDrop: false,
snapToGridWhileDragging: false
};
}
render() {
const { snapToGridAfterDrop, snapToGridWhileDragging } = this.state;
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/02%20Drag%20Around/Custom%20Drag%20Layer'>Browse the Source</a></b>
</p>
<p>
The browser APIs provide no way to change the drag preview or its behavior once drag has started.
Libraries such as jQuery UI implement the drag and drop from scratch to work around this, but react-dnd
only supports browser drag and drop “backend” for now, so we have to accept its limitations.
</p>
<p>
We can, however, customize behavior a great deal if we feed the browser an empty image as drag preview.
This library provides a <code>DragLayer</code> that you can use to implement a fixed layer on top of your app where you'd draw a custom drag preview component.
</p>
<p>
Note that we can draw a completely different component on our drag layer if we wish so. It's not just a screenshot.
</p>
<p>
With this approach, we miss out on default “return” animation when dropping outside the container.
However, we get great flexibility in customizing drag feedback and zero flicker.
</p>
<Container snapToGrid={snapToGridAfterDrop} />
<CustomDragLayer snapToGrid={snapToGridWhileDragging} />
<p>
<label>
<input type='checkbox'
checked={snapToGridWhileDragging}
onChange={this.handleSnapToGridWhileDraggingChange} />
<small>Snap to grid while dragging</small>
</label>
<br />
<label>
<input type='checkbox'
checked={snapToGridAfterDrop}
onChange={this.handleSnapToGridAfterDropChange} />
<small>Snap to grid after drop</small>
</label>
</p>
</div>
);
}
handleSnapToGridAfterDropChange() {
this.setState({
snapToGridAfterDrop: !this.state.snapToGridAfterDrop
});
}
handleSnapToGridWhileDraggingChange() {
this.setState({
snapToGridWhileDragging: !this.state.snapToGridWhileDragging
});
}
} |
define(function(require){
//automatically generated, do not edit!
//run `node build` instead
return {
'append' : require('./array/append'),
'collect' : require('./array/collect'),
'combine' : require('./array/combine'),
'compact' : require('./array/compact'),
'contains' : require('./array/contains'),
'difference' : require('./array/difference'),
'every' : require('./array/every'),
'filter' : require('./array/filter'),
'find' : require('./array/find'),
'findIndex' : require('./array/findIndex'),
'flatten' : require('./array/flatten'),
'forEach' : require('./array/forEach'),
'indexOf' : require('./array/indexOf'),
'insert' : require('./array/insert'),
'intersection' : require('./array/intersection'),
'invoke' : require('./array/invoke'),
'join' : require('./array/join'),
'lastIndexOf' : require('./array/lastIndexOf'),
'map' : require('./array/map'),
'max' : require('./array/max'),
'min' : require('./array/min'),
'pick' : require('./array/pick'),
'pluck' : require('./array/pluck'),
'range' : require('./array/range'),
'reduce' : require('./array/reduce'),
'reduceRight' : require('./array/reduceRight'),
'reject' : require('./array/reject'),
'remove' : require('./array/remove'),
'removeAll' : require('./array/removeAll'),
'shuffle' : require('./array/shuffle'),
'some' : require('./array/some'),
'sort' : require('./array/sort'),
'split' : require('./array/split'),
'toLookup' : require('./array/toLookup'),
'union' : require('./array/union'),
'unique' : require('./array/unique'),
'xor' : require('./array/xor'),
'zip' : require('./array/zip')
};
});
|
module.exports={A:{A:{"1":"G E A B","8":"H D fB"},B:{"1":"1 C p J L N I"},C:{"1":"0 2 3 5 6 7 8 9 Y Z a b d e f g h i j k l m n o M q r s t u v w x y z BB CB DB","33":"1 dB FB F K H D G E A B C p J L N I O P Q R S T U V W X bB VB"},D:{"1":"0 1 2 3 5 6 7 8 9 A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z BB CB DB GB PB KB IB gB LB MB NB","33":"F K H D G E"},E:{"1":"H D G E A B C QB RB SB TB UB c WB","33":"F K OB HB"},F:{"1":"0 3 B C J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z XB YB ZB aB c EB cB AB","2":"E"},G:{"1":"G JB hB iB jB kB lB mB nB oB pB qB","33":"4 HB eB"},H:{"1":"rB"},I:{"1":"4 F GB vB wB xB","33":"FB sB tB uB"},J:{"1":"A","33":"D"},K:{"1":"A B C M c EB AB"},L:{"1":"IB"},M:{"1":"2"},N:{"1":"A B"},O:{"1":"yB"},P:{"1":"F K zB 0B"},Q:{"1":"1B"},R:{"1":"2B"}},B:5,C:"CSS3 Box-sizing"};
|
/* */
System.register(['aurelia-router', './route-loader', './router-view', './route-href'], function (_export) {
var Router, AppRouter, RouteLoader, TemplatingRouteLoader, RouterView, RouteHref;
function configure(aurelia) {
aurelia.withSingleton(RouteLoader, TemplatingRouteLoader).withSingleton(Router, AppRouter).globalizeResources('./router-view', './route-href');
}
return {
setters: [function (_aureliaRouter) {
Router = _aureliaRouter.Router;
AppRouter = _aureliaRouter.AppRouter;
RouteLoader = _aureliaRouter.RouteLoader;
}, function (_routeLoader) {
TemplatingRouteLoader = _routeLoader.TemplatingRouteLoader;
}, function (_routerView) {
RouterView = _routerView.RouterView;
}, function (_routeHref) {
RouteHref = _routeHref.RouteHref;
}],
execute: function () {
'use strict';
_export('TemplatingRouteLoader', TemplatingRouteLoader);
_export('RouterView', RouterView);
_export('RouteHref', RouteHref);
_export('configure', configure);
}
};
}); |
/* */
System.register(['core-js', 'aurelia-logging', 'aurelia-metadata'], function (_export) {
var core, LogManager, Metadata, _classCallCheck, logger, Plugins;
function loadPlugin(aurelia, loader, info) {
logger.debug('Loading plugin ' + info.moduleId + '.');
aurelia.currentPluginId = info.moduleId;
return loader.loadModule(info.moduleId).then(function (m) {
if ('configure' in m) {
return Promise.resolve(m.configure(aurelia, info.config || {})).then(function () {
aurelia.currentPluginId = null;
logger.debug('Configured plugin ' + info.moduleId + '.');
});
} else {
aurelia.currentPluginId = null;
logger.debug('Loaded plugin ' + info.moduleId + '.');
}
});
}
return {
setters: [function (_coreJs) {
core = _coreJs['default'];
}, function (_aureliaLogging) {
LogManager = _aureliaLogging;
}, function (_aureliaMetadata) {
Metadata = _aureliaMetadata.Metadata;
}],
execute: function () {
'use strict';
_classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } };
logger = LogManager.getLogger('aurelia');
Plugins = (function () {
function Plugins(aurelia) {
_classCallCheck(this, Plugins);
this.aurelia = aurelia;
this.info = [];
this.processed = false;
}
Plugins.prototype.plugin = (function (_plugin) {
function plugin(_x, _x2) {
return _plugin.apply(this, arguments);
}
plugin.toString = function () {
return _plugin.toString();
};
return plugin;
})(function (moduleId, config) {
var plugin = { moduleId: moduleId, config: config || {} };
if (this.processed) {
loadPlugin(this.aurelia, this.aurelia.loader, plugin);
} else {
this.info.push(plugin);
}
return this;
});
Plugins.prototype._process = function _process() {
var _this = this;
var aurelia = this.aurelia,
loader = aurelia.loader,
info = this.info,
current;
if (this.processed) {
return;
}
var next = (function (_next) {
function next() {
return _next.apply(this, arguments);
}
next.toString = function () {
return _next.toString();
};
return next;
})(function () {
if (current = info.shift()) {
return loadPlugin(aurelia, loader, current).then(next);
}
_this.processed = true;
return Promise.resolve();
});
return next();
};
return Plugins;
})();
_export('Plugins', Plugins);
}
};
}); |
'use strict';
var passwordGrant = require('./oauth/password-grant');
var refreshGrant = require('./oauth/refresh-grant');
var idSiteGrant = require('./oauth/id-site-grant');
var stormpathToken = require('./oauth/stormpath-token');
var clientCredentialsGrant = require('./oauth/client-credentials');
var stormpathSocial = require('./oauth/stormpath-social');
module.exports = {
ApiKey: require('./authc/ApiKey'),
loadApiKey: require('./authc/ApiKeyLoader'),
configLoader: require('./configLoader'),
Client: require('./Client'),
Tenant: require('./resource/Tenant'),
OAuthPasswordGrantRequestAuthenticator: passwordGrant.authenticator,
OauthPasswordGrantAuthenticationResult: passwordGrant.authenticationResult,
OAuthRefreshTokenGrantRequestAuthenticator: refreshGrant.authenticator,
OAuthIdSiteTokenGrantAuthenticator: idSiteGrant.authenticator,
OAuthIdSiteTokenGrantAuthenticationResult: idSiteGrant.authenticationResult,
OAuthStormpathTokenAuthenticator: stormpathToken.authenticator,
OAuthStormpathSocialAuthenticator: stormpathSocial.authenticator,
OAuthStormpathTokenAuthenticationResult: stormpathToken.authenticationResult,
OAuthClientCredentialsAuthenticator: clientCredentialsGrant.authenticator,
OAuthClientCredentialsAuthenticationResult: clientCredentialsGrant.authenticationResult,
SamlIdpUrlBuilder: require('./saml/SamlIdpUrlBuilder'),
AssertionAuthenticationResult: require('./authc/AssertionAuthenticationResult'),
StormpathAccessTokenAuthenticator: require('./oauth/stormpath-access-token-authenticator'),
StormpathAssertionAuthenticator: require('./authc/StormpathAssertionAuthenticator'),
JwtAuthenticator: require('./jwt/jwt-authenticator'),
OAuthAuthenticator: require('./oauth/authenticator')
};
|
module.exports = app => {
app.get('/', app.controller.home);
app.get('/clear', app.controller.clear);
};
|
var DocUtils, XmlUtil;
DocUtils = require('./docUtils');
XmlUtil = {};
XmlUtil.getListXmlElements = function(text, start, end) {
var i, innerCurrentTag, innerLastTag, justOpened, lastTag, result, tag, tags, _i, _len;
if (start == null) {
start = 0;
}
if (end == null) {
end = text.length - 1;
}
/*
get the different closing and opening tags between two texts (doesn't take into account tags that are opened then closed (those that are closed then opened are returned)):
returns:[{"tag":"</w:r>","offset":13},{"tag":"</w:p>","offset":265},{"tag":"</w:tc>","offset":271},{"tag":"<w:tc>","offset":828},{"tag":"<w:p>","offset":883},{"tag":"<w:r>","offset":1483}]
*/
tags = DocUtils.preg_match_all("<(\/?[^/> ]+)([^>]*)>", text.substr(start, end));
result = [];
for (i = _i = 0, _len = tags.length; _i < _len; i = ++_i) {
tag = tags[i];
if (tag[1][0] === '/') {
justOpened = false;
if (result.length > 0) {
lastTag = result[result.length - 1];
innerLastTag = lastTag.tag.substr(1, lastTag.tag.length - 2);
innerCurrentTag = tag[1].substr(1);
if (innerLastTag === innerCurrentTag) {
justOpened = true;
}
}
if (justOpened) {
result.pop();
} else {
result.push({
tag: '<' + tag[1] + '>',
offset: tag.offset
});
}
} else if (tag[2][tag[2].length - 1] === '/') {
} else {
result.push({
tag: '<' + tag[1] + '>',
offset: tag.offset
});
}
}
return result;
};
XmlUtil.getListDifferenceXmlElements = function(text, start, end) {
var scope;
if (start == null) {
start = 0;
}
if (end == null) {
end = text.length - 1;
}
scope = this.getListXmlElements(text, start, end);
while (1.) {
if (scope.length <= 1) {
break;
}
if (scope[0].tag.substr(2) === scope[scope.length - 1].tag.substr(1)) {
scope.pop();
scope.shift();
} else {
break;
}
}
return scope;
};
module.exports = XmlUtil;
|
var redis = require('redis');
/*
sub.subscribe('event');
sub.on("message", function (channel, message) {});
sub.unsubscribe();
pub.publish('event','newMessage');
sub/pub.get('key');
sub/pub.set('key', 'value');
*/
module.exports = {
sub: redis.createClient(),
pub: redis.createClient()
};
|
(function () {
'use strict';
angular
.module('umbraco.directives')
.component('umbLogin', {
templateUrl: 'views/components/application/umb-login.html',
controller: UmbLoginController,
controllerAs: 'vm',
bindings: {
isTimedOut: "<",
onLogin: "&"
}
});
function UmbLoginController($scope, $location, currentUserResource, formHelper,
mediaHelper, umbRequestHelper, Upload, localizationService,
userService, externalLoginInfo, externalLoginInfoService,
resetPasswordCodeInfo, authResource, $q) {
const vm = this;
vm.invitedUser = null;
vm.invitedUserPasswordModel = {
password: "",
confirmPassword: "",
buttonState: "",
passwordPolicies: null,
passwordPolicyText: ""
};
vm.loginStates = {
submitButton: "init"
};
vm.avatarFile = {
filesHolder: null,
uploadStatus: null,
uploadProgress: 0,
maxFileSize: Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB",
acceptedFileTypes: mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes),
uploaded: false
};
vm.allowPasswordReset = Umbraco.Sys.ServerVariables.umbracoSettings.canSendRequiredEmail && Umbraco.Sys.ServerVariables.umbracoSettings.allowPasswordReset;
vm.errorMsg = "";
vm.externalLoginFormAction = Umbraco.Sys.ServerVariables.umbracoUrls.externalLoginsUrl;
vm.externalLoginProviders = externalLoginInfoService.getLoginProviders();
vm.externalLoginProviders.forEach(x => {
x.customView = externalLoginInfoService.getLoginProviderView(x);
// if there are errors set for this specific provider than assign them directly to the model
if (externalLoginInfo.errorProvider === x.authType) {
x.errors = externalLoginInfo.errors;
}
});
vm.denyLocalLogin = externalLoginInfoService.hasDenyLocalLogin();
vm.externalLoginInfo = externalLoginInfo;
vm.resetPasswordCodeInfo = resetPasswordCodeInfo;
vm.logoImage = Umbraco.Sys.ServerVariables.umbracoSettings.loginLogoImage;
vm.backgroundImage = Umbraco.Sys.ServerVariables.umbracoSettings.loginBackgroundImage;
vm.usernameIsEmail = Umbraco.Sys.ServerVariables.umbracoSettings.usernameIsEmail;
vm.$onInit = onInit;
vm.togglePassword = togglePassword;
vm.changeAvatar = changeAvatar;
vm.getStarted = getStarted;
vm.inviteSavePassword = inviteSavePassword;
vm.showLogin = showLogin;
vm.showRequestPasswordReset = showRequestPasswordReset;
vm.showSetPassword = showSetPassword;
vm.loginSubmit = loginSubmit;
vm.requestPasswordResetSubmit = requestPasswordResetSubmit;
vm.setPasswordSubmit = setPasswordSubmit;
vm.newPasswordKeyUp = newPasswordKeyUp;
vm.labels = {};
localizationService.localizeMany([
vm.usernameIsEmail ? "general_email" : "general_username",
vm.usernameIsEmail ? "placeholders_email" : "placeholders_usernameHint",
vm.usernameIsEmail ? "placeholders_emptyEmail" : "placeholders_emptyUsername",
"placeholders_emptyPassword"]
).then(function (data) {
vm.labels.usernameLabel = data[0];
vm.labels.usernamePlaceholder = data[1];
vm.labels.usernameError = data[2];
vm.labels.passwordError = data[3];
});
vm.twoFactor = {};
vm.loginSuccess = loginSuccess;
function onInit() {
// Check if it is a new user
const inviteVal = $location.search().invite;
//1 = enter password, 2 = password set, 3 = invalid token
if (inviteVal && (inviteVal === "1" || inviteVal === "2")) {
$q.all([
//get the current invite user
authResource.getCurrentInvitedUser().then(function (data) {
vm.invitedUser = data;
},
function () {
//it failed so we should remove the search
$location.search('invite', null);
}),
//get the membership provider config for password policies
authResource.getPasswordConfig(0).then(function (data) {
vm.invitedUserPasswordModel.passwordPolicies = data;
//localize the text
localizationService.localize("errorHandling_errorInPasswordFormat", [
vm.invitedUserPasswordModel.passwordPolicies.minPasswordLength,
vm.invitedUserPasswordModel.passwordPolicies.minNonAlphaNumericChars
]).then(function (data) {
vm.invitedUserPasswordModel.passwordPolicyText = data;
});
})
]).then(function () {
vm.inviteStep = Number(inviteVal);
});
} else if (inviteVal && inviteVal === "3") {
vm.inviteStep = Number(inviteVal);
}
// set the welcome greeting
setGreeting();
// show the correct panel
if (vm.resetPasswordCodeInfo.resetCodeModel) {
vm.showSetPassword();
}
else if (vm.resetPasswordCodeInfo.errors.length > 0) {
vm.view = "password-reset-code-expired";
}
else {
vm.showLogin();
}
SetTitle();
}
function togglePassword() {
var elem = $("form[name='vm.loginForm'] input[name='password']");
elem.attr("type", (elem.attr("type") === "text" ? "password" : "text"));
elem.focus();
$(".password-text.show, .password-text.hide").toggle();
}
function changeAvatar(files, event) {
if (files && files.length > 0) {
upload(files[0]);
}
}
function getStarted() {
$location.search('invite', null);
if (vm.onLogin) {
vm.onLogin();
}
}
function inviteSavePassword() {
if (formHelper.submitForm({ scope: $scope, formCtrl: vm.inviteUserPasswordForm })) {
vm.invitedUserPasswordModel.buttonState = "busy";
currentUserResource.performSetInvitedUserPassword(vm.invitedUserPasswordModel.password)
.then(function (data) {
//success
formHelper.resetForm({ scope: $scope, formCtrl: vm.inviteUserPasswordForm });
vm.invitedUserPasswordModel.buttonState = "success";
//set the user and set them as logged in
vm.invitedUser = data;
userService.setAuthenticationSuccessful(data);
vm.inviteStep = 2;
}, function (err) {
formHelper.resetForm({ scope: $scope, hasErrors: true, formCtrl: vm.inviteUserPasswordForm });
formHelper.handleError(err);
vm.invitedUserPasswordModel.buttonState = "error";
});
}
}
function showLogin() {
vm.errorMsg = "";
resetInputValidation();
vm.view = "login";
SetTitle();
}
function showRequestPasswordReset() {
vm.errorMsg = "";
resetInputValidation();
vm.view = "request-password-reset";
vm.showEmailResetConfirmation = false;
SetTitle();
}
function showSetPassword() {
vm.errorMsg = "";
resetInputValidation();
vm.view = "set-password";
SetTitle();
}
function loginSuccess() {
vm.loginStates.submitButton = "success";
userService._retryRequestQueue(true);
if (vm.onLogin) {
vm.onLogin();
}
}
function loginSubmit() {
if (formHelper.submitForm({ scope: $scope, formCtrl: vm.loginForm })) {
//if the login and password are not empty we need to automatically
// validate them - this is because if there are validation errors on the server
// then the user has to change both username & password to resubmit which isn't ideal,
// so if they're not empty, we'll just make sure to set them to valid.
if (vm.login && vm.password && vm.login.length > 0 && vm.password.length > 0) {
vm.loginForm.username.$setValidity('auth', true);
vm.loginForm.password.$setValidity('auth', true);
}
if (vm.loginForm.$invalid) {
SetTitle();
return;
}
// make sure that we are returning to the login view.
vm.view = "login";
vm.loginStates.submitButton = "busy";
userService.authenticate(vm.login, vm.password)
.then(function (data) {
loginSuccess();
},
function (reason) {
//is Two Factor required?
if (reason.status === 402) {
vm.errorMsg = "Additional authentication required";
show2FALoginDialog(reason.data.twoFactorView);
} else {
vm.loginStates.submitButton = "error";
vm.errorMsg = reason.errorMsg;
//set the form inputs to invalid
vm.loginForm.username.$setValidity("auth", false);
vm.loginForm.password.$setValidity("auth", false);
}
userService._retryRequestQueue();
});
//setup a watch for both of the model values changing, if they change
// while the form is invalid, then revalidate them so that the form can
// be submitted again.
vm.loginForm.username.$viewChangeListeners.push(function () {
if (vm.loginForm.$invalid) {
vm.loginForm.username.$setValidity('auth', true);
vm.loginForm.password.$setValidity('auth', true);
}
});
vm.loginForm.password.$viewChangeListeners.push(function () {
if (vm.loginForm.$invalid) {
vm.loginForm.username.$setValidity('auth', true);
vm.loginForm.password.$setValidity('auth', true);
}
});
}
}
function requestPasswordResetSubmit(email) {
// TODO: Do validation properly like in the invite password update
if (email && email.length > 0) {
vm.requestPasswordResetForm.email.$setValidity('auth', true);
}
vm.showEmailResetConfirmation = false;
if (vm.requestPasswordResetForm.$invalid) {
vm.errorMsg = 'Email address cannot be empty';
return;
}
vm.errorMsg = "";
authResource.performRequestPasswordReset(email)
.then(function () {
//remove the email entered
vm.email = "";
vm.showEmailResetConfirmation = true;
}, function (reason) {
vm.errorMsg = reason.errorMsg;
vm.requestPasswordResetForm.email.$setValidity("auth", false);
});
vm.requestPasswordResetForm.email.$viewChangeListeners.push(function () {
if (vm.requestPasswordResetForm.email.$invalid) {
vm.requestPasswordResetForm.email.$setValidity('auth', true);
}
});
}
function setPasswordSubmit(password, confirmPassword) {
vm.showSetPasswordConfirmation = false;
if (password && confirmPassword && password.length > 0 && confirmPassword.length > 0) {
vm.setPasswordForm.password.$setValidity('auth', true);
vm.setPasswordForm.confirmPassword.$setValidity('auth', true);
}
if (vm.setPasswordForm.$invalid) {
return;
}
// TODO: All of this logic can/should be shared! We should do validation the nice way instead of all of this manual stuff, see: inviteSavePassword
authResource.performSetPassword(vm.resetPasswordCodeInfo.resetCodeModel.userId, password, confirmPassword, vm.resetPasswordCodeInfo.resetCodeModel.resetCode)
.then(function () {
vm.showSetPasswordConfirmation = true;
vm.resetComplete = true;
//reset the values in the resetPasswordCodeInfo angular so if someone logs out the change password isn't shown again
resetPasswordCodeInfo.resetCodeModel = null;
}, function (reason) {
if (reason.data && reason.data.Message) {
vm.errorMsg = reason.data.Message;
}
else {
vm.errorMsg = reason.errorMsg;
}
vm.setPasswordForm.password.$setValidity("auth", false);
vm.setPasswordForm.confirmPassword.$setValidity("auth", false);
});
vm.setPasswordForm.password.$viewChangeListeners.push(function () {
if (vm.setPasswordForm.password.$invalid) {
vm.setPasswordForm.password.$setValidity('auth', true);
}
});
vm.setPasswordForm.confirmPassword.$viewChangeListeners.push(function () {
if (vm.setPasswordForm.confirmPassword.$invalid) {
vm.setPasswordForm.confirmPassword.$setValidity('auth', true);
}
});
}
function newPasswordKeyUp(event) {
vm.passwordVal = event.target.value;
}
////
function setGreeting() {
const date = new Date();
localizationService.localize("login_greeting" + date.getDay()).then(function (label) {
$scope.greeting = label;
});
}
function upload(file) {
vm.avatarFile.uploadProgress = 0;
Upload.upload({
url: umbRequestHelper.getApiUrl("currentUserApiBaseUrl", "PostSetAvatar"),
fields: {},
file: file
}).progress(function (evt) {
if (vm.avatarFile.uploadStatus !== "done" && vm.avatarFile.uploadStatus !== "error") {
// set uploading status on file
vm.avatarFile.uploadStatus = "uploading";
// calculate progress in percentage
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total, 10);
// set percentage property on file
vm.avatarFile.uploadProgress = progressPercentage;
}
}).success(function (data, status, headers, config) {
vm.avatarFile.uploadProgress = 100;
// set done status on file
vm.avatarFile.uploadStatus = "done";
vm.invitedUser.avatars = data;
vm.avatarFile.uploaded = true;
}).error(function (evt, status, headers, config) {
// set status done
vm.avatarFile.uploadStatus = "error";
// If file not found, server will return a 404 and display this message
if (status === 404) {
vm.avatarFile.serverErrorMessage = "File not found";
}
else if (status == 400) {
//it's a validation error
vm.avatarFile.serverErrorMessage = evt.message;
}
else {
//it's an unhandled error
//if the service returns a detailed error
if (evt.InnerException) {
vm.avatarFile.serverErrorMessage = evt.InnerException.ExceptionMessage;
//Check if its the common "too large file" exception
if (evt.InnerException.StackTrace && evt.InnerException.StackTrace.indexOf("ValidateRequestEntityLength") > 0) {
vm.avatarFile.serverErrorMessage = "File too large to upload";
}
} else if (evt.Message) {
vm.avatarFile.serverErrorMessage = evt.Message;
}
}
});
}
function show2FALoginDialog(viewPath) {
vm.twoFactor.submitCallback = function submitCallback() {
vm.onLogin();
}
vm.twoFactor.view = viewPath;
vm.view = "2fa-login";
SetTitle();
}
function resetInputValidation() {
vm.confirmPassword = "";
vm.password = "";
vm.login = "";
if (vm.loginForm) {
vm.loginForm.username.$setValidity('auth', true);
vm.loginForm.password.$setValidity('auth', true);
}
if (vm.requestPasswordResetForm) {
vm.requestPasswordResetForm.email.$setValidity("auth", true);
}
if (vm.setPasswordForm) {
vm.setPasswordForm.password.$setValidity('auth', true);
vm.setPasswordForm.confirmPassword.$setValidity('auth', true);
}
}
function SetTitle() {
var title = null;
switch (vm.view.toLowerCase()) {
case "login":
title = "Login";
break;
case "password-reset-code-expired":
case "request-password-reset":
title = "Password Reset";
break;
case "set-password":
title = "Change Password";
break;
case "2fa-login":
title = "Two Factor Authentication";
break;
}
$scope.$emit("$changeTitle", title);
}
}
})();
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z" /></React.Fragment>
, 'BatteryCharging30');
|
function f() {
return '\'';
}
function g() {
return "\"";
}
function h() {
return '\\';
}
|
var A = 1;
interface A {}
|
var kunstmaanbundles = kunstmaanbundles || {};
kunstmaanbundles.appLoading = (function($, window, undefined) {
var init,
addLoading, addLoadingForms, removeLoading;
var $body = $('body');
init = function() {
$('.js-add-app-loading').on('click', addLoading);
$('.js-add-app-loading--forms').on('click', addLoadingForms);
};
addLoading = function() {
$body.addClass('app--loading');
};
addLoadingForms = function() {
var valid = $(this).parents('form')[0].checkValidity();
if(valid) {
addLoading();
}
};
removeLoading = function() {
$body.removeClass('app--loading');
};
return {
init: init,
addLoading: addLoading,
removeLoading: removeLoading
};
}(jQuery, window));
|
/**
* Copyright 2015 Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([], f);
})(function(){
(function ($, undefined) {
/* Filter cell operator messages */
if (kendo.ui.FilterCell) {
kendo.ui.FilterCell.prototype.options.operators =
$.extend(true, kendo.ui.FilterCell.prototype.options.operators,{
"date": {
"eq": "рівними",
"gte": "після або рівна",
"gt": "після",
"lte": "до або рівними",
"lt": "до",
"neq": "не рівна"
},
"number": {
"eq": "рівне",
"gte": "більше або рівними",
"gt": "більше",
"lte": "менше або рівними",
"lt": "менше",
"neq": "не рівними"
},
"string": {
"endswith": "закінчуються на",
"eq": "рівні",
"neq": "не рівні",
"startswith": "починаються на",
"contains": "містять",
"doesnotcontain": "Does not contain"
},
"enums": {
"eq": "рівними",
"neq": "не рівними"
}
});
}
/* Filter menu operator messages */
if (kendo.ui.FilterMenu) {
kendo.ui.FilterMenu.prototype.options.operators =
$.extend(true, kendo.ui.FilterMenu.prototype.options.operators,{
"date": {
"eq": "рівними",
"gte": "після або рівна",
"gt": "після",
"lte": "до або рівними",
"lt": "до",
"neq": "не рівна"
},
"number": {
"eq": "рівне",
"gte": "більше або рівними",
"gt": "більше",
"lte": "менше або рівними",
"lt": "менше",
"neq": "не рівними"
},
"string": {
"endswith": "закінчуються на",
"eq": "рівні",
"neq": "не рівні",
"startswith": "починаються на",
"contains": "містять",
"doesnotcontain": "Does not contain"
},
"enums": {
"eq": "рівними",
"neq": "не рівними"
}
});
}
/* ColumnMenu messages */
if (kendo.ui.ColumnMenu) {
kendo.ui.ColumnMenu.prototype.options.messages =
$.extend(true, kendo.ui.ColumnMenu.prototype.options.messages,{
"columns": "Kолони",
"sortAscending": "Сортування за зростанням",
"sortDescending": "Сортування за спаданням",
"settings": "Параметри стовпців",
"done": "Зроблений",
"lock": "Замикати",
"unlock": "Відімкнути"
});
}
/* RecurrenceEditor messages */
if (kendo.ui.RecurrenceEditor) {
kendo.ui.RecurrenceEditor.prototype.options.messages =
$.extend(true, kendo.ui.RecurrenceEditor.prototype.options.messages,{
"daily": {
"interval": "days(s)",
"repeatEvery": "Repeat every:"
},
"end": {
"after": "After",
"occurrence": "occurrence(s)",
"label": "End:",
"never": "Never",
"on": "On",
"mobileLabel": "Ends"
},
"frequencies": {
"daily": "Daily",
"monthly": "Monthly",
"never": "Never",
"weekly": "Weekly",
"yearly": "Yearly"
},
"monthly": {
"day": "Day",
"interval": "month(s)",
"repeatEvery": "Repeat every:",
"repeatOn": "Repeat on:"
},
"offsetPositions": {
"first": "first",
"fourth": "fourth",
"last": "last",
"second": "second",
"third": "third"
},
"weekly": {
"repeatEvery": "Repeat every:",
"repeatOn": "Repeat on:",
"interval": "week(s)"
},
"yearly": {
"of": "of",
"repeatEvery": "Repeat every:",
"repeatOn": "Repeat on:",
"interval": "year(s)"
},
"weekdays": {
"day": "day",
"weekday": "weekday",
"weekend": "weekend day"
}
});
}
/* Grid messages */
if (kendo.ui.Grid) {
kendo.ui.Grid.prototype.options.messages =
$.extend(true, kendo.ui.Grid.prototype.options.messages,{
"commands": {
"create": "Додати",
"destroy": "Видалити",
"canceledit": "Скасувати",
"update": "Оновити",
"edit": "Редагувати",
"excel": "Export to Excel",
"pdf": "Export to PDF",
"select": "Вибрати",
"cancel": "Cancel Changes",
"save": "Save Changes"
},
"editable": {
"confirmation": "Ви впевнені, що бажаєте видалити даний запис?",
"cancelDelete": "Скасувати",
"confirmDelete": "Видалити"
}
});
}
/* Pager messages */
if (kendo.ui.Pager) {
kendo.ui.Pager.prototype.options.messages =
$.extend(true, kendo.ui.Pager.prototype.options.messages,{
"page": "Сторінка",
"display": "Зображено записи {0} - {1} з {2}",
"of": "з {0}",
"empty": "немає записів",
"refresh": "Оновити",
"first": "Повернутися на першу сторінку",
"itemsPerPage": "елементів на сторінці",
"last": "До останньої сторінки",
"next": "Перейдіть на наступну сторінку",
"previous": "Перейти на попередню сторінку",
"morePages": "Більше сторінок"
});
}
/* FilterCell messages */
if (kendo.ui.FilterCell) {
kendo.ui.FilterCell.prototype.options.messages =
$.extend(true, kendo.ui.FilterCell.prototype.options.messages,{
"filter": "фільтрувати",
"clear": "очистити",
"isFalse": "хиба",
"isTrue": "істина",
"operator": "Oператор"
});
}
/* FilterMenu messages */
if (kendo.ui.FilterMenu) {
kendo.ui.FilterMenu.prototype.options.messages =
$.extend(true, kendo.ui.FilterMenu.prototype.options.messages,{
"filter": "фільтрувати",
"and": "І",
"clear": "очистити",
"info": "Рядки із записами",
"selectValue": "-виберіть-",
"isFalse": "хиба",
"isTrue": "істина",
"or": "Or",
"cancel": "Скасувати",
"operator": "Oператор",
"value": "Значення"
});
}
/* Groupable messages */
if (kendo.ui.Groupable) {
kendo.ui.Groupable.prototype.options.messages =
$.extend(true, kendo.ui.Groupable.prototype.options.messages,{
"empty": "Перетягніть сюди заголовок стовпця, щоб згрупувати записи з цього стовпця"
});
}
/* Editor messages */
if (kendo.ui.Editor) {
kendo.ui.Editor.prototype.options.messages =
$.extend(true, kendo.ui.Editor.prototype.options.messages,{
"bold": "Жирний",
"createLink": "Додати посилання",
"fontName": "Шрифт",
"fontNameInherit": "(inherited font)",
"fontSize": "Розмір шрифта",
"fontSizeInherit": "(inherited size)",
"formatBlock": "Форматування",
"indent": "Збільшити відступ",
"insertHtml": "Додати HTML",
"insertImage": "Додати зображення",
"insertOrderedList": "Нумерований список",
"insertUnorderedList": "Маркований список",
"italic": "Курсив",
"justifyCenter": "По центру",
"justifyFull": "По ширині",
"justifyLeft": "По лівому краю",
"justifyRight": "По правому краю",
"outdent": "Зменшити відступ",
"strikethrough": "Закреслений",
"styles": "Стиль",
"subscript": "Subscript",
"superscript": "Superscript",
"underline": "Підкреслений",
"unlink": "Видалити посилання",
"dialogButtonSeparator": "or",
"dialogCancel": "Cancel",
"dialogInsert": "Insert",
"imageAltText": "Alternate text",
"imageWebAddress": "Web address",
"linkOpenInNewWindow": "Open link in new window",
"linkText": "Text",
"linkToolTip": "ToolTip",
"linkWebAddress": "Web address",
"search": "Search",
"createTable": "Створити таблицю",
"addColumnLeft": "Add column on the left",
"addColumnRight": "Add column on the right",
"addRowAbove": "Add row above",
"addRowBelow": "Add row below",
"deleteColumn": "Delete column",
"deleteRow": "Delete row",
"backColor": "Background color",
"deleteFile": "Are you sure you want to delete \"{0}\"?",
"deleteRow1": "Delete row",
"dialogButtonSeparator1": "or",
"dialogCancel1": "Cancel",
"dialogInsert1": "Insert",
"directoryNotFound": "A directory with this name was not found.",
"dropFilesHere": "drop files here to upload",
"emptyFolder": "Empty Folder",
"foreColor": "Color",
"invalidFileType": "The selected file \"{0}\" is not valid. Supported file types are {1}.",
"orderBy": "Arrange by:",
"orderByName": "Name",
"orderBySize": "Size",
"overwriteFile": "'A file with name \"{0}\" already exists in the current directory. Do you want to overwrite it?",
"uploadFile": "Upload",
"formatting": "Format",
"viewHtml": "View HTML",
"dialogUpdate": "Update",
"insertFile": "Insert file"
});
}
/* Scheduler messages */
if (kendo.ui.Scheduler) {
kendo.ui.Scheduler.prototype.options.messages =
$.extend(true, kendo.ui.Scheduler.prototype.options.messages,{
"allDay": "all day",
"cancel": "Скасувати",
"editable": {
"confirmation": "Are you sure you want to delete this event?"
},
"date": "Date",
"destroy": "Delete",
"editor": {
"allDayEvent": "All day event",
"description": "Description",
"editorTitle": "Event",
"end": "End",
"endTimezone": "End timezone",
"repeat": "Repeat",
"separateTimezones": "Use separate start and end time zones",
"start": "Start",
"startTimezone": "Start timezone",
"timezone": " ",
"timezoneEditorButton": "Time zone",
"timezoneEditorTitle": "Timezones",
"title": "Title",
"noTimezone": "No timezone"
},
"event": "Event",
"recurrenceMessages": {
"deleteRecurring": "Do you want to delete only this event occurrence or the whole series?",
"deleteWindowOccurrence": "Delete current occurrence",
"deleteWindowSeries": "Delete the series",
"deleteWindowTitle": "Delete Recurring Item",
"editRecurring": "Do you want to edit only this event occurrence or the whole series?",
"editWindowOccurrence": "Edit current occurrence",
"editWindowSeries": "Edit the series",
"editWindowTitle": "Edit Recurring Item"
},
"save": "Save",
"time": "Time",
"today": "Today",
"views": {
"agenda": "Agenda",
"day": "Day",
"month": "Month",
"week": "Week",
"workWeek": "Work Week"
},
"deleteWindowTitle": "Delete event",
"showFullDay": "Show full day",
"showWorkDay": "Show business hours"
});
}
/* Upload messages */
if (kendo.ui.Upload) {
kendo.ui.Upload.prototype.options.localization =
$.extend(true, kendo.ui.Upload.prototype.options.localization,{
"cancel": "Cancel",
"dropFilesHere": "drop files here to upload",
"headerStatusUploaded": "Done",
"headerStatusUploading": "Uploading...",
"remove": "Remove",
"retry": "Retry",
"select": "Select...",
"statusFailed": "failed",
"statusUploaded": "uploaded",
"statusUploading": "uploading",
"uploadSelectedFiles": "Upload files"
});
}
})(window.kendo.jQuery);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
const SET_THEMES_FILTER = 'SET_THEMES_FILTER'
const reducers = {
themes: ThemesReducer
}
const actions = {
[ SET_THEMES_FILTER ]: (payload) => {
return { type: SET_THEMES_FILTER, payload }
}
}
const initialState = {
filters: { }
}
function ThemesReducer (state = initialState, {type, payload}) {
switch(type) {
case SET_THEMES_FILTER:
return assign(state, {
filter: payload.filter
})
default:
return state
}
}
export default {
reducers,
actions,
initialState,
get constants() {
return Object.keys(actions)
}
}
|
var fs = require('fs');
var p = require('path');
var path = p.join(__dirname,'../','/cap_img');
var dir = function(){
fs.chmodSync(path, '777');//修改访问文件夹权限
var fileArray = fs.readdirSync(path);//获取所有文件名
fileArray.forEach(function(v,i){ //清空文件夹
fs.unlinkSync(p.join(path,v));
})
}
module.exports = dir; |
define({main:{"lv-LV":{identity:{version:{_number:"$Revision: 11914 $",_cldrVersion:"29"},language:"lv",territory:"LV"},dates:{calendars:{gregorian:{months:{format:{abbreviated:{1:"janv.",2:"febr.",3:"marts",4:"apr.",5:"maijs",6:"jūn.",7:"jūl.",8:"aug.",9:"sept.",10:"okt.",11:"nov.",12:"dec."},narrow:{1:"J",2:"F",3:"M",4:"A",5:"M",6:"J",7:"J",8:"A",9:"S",10:"O",11:"N",12:"D"},wide:{1:"janvāris",2:"februāris",3:"marts",4:"aprīlis",5:"maijs",6:"jūnijs",7:"jūlijs",8:"augusts",9:"septembris",10:"oktobris",
11:"novembris",12:"decembris"}},"stand-alone":{abbreviated:{1:"Janv.",2:"Febr.",3:"Marts",4:"Apr.",5:"Maijs",6:"Jūn.",7:"Jūl.",8:"Aug.",9:"Sept.",10:"Okt.",11:"Nov.",12:"Dec."},narrow:{1:"J",2:"F",3:"M",4:"A",5:"M",6:"J",7:"J",8:"A",9:"S",10:"O",11:"N",12:"D"},wide:{1:"Janvāris",2:"Februāris",3:"Marts",4:"Aprīlis",5:"Maijs",6:"Jūnijs",7:"Jūlijs",8:"Augusts",9:"Septembris",10:"Oktobris",11:"Novembris",12:"Decembris"}}},days:{format:{abbreviated:{sun:"Sv",mon:"Pr",tue:"Ot",wed:"Tr",thu:"Ce",fri:"Pk",
sat:"Se"},narrow:{sun:"S",mon:"P",tue:"O",wed:"T",thu:"C",fri:"P",sat:"S"},wide:{sun:"svētdiena",mon:"pirmdiena",tue:"otrdiena",wed:"trešdiena",thu:"ceturtdiena",fri:"piektdiena",sat:"sestdiena"}},"stand-alone":{abbreviated:{sun:"Sv",mon:"Pr",tue:"Ot",wed:"Tr",thu:"Ce",fri:"Pk",sat:"Se"},narrow:{sun:"S",mon:"P",tue:"O",wed:"T",thu:"C",fri:"P",sat:"S"},wide:{sun:"Svētdiena",mon:"Pirmdiena",tue:"Otrdiena",wed:"Trešdiena",thu:"Ceturtdiena",fri:"Piektdiena",sat:"Sestdiena"}}},dayPeriods:{format:{wide:{am:"priekšpusdienā",
pm:"pēcpusdienā"}}},eras:{eraAbbr:{0:"p.m.ē.",1:"m.ē."}},dateFormats:{full:"EEEE, y. 'gada' d. MMMM","long":"y. 'gada' d. MMMM",medium:"y. 'gada' d. MMM","short":"dd.MM.yy"},timeFormats:{full:"HH:mm:ss zzzz","long":"HH:mm:ss z",medium:"HH:mm:ss","short":"HH:mm"},dateTimeFormats:{full:"{1} {0}","long":"{1} {0}",medium:"{1} {0}","short":"{1} {0}",availableFormats:{d:"d",E:"ccc",Ed:"E, d.",Ehm:"E, h:mm a",EHm:"E, HH:mm",Ehms:"E, h:mm:ss a",EHms:"E, HH:mm:ss",Gy:"G y. 'g'.",GyMMM:"G y. 'g'. MMM",GyMMMd:"G y. 'g'. d. MMM",
GyMMMEd:"E, G y. 'g'. d. MMM",h:"h a",H:"HH",hm:"h:mm a",Hm:"HH:mm",hms:"h:mm:ss a",Hms:"HH:mm:ss",hmsv:"h:mm:ss a v",Hmsv:"HH:mm:ss v",hmv:"h:mm a v",Hmv:"HH:mm v",M:"L",Md:"dd.MM.",MEd:"E, dd.MM.",MMM:"LLL",MMMd:"d. MMM",MMMEd:"E, d. MMM",MMMMd:"d. MMMM",MMMMEd:"E, d. MMMM",mmss:"mm:ss",ms:"mm:ss",y:"y. 'g'.",yM:"MM.y.",yMd:"d.M.y.",yMEd:"E, d.M.y.",yMMM:"y. 'g'. MMM",yMMMd:"y. 'g'. d. MMM",yMMMEd:"E, y. 'g'. d. MMM",yMMMM:"y. 'g'. MMMM",yQQQ:"y. 'g'. QQQ",yQQQQ:"y. 'g'. QQQQ"},appendItems:{Timezone:"{0} {1}"}}}},
fields:{year:{"relative-type--1":"pagājušajā gadā","relative-type-0":"šajā gadā","relative-type-1":"nākamajā gadā","relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} gadiem","relativeTimePattern-count-one":"pēc {0} gada","relativeTimePattern-count-other":"pēc {0} gadiem"},"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} gadiem","relativeTimePattern-count-one":"pirms {0} gada","relativeTimePattern-count-other":"pirms {0} gadiem"}},month:{"relative-type--1":"pagājušajā mēnesī",
"relative-type-0":"šajā mēnesī","relative-type-1":"nākamajā mēnesī","relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} mēnešiem","relativeTimePattern-count-one":"pēc {0} mēneša","relativeTimePattern-count-other":"pēc {0} mēnešiem"},"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} mēnešiem","relativeTimePattern-count-one":"pirms {0} mēneša","relativeTimePattern-count-other":"pirms {0} mēnešiem"}},week:{"relative-type--1":"pagājušajā nedēļā","relative-type-0":"šajā nedēļā",
"relative-type-1":"nākamajā nedēļā","relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} nedēļām","relativeTimePattern-count-one":"pēc {0} nedēļas","relativeTimePattern-count-other":"pēc {0} nedēļām"},"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} nedēļām","relativeTimePattern-count-one":"pirms {0} nedēļas","relativeTimePattern-count-other":"pirms {0} nedēļām"}},day:{"relative-type--1":"vakar","relative-type-0":"šodien","relative-type-1":"rīt","relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} dienām",
"relativeTimePattern-count-one":"pēc {0} dienas","relativeTimePattern-count-other":"pēc {0} dienām"},"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} dienām","relativeTimePattern-count-one":"pirms {0} dienas","relativeTimePattern-count-other":"pirms {0} dienām"}},sun:{"relative-type--1":"pagājušajā svētdienā"},mon:{"relative-type--1":"pagājušajā pirmdienā"},tue:{"relative-type--1":"pagājušajā otrdienā"},wed:{"relative-type--1":"pagājušajā trešdienā"},thu:{"relative-type--1":"pagājušajā ceturtdienā"},
fri:{"relative-type--1":"pagājušajā piektdienā"},sat:{"relative-type--1":"pagājušajā sestdienā"},hour:{"relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} stundām","relativeTimePattern-count-one":"pēc {0} stundas","relativeTimePattern-count-other":"pēc {0} stundām"},"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} stundām","relativeTimePattern-count-one":"pirms {0} stundas","relativeTimePattern-count-other":"pirms {0} stundām"}},minute:{"relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} minūtēm",
"relativeTimePattern-count-one":"pēc {0} minūtes","relativeTimePattern-count-other":"pēc {0} minūtēm"},"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} minūtēm","relativeTimePattern-count-one":"pirms {0} minūtes","relativeTimePattern-count-other":"pirms {0} minūtēm"}},second:{"relative-type-0":"tagad","relativeTime-type-future":{"relativeTimePattern-count-zero":"pēc {0} sekundēm","relativeTimePattern-count-one":"pēc {0} sekundes","relativeTimePattern-count-other":"pēc {0} sekundēm"},
"relativeTime-type-past":{"relativeTimePattern-count-zero":"pirms {0} sekundēm","relativeTimePattern-count-one":"pirms {0} sekundes","relativeTimePattern-count-other":"pirms {0} sekundēm"}}}},numbers:{defaultNumberingSystem:"latn",otherNumberingSystems:{"native":"latn"},"symbols-numberSystem-latn":{decimal:",",group:" ",percentSign:"%",plusSign:"+",minusSign:"-",exponential:"E",perMille:"‰",infinity:"∞",nan:"nav skaitlis"},"decimalFormats-numberSystem-latn":{standard:"#,##0.###","long":{decimalFormat:{"1000-count-zero":"0 tūkstoši",
"1000-count-one":"0 tūkstotis","1000-count-other":"0 tūkstoši","10000-count-zero":"00 tūkstoši","10000-count-one":"00 tūkstotis","10000-count-other":"00 tūkstoši","100000-count-zero":"000 tūkstoši","100000-count-one":"000 tūkstotis","100000-count-other":"000 tūkstoši","1000000-count-zero":"0 miljoni","1000000-count-one":"0 miljons","1000000-count-other":"0 miljoni","10000000-count-zero":"00 miljoni","10000000-count-one":"00 miljons","10000000-count-other":"00 miljoni","100000000-count-zero":"000 miljoni",
"100000000-count-one":"000 miljons","100000000-count-other":"000 miljoni","1000000000-count-zero":"0 miljardi","1000000000-count-one":"0 miljards","1000000000-count-other":"0 miljardi","10000000000-count-zero":"00 miljardi","10000000000-count-one":"00 miljards","10000000000-count-other":"00 miljardi","100000000000-count-zero":"000 miljardi","100000000000-count-one":"000 miljards","100000000000-count-other":"000 miljardi","1000000000000-count-zero":"0 triljoni","1000000000000-count-one":"0 triljons",
"1000000000000-count-other":"0 triljoni","10000000000000-count-zero":"00 triljoni","10000000000000-count-one":"00 triljons","10000000000000-count-other":"00 triljoni","100000000000000-count-zero":"000 triljoni","100000000000000-count-one":"000 triljons","100000000000000-count-other":"000 triljoni"}},"short":{decimalFormat:{"1000-count-zero":"0 tūkst'.'","1000-count-one":"0 tūkst'.'","1000-count-other":"0 tūkst'.'","10000-count-zero":"00 tūkst'.'","10000-count-one":"00 tūkst'.'","10000-count-other":"00 tūkst'.'",
"100000-count-zero":"000 tūkst'.'","100000-count-one":"000 tūkst'.'","100000-count-other":"000 tūkst'.'","1000000-count-zero":"0 milj'.'","1000000-count-one":"0 milj'.'","1000000-count-other":"0 milj'.'","10000000-count-zero":"00 milj'.'","10000000-count-one":"00 milj'.'","10000000-count-other":"00 milj'.'","100000000-count-zero":"000 milj'.'","100000000-count-one":"000 milj'.'","100000000-count-other":"000 milj'.'","1000000000-count-zero":"0 mljrd'.'","1000000000-count-one":"0 mljrd'.'","1000000000-count-other":"0 mljrd'.'",
"10000000000-count-zero":"00 mljrd'.'","10000000000-count-one":"00 mljrd'.'","10000000000-count-other":"00 mljrd'.'","100000000000-count-zero":"000 mljrd'.'","100000000000-count-one":"000 mljrd'.'","100000000000-count-other":"000 mljrd'.'","1000000000000-count-zero":"0 trilj'.'","1000000000000-count-one":"0 trilj'.'","1000000000000-count-other":"0 trilj'.'","10000000000000-count-zero":"00 trilj'.'","10000000000000-count-one":"00 trilj'.'","10000000000000-count-other":"00 trilj'.'","100000000000000-count-zero":"000 trilj'.'",
"100000000000000-count-one":"000 trilj'.'","100000000000000-count-other":"000 trilj'.'"}}},"percentFormats-numberSystem-latn":{standard:"#,##0%"},"currencyFormats-numberSystem-latn":{standard:"#0.00 ¤","unitPattern-count-zero":"{0} {1}","unitPattern-count-one":"{0} {1}","unitPattern-count-other":"{0} {1}"},currencies:{AUD:{displayName:"Austrālijas dolārs",symbol:"AU$"},BRL:{displayName:"Brazīlijas reāls",symbol:"R$"},CAD:{displayName:"Kanādas dolārs",symbol:"CA$"},CHF:{displayName:"Šveices franks",
symbol:"CHF"},CNY:{displayName:"Ķīnas juaņs",symbol:"CN¥"},CZK:{displayName:"Čehijas krona",symbol:"CZK"},DKK:{displayName:"Dānijas krona",symbol:"DKK"},EUR:{displayName:"eiro",symbol:"€"},GBP:{displayName:"Lielbritānijas mārciņa",symbol:"£"},HKD:{displayName:"Honkongas dolārs",symbol:"HK$"},HUF:{displayName:"Ungārijas forints",symbol:"HUF"},IDR:{displayName:"Indonēzijas rūpija",symbol:"IDR"},INR:{displayName:"Indijas rūpija",symbol:"₹"},JPY:{displayName:"Japānas jena",symbol:"¥"},KRW:{displayName:"Dienvidkorejas vona",
symbol:"₩"},MXN:{displayName:"Meksikas peso",symbol:"MX$"},NOK:{displayName:"Norvēģijas krona",symbol:"NOK"},PLN:{displayName:"Polijas zlots",symbol:"PLN"},RUB:{displayName:"Krievijas rublis",symbol:"RUB"},SAR:{displayName:"Saūda riāls",symbol:"SAR"},SEK:{displayName:"Zviedrijas krona",symbol:"SEK"},THB:{displayName:"Taizemes bāts",symbol:"฿"},TRY:{displayName:"Turcijas lira",symbol:"TRY"},TWD:{displayName:"Taivānas jaunais dolārs",symbol:"NT$"},USD:{displayName:"ASV dolārs",symbol:"$"},ZAR:{displayName:"Dienvidāfrikas rends",
symbol:"ZAR"}}}}}}); |
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/* jshint node:true, bitwise:true, undef:true, trailing:true, quotmark:true,
indent:4, unused:vars, latedef:nofunc
*/
var path = require('path'),
cordova_util = require('./util'),
hooker = require('./hooker'),
superspawn = require('./superspawn');
// Returns a promise.
module.exports = function compile(options) {
var projectRoot = cordova_util.cdProjectRoot();
options = cordova_util.preProcessOptions(options);
var hooks = new hooker(projectRoot);
var ret = hooks.fire('before_compile', options);
options.platforms.forEach(function(platform) {
ret = ret.then(function() {
var cmd = path.join(projectRoot, 'platforms', platform, 'cordova', 'build');
return superspawn.spawn(cmd, options.options, { stdio: 'inherit', printCommand: true });
});
});
ret = ret.then(function() {
return hooks.fire('after_compile', options);
});
return ret;
};
|
export const value = 21; |
import throttle from './lib/throttle.js';
const fn = throttle( () => {
console.log( '.' );
}, 500 );
window.addEventListener( 'mousemove', throttle );
|
"use strict";
var Observable_1 = require('rxjs/Observable');
var select_1 = require('../../operator/select');
Observable_1.Observable.prototype.select = select_1.select;
|
module.exports = {
"@id": "/documents/df9dd0ec-c1cf-4391-a745-a933ab1af7a7/",
"@type": ["Document", "Item"],
"aliases": [
"ENCODE:Myers_Lab_ChIP-seq_Protocol_v042211"
],
"attachment": {
"download": "Myers_Lab_ChIP-seq_Protocol_v042211.pdf",
"href": "@@download/attachment/Myers_Lab_ChIP-seq_Protocol_v042211.pdf",
"type": "application/pdf"
},
"award": require('../award'),
"document_type": "general protocol",
"lab": require('../lab'),
"submitted_by": require('../submitter'),
"uuid": "df9dd0ec-c1cf-4391-a745-a933ab1af7a7"
}; |
var title = "Peter out Peat";
var desc = "Grab your <a href=\"event:item|shovel\">Shovel<\/a> and wrangle some friends to help you harvest a full <b>Peat Bog<\/b> until it's empty. In less than 9 seconds.";
var offer = "Greetings, my round-headed friend. I have a job for you. Use your <a href=\"event:item|shovel\">Shovel<\/a> to harvest a full <b>Peat Bog<\/b> until it's empty. In 9 seconds. <split butt_txt=\"Eep.\" \/> Did I mention you can invite some friends to help you? Better now?";
var completion = "Congratulations. You and your confreres harvested this entire bog in less than 9 seconds. <split butt_txt=\"I say Boo. And also Ya.\" \/> Unfortunately, I've only got enough on me to reward just you. <split butt_txt=\"Oh.\" \/> Might I recommend a round of heartfelt high-fives?";
var auto_complete = 0;
var familiar_turnin = 1;
var is_tracked = 0;
var show_alert = 0;
var silent_complete = 0;
var progress = [
];
var giver_progress = [
];
var no_progress = "null";
var prereq_quests = [];
var prerequisites = [];
var end_npcs = [];
var locations = {};
var requirements = {
"r239" : {
"type" : "flag",
"name" : "peat_bog_fully_harvested",
"class_id" : "shovel",
"desc" : "Fully harvest a Peat Bog"
}
};
function onComplete(pc){ // generated from rewards
var xp=0;
var currants=0;
var mood=0;
var energy=0;
var favor=0;
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_quest_modifier();
xp = pc.stats_add_xp(round_to_5(375 * multiplier), true, {type: 'quest_complete', quest: this.class_tsid});
currants = pc.stats_add_currants(round_to_5(325 * multiplier), {type: 'quest_complete', quest: this.class_tsid});
energy = pc.metabolics_add_energy(round_to_5(50 * multiplier));
favor = pc.stats_add_favor_points("grendaline", round_to_5(40 * multiplier));
apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor));
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
this.onComplete_custom(pc);
}
var rewards = {
"xp" : 375,
"currants" : 325,
"energy" : 50,
"favor" : {
"0" : {
"giant" : "grendaline",
"points" : 40
}
}
};
function onComplete_custom(pc){
pc.buffs_remove('bogspecialization_harvest_full_peat_bog_in_time_period');
}
function onStarted(pc){
// To start the quest (by pressing TRY NOW button in quest log), you have to be at least 100 pixels near a peat bog that is 100% full.
function is_bog(stack){ return stack.is_peat_bog && stack.getInstanceProp('harvests_remaining') == 4; }
var bog = pc.findCloseStack(is_bog, 100);
if (!bog){
return {
ok: 0,
error: 'You need to be near a full Peat Bog.'
};
}
this.peat_bog = bog.tsid;
bog.sendBubble('Empty me out! Go!', 5000);
pc.buffs_apply('bogspecialization_harvest_full_peat_bog_in_time_period');
return {
ok: 1
};
}
function testBog(){
if (!this.peat_bog) return;
var bog = apiFindObject(this.peat_bog);
if (!bog.isUseable()){
this.owner.quests_set_flag('peat_bog_fully_harvested');
}
}
// generated ok (NO DATE)
|
goog.provide("trapeze.AffineTransform");
trapeze.AffineTransform = function(m00, m10, m01, m11, m02, m12) {
if(arguments.length == 0) {
m00 = 1; // Scale X = m00
m10 = 0; // Shear Y = m10
m01 = 0; // Shear X = m01
m11 = 1; // Scale Y = m11
m02 = 0; // Translation X = m02
m12 = 0; // Translation Y = m12
}
this.m00 = m00; // Scale X = m00
this.m10 = m10; // Shear Y = m10
this.m01 = m01; // Shear X = m01
this.m11 = m11; // Scale Y = m11
this.m02 = m02; // Translation X = m02
this.m12 = m12; // Translation Y = m12
};
trapeze.AffineTransform.prototype = {
/**
* This will take the current AffineTransform and multipy it with a AffineTransform that is passed in.
*
* @param b The AffineTransform to multiply by.
*
* @return The result of the two multiplied matrices.
*/
multiply: function(b) {
var result = new trapeze.AffineTransform();
if (b != null)
{
result.m00 = this.m00 * b.m00 + this.m01 * b.m10;
result.m01 = this.m00 * b.m01 + this.m01 * b.m11;
result.m02 = this.m00 * b.m02 + this.m01 * b.m12 + this.m02;
result.m10 = this.m10 * b.m00 + this.m11 * b.m10;
result.m11 = this.m10 * b.m01 + this.m11 * b.m11;
result.m12 = this.m10 * b.m02 + this.m11 * b.m12 + this.m12;
}
else { console.error('no AffineTransform'); }
return result;
},
/**
* This will return a string representation of the trapeze.AffineTransform.
*
* @return The AffineTransform as a string.
*/
toString: function() {
var result = "";
result += "[[";
result += this.m00 + ", ";
result += this.m01 + ", ";
result += this.m02 + "][";
result += this.m10 + ", ";
result += this.m11 + ", " ;
result += this.m12 + "]]";
return result;
},
getDeterminant: function() {
return this.m00 * this.m11 - this.m01 * this.m10;
},
/*
this.createInverse = function() {
new funkytown();
var result = new trapeze.AffineTransform();
var mult = 1 / this.getDeterminant();
var resultAffineTransform = result.single;
resultAffineTransform[0] = mult*(single[4]*1-0);
resultAffineTransform[1] = mult*(0-single[1]*1);
resultAffineTransform[2] = mult*(single[1]*single[5]-single[2]*single[4]);
resultAffineTransform[3] = mult*(0-single[3]*single[8]);
resultAffineTransform[4] = mult*(single[0]*1-0);
resultAffineTransform[5] = mult*(single[2]*single[3]-single[0]*single[5]);
resultAffineTransform[6] = mult*(0-0);
resultAffineTransform[7] = mult*(0-0);
resultAffineTransform[8] = mult*(single[0]*single[4]-single[1]*single[3]);
return result;
};*/
getScaleX: function() {
return this.m00;
},
getScaleY: function() {
return this.m11;
},
clone: function() {
return new trapeze.AffineTransform(this.m00, this.m10, this.m01, this.m11, this.m02, this.m12);
},
scale: function(x, y) {
var scalor = trapeze.AffineTransform.getScaleInstance(x, y);
return this.multiply(scalor);
},
translate: function(x, y) {
var scalor = trapeze.AffineTransform.getTranslatingInstance(x, y);
return this.multiply(scalor);
},
transform: function(pt) {
return {x: pt.x * this.m00 + pt.y * this.m01 + this.m02,
y: pt.x * this.m10 + pt.y * this.m11 + this.m12};
}
};
trapeze.AffineTransform.getScaleInstance = function(x, y) {
var affineTransform = new trapeze.AffineTransform();
affineTransform.m00 = x;
affineTransform.m11 = y;
return affineTransform;
};
trapeze.AffineTransform.getTranslatingInstance = function(x, y) {
var affineTransform = new trapeze.AffineTransform();
affineTransform.m02 = x;
affineTransform.m12 = y;
return affineTransform;
}; |
// @flow
import React from 'react'
import { shallow } from 'enzyme'
import { resetStyled, expectCSSMatches } from './utils'
let styled
describe('css features', () => {
beforeEach(() => {
styled = resetStyled()
})
it('should add vendor prefixes in the right order', () => {
const Comp = styled.div`
transition: opacity 0.3s;
`
shallow(<Comp />)
expectCSSMatches('.sc-a {} .b { -webkit-transition: opacity 0.3s; transition: opacity 0.3s; }')
})
it('should add vendor prefixes for display', () => {
const Comp = styled.div`
display: flex;
flex-direction: column;
align-items: center;
`
shallow(<Comp />)
expectCSSMatches(`
.sc-a {}
.b {
display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-flex-direction: column; -ms-flex-direction: column; flex-direction: column; -webkit-align-items: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center;
}
`)
})
it('should pass through custom properties', () => {
const Comp = styled.div`
--custom-prop: some-val;
`
shallow(<Comp />)
expectCSSMatches('.sc-a {} .b { --custom-prop: some-val; }')
})
})
|
/*! Select2 4.0.6 | https://github.com/select2/select2/blob/master/LICENSE.md */
(function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;return e.define("select2/i18n/bg",[],function(){return{inputTooLong:function(e){var t=e.input.length-e.maximum,n="Моля въведете с "+t+" по-малко символ";return t>1&&(n+="a"),n},inputTooShort:function(e){var t=e.minimum-e.input.length,n="Моля въведете още "+t+" символ";return t>1&&(n+="a"),n},loadingMore:function(){return"Зареждат се още…"},maximumSelected:function(e){var t="Можете да направите до "+e.maximum+" ";return e.maximum>1?t+="избора":t+="избор",t},noResults:function(){return"Няма намерени съвпадения"},searching:function(){return"Търсене…"},removeAllItems:function(){return"Премахнете всички елементи"}}}),{define:e.define,require:e.require}})(); |
$.fn.dataTable.ext.order["dom-checkbox"]=function(e,n){return this.api().column(n,{order:"index"}).nodes().map(function(e,n){return $("input",e).prop("checked")?"1":"0"})}; |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.2.8_A2_T8;
* @section: 15.10.2.8;
* @assertion: The form (?! Disjunction ) specifies a zero-width negative lookahead.
* In order for it to succeed, the pattern inside Disjunction must fail to match at the current position.
* The current position is not advanced before matching the sequel;
* @description: Execute /(\.(?!com|org)|\/)/.test("ah.com") and check results;
*/
__executed = /(\.(?!com|org)|\/)/.test("ah.com");
//CHECK#1
if (__executed) {
$ERROR('#1: /(\\.(?!com|org)|\\/)/.test("ah.com") === false');
}
|
// Ajax Preloader
var Preloader;
if (Preloader == undefined) {
Preloader = function(dom_id) {
this.show(dom_id);
};
}
Preloader.select = function(dom_id) {
var element_id = (dom_id == null) ? 'preloader' : dom_id;
if (this.element == null)
{
this.element = document.getElementById(element_id);
}
};
Preloader.show = function(dom_id) {
this.select(dom_id);
if (this.element == null) return;
this.draw();
};
Preloader.draw = function(){
if (this.element == null) return;
var client = window.innerHeight || document.documentElement.clientHeight;
var top = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
var prefix = top + (client / 2);
this.element.style.top = prefix + 'px';
this.element.style.display = '';
};
Preloader.hide = function(dom_id){
this.select(dom_id);
if (this.element == null) return;
this.element.style.display = 'none';
this.element.style.top = '0px';
};
Preloader.is_enable = function(){
return (document.getElementById('preloader') != null);
};
|
/**
* @author Virtulous / https://virtulo.us/
*/
import {
Bone,
BufferAttribute,
BufferGeometry,
Color,
DefaultLoadingManager,
FileLoader,
LoaderUtils,
Matrix4,
Mesh,
MeshLambertMaterial,
MeshPhongMaterial,
Object3D,
Quaternion,
Skeleton,
SkinnedMesh,
TextureLoader,
Vector3
} from "../../../build/three.module.js";
var AssimpLoader = function ( manager ) {
this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
};
AssimpLoader.prototype = {
constructor: AssimpLoader,
crossOrigin: 'anonymous',
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var path = ( scope.path === undefined ) ? LoaderUtils.extractUrlBase( url ) : scope.path;
var loader = new FileLoader( this.manager );
loader.setPath( scope.path );
loader.setResponseType( 'arraybuffer' );
loader.load( url, function ( buffer ) {
onLoad( scope.parse( buffer, path ) );
}, onProgress, onError );
},
setPath: function ( value ) {
this.path = value;
return this;
},
setResourcePath: function ( value ) {
this.resourcePath = value;
return this;
},
setCrossOrigin: function ( value ) {
this.crossOrigin = value;
return this;
},
parse: function ( buffer, path ) {
var textureLoader = new TextureLoader( this.manager );
textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
var Virtulous = {};
Virtulous.KeyFrame = function ( time, matrix ) {
this.time = time;
this.matrix = matrix.clone();
this.position = new Vector3();
this.quaternion = new Quaternion();
this.scale = new Vector3( 1, 1, 1 );
this.matrix.decompose( this.position, this.quaternion, this.scale );
this.clone = function () {
var n = new Virtulous.KeyFrame( this.time, this.matrix );
return n;
};
this.lerp = function ( nextKey, time ) {
time -= this.time;
var dist = ( nextKey.time - this.time );
var l = time / dist;
var l2 = 1 - l;
var keypos = this.position;
var keyrot = this.quaternion;
// var keyscl = key.parentspaceScl || key.scl;
var key2pos = nextKey.position;
var key2rot = nextKey.quaternion;
// var key2scl = key2.parentspaceScl || key2.scl;
Virtulous.KeyFrame.tempAniPos.x = keypos.x * l2 + key2pos.x * l;
Virtulous.KeyFrame.tempAniPos.y = keypos.y * l2 + key2pos.y * l;
Virtulous.KeyFrame.tempAniPos.z = keypos.z * l2 + key2pos.z * l;
// tempAniScale.x = keyscl[0] * l2 + key2scl[0] * l;
// tempAniScale.y = keyscl[1] * l2 + key2scl[1] * l;
// tempAniScale.z = keyscl[2] * l2 + key2scl[2] * l;
Virtulous.KeyFrame.tempAniQuat.set( keyrot.x, keyrot.y, keyrot.z, keyrot.w );
Virtulous.KeyFrame.tempAniQuat.slerp( key2rot, l );
return Virtulous.KeyFrame.tempAniMatrix.compose( Virtulous.KeyFrame.tempAniPos, Virtulous.KeyFrame.tempAniQuat, Virtulous.KeyFrame.tempAniScale );
};
};
Virtulous.KeyFrame.tempAniPos = new Vector3();
Virtulous.KeyFrame.tempAniQuat = new Quaternion();
Virtulous.KeyFrame.tempAniScale = new Vector3( 1, 1, 1 );
Virtulous.KeyFrame.tempAniMatrix = new Matrix4();
Virtulous.KeyFrameTrack = function () {
this.keys = [];
this.target = null;
this.time = 0;
this.length = 0;
this._accelTable = {};
this.fps = 20;
this.addKey = function ( key ) {
this.keys.push( key );
};
this.init = function () {
this.sortKeys();
if ( this.keys.length > 0 )
this.length = this.keys[ this.keys.length - 1 ].time;
else
this.length = 0;
if ( ! this.fps ) return;
for ( var j = 0; j < this.length * this.fps; j ++ ) {
for ( var i = 0; i < this.keys.length; i ++ ) {
if ( this.keys[ i ].time == j ) {
this._accelTable[ j ] = i;
break;
} else if ( this.keys[ i ].time < j / this.fps && this.keys[ i + 1 ] && this.keys[ i + 1 ].time >= j / this.fps ) {
this._accelTable[ j ] = i;
break;
}
}
}
};
this.parseFromThree = function ( data ) {
var fps = data.fps;
this.target = data.node;
var track = data.hierarchy[ 0 ].keys;
for ( var i = 0; i < track.length; i ++ ) {
this.addKey( new Virtulous.KeyFrame( i / fps || track[ i ].time, track[ i ].targets[ 0 ].data ) );
}
this.init();
};
this.parseFromCollada = function ( data ) {
var track = data.keys;
var fps = this.fps;
for ( var i = 0; i < track.length; i ++ ) {
this.addKey( new Virtulous.KeyFrame( i / fps || track[ i ].time, track[ i ].matrix ) );
}
this.init();
};
this.sortKeys = function () {
this.keys.sort( this.keySortFunc );
};
this.keySortFunc = function ( a, b ) {
return a.time - b.time;
};
this.clone = function () {
var t = new Virtulous.KeyFrameTrack();
t.target = this.target;
t.time = this.time;
t.length = this.length;
for ( var i = 0; i < this.keys.length; i ++ ) {
t.addKey( this.keys[ i ].clone() );
}
t.init();
return t;
};
this.reTarget = function ( root, compareitor ) {
if ( ! compareitor ) compareitor = Virtulous.TrackTargetNodeNameCompare;
this.target = compareitor( root, this.target );
};
this.keySearchAccel = function ( time ) {
time *= this.fps;
time = Math.floor( time );
return this._accelTable[ time ] || 0;
};
this.setTime = function ( time ) {
time = Math.abs( time );
if ( this.length )
time = time % this.length + .05;
var key0 = null;
var key1 = null;
for ( var i = this.keySearchAccel( time ); i < this.keys.length; i ++ ) {
if ( this.keys[ i ].time == time ) {
key0 = this.keys[ i ];
key1 = this.keys[ i ];
break;
} else if ( this.keys[ i ].time < time && this.keys[ i + 1 ] && this.keys[ i + 1 ].time > time ) {
key0 = this.keys[ i ];
key1 = this.keys[ i + 1 ];
break;
} else if ( this.keys[ i ].time < time && i == this.keys.length - 1 ) {
key0 = this.keys[ i ];
key1 = this.keys[ 0 ].clone();
key1.time += this.length + .05;
break;
}
}
if ( key0 && key1 && key0 !== key1 ) {
this.target.matrixAutoUpdate = false;
this.target.matrix.copy( key0.lerp( key1, time ) );
this.target.matrixWorldNeedsUpdate = true;
return;
}
if ( key0 && key1 && key0 == key1 ) {
this.target.matrixAutoUpdate = false;
this.target.matrix.copy( key0.matrix );
this.target.matrixWorldNeedsUpdate = true;
return;
}
};
};
Virtulous.TrackTargetNodeNameCompare = function ( root, target ) {
function find( node, name ) {
if ( node.name == name )
return node;
for ( var i = 0; i < node.children.length; i ++ ) {
var r = find( node.children[ i ], name );
if ( r ) return r;
}
return null;
}
return find( root, target.name );
};
Virtulous.Animation = function () {
this.tracks = [];
this.length = 0;
this.addTrack = function ( track ) {
this.tracks.push( track );
this.length = Math.max( track.length, this.length );
};
this.setTime = function ( time ) {
this.time = time;
for ( var i = 0; i < this.tracks.length; i ++ )
this.tracks[ i ].setTime( time );
};
this.clone = function ( target, compareitor ) {
if ( ! compareitor ) compareitor = Virtulous.TrackTargetNodeNameCompare;
var n = new Virtulous.Animation();
n.target = target;
for ( var i = 0; i < this.tracks.length; i ++ ) {
var track = this.tracks[ i ].clone();
track.reTarget( target, compareitor );
n.addTrack( track );
}
return n;
};
};
var ASSBIN_CHUNK_AICAMERA = 0x1234;
var ASSBIN_CHUNK_AILIGHT = 0x1235;
var ASSBIN_CHUNK_AITEXTURE = 0x1236;
var ASSBIN_CHUNK_AIMESH = 0x1237;
var ASSBIN_CHUNK_AINODEANIM = 0x1238;
var ASSBIN_CHUNK_AISCENE = 0x1239;
var ASSBIN_CHUNK_AIBONE = 0x123a;
var ASSBIN_CHUNK_AIANIMATION = 0x123b;
var ASSBIN_CHUNK_AINODE = 0x123c;
var ASSBIN_CHUNK_AIMATERIAL = 0x123d;
var ASSBIN_CHUNK_AIMATERIALPROPERTY = 0x123e;
var ASSBIN_MESH_HAS_POSITIONS = 0x1;
var ASSBIN_MESH_HAS_NORMALS = 0x2;
var ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS = 0x4;
var ASSBIN_MESH_HAS_TEXCOORD_BASE = 0x100;
var ASSBIN_MESH_HAS_COLOR_BASE = 0x10000;
var AI_MAX_NUMBER_OF_COLOR_SETS = 1;
var AI_MAX_NUMBER_OF_TEXTURECOORDS = 4;
//var aiLightSource_UNDEFINED = 0x0;
//! A directional light source has a well-defined direction
//! but is infinitely far away. That's quite a good
//! approximation for sun light.
var aiLightSource_DIRECTIONAL = 0x1;
//! A point light source has a well-defined position
//! in space but no direction - it emits light in all
//! directions. A normal bulb is a point light.
//var aiLightSource_POINT = 0x2;
//! A spot light source emits light in a specific
//! angle. It has a position and a direction it is pointing to.
//! A good example for a spot light is a light spot in
//! sport arenas.
var aiLightSource_SPOT = 0x3;
//! The generic light level of the world, including the bounces
//! of all other lightsources.
//! Typically, there's at most one ambient light in a scene.
//! This light type doesn't have a valid position, direction, or
//! other properties, just a color.
//var aiLightSource_AMBIENT = 0x4;
/** Flat shading. Shading is done on per-face base,
* diffuse only. Also known as 'faceted shading'.
*/
//var aiShadingMode_Flat = 0x1;
/** Simple Gouraud shading.
*/
//var aiShadingMode_Gouraud = 0x2;
/** Phong-Shading -
*/
//var aiShadingMode_Phong = 0x3;
/** Phong-Blinn-Shading
*/
//var aiShadingMode_Blinn = 0x4;
/** Toon-Shading per pixel
*
* Also known as 'comic' shader.
*/
//var aiShadingMode_Toon = 0x5;
/** OrenNayar-Shading per pixel
*
* Extension to standard Lambertian shading, taking the
* roughness of the material into account
*/
//var aiShadingMode_OrenNayar = 0x6;
/** Minnaert-Shading per pixel
*
* Extension to standard Lambertian shading, taking the
* "darkness" of the material into account
*/
//var aiShadingMode_Minnaert = 0x7;
/** CookTorrance-Shading per pixel
*
* Special shader for metallic surfaces.
*/
//var aiShadingMode_CookTorrance = 0x8;
/** No shading at all. Constant light influence of 1.0.
*/
//var aiShadingMode_NoShading = 0x9;
/** Fresnel shading
*/
//var aiShadingMode_Fresnel = 0xa;
//var aiTextureType_NONE = 0x0;
/** The texture is combined with the result of the diffuse
* lighting equation.
*/
var aiTextureType_DIFFUSE = 0x1;
/** The texture is combined with the result of the specular
* lighting equation.
*/
//var aiTextureType_SPECULAR = 0x2;
/** The texture is combined with the result of the ambient
* lighting equation.
*/
//var aiTextureType_AMBIENT = 0x3;
/** The texture is added to the result of the lighting
* calculation. It isn't influenced by incoming light.
*/
//var aiTextureType_EMISSIVE = 0x4;
/** The texture is a height map.
*
* By convention, higher gray-scale values stand for
* higher elevations from the base height.
*/
//var aiTextureType_HEIGHT = 0x5;
/** The texture is a (tangent space) normal-map.
*
* Again, there are several conventions for tangent-space
* normal maps. Assimp does (intentionally) not
* distinguish here.
*/
var aiTextureType_NORMALS = 0x6;
/** The texture defines the glossiness of the material.
*
* The glossiness is in fact the exponent of the specular
* (phong) lighting equation. Usually there is a conversion
* function defined to map the linear color values in the
* texture to a suitable exponent. Have fun.
*/
//var aiTextureType_SHININESS = 0x7;
/** The texture defines per-pixel opacity.
*
* Usually 'white' means opaque and 'black' means
* 'transparency'. Or quite the opposite. Have fun.
*/
var aiTextureType_OPACITY = 0x8;
/** Displacement texture
*
* The exact purpose and format is application-dependent.
* Higher color values stand for higher vertex displacements.
*/
//var aiTextureType_DISPLACEMENT = 0x9;
/** Lightmap texture (aka Ambient Occlusion)
*
* Both 'Lightmaps' and dedicated 'ambient occlusion maps' are
* covered by this material property. The texture contains a
* scaling value for the final color value of a pixel. Its
* intensity is not affected by incoming light.
*/
var aiTextureType_LIGHTMAP = 0xA;
/** Reflection texture
*
* Contains the color of a perfect mirror reflection.
* Rarely used, almost never for real-time applications.
*/
//var aiTextureType_REFLECTION = 0xB;
/** Unknown texture
*
* A texture reference that does not match any of the definitions
* above is considered to be 'unknown'. It is still imported,
* but is excluded from any further postprocessing.
*/
//var aiTextureType_UNKNOWN = 0xC;
var BONESPERVERT = 4;
function ASSBIN_MESH_HAS_TEXCOORD( n ) {
return ASSBIN_MESH_HAS_TEXCOORD_BASE << n;
}
function ASSBIN_MESH_HAS_COLOR( n ) {
return ASSBIN_MESH_HAS_COLOR_BASE << n;
}
function markBones( scene ) {
for ( var i in scene.mMeshes ) {
var mesh = scene.mMeshes[ i ];
for ( var k in mesh.mBones ) {
var boneNode = scene.findNode( mesh.mBones[ k ].mName );
if ( boneNode )
boneNode.isBone = true;
}
}
}
function cloneTreeToBones( root, scene ) {
var rootBone = new Bone();
rootBone.matrix.copy( root.matrix );
rootBone.matrixWorld.copy( root.matrixWorld );
rootBone.position.copy( root.position );
rootBone.quaternion.copy( root.quaternion );
rootBone.scale.copy( root.scale );
scene.nodeCount ++;
rootBone.name = "bone_" + root.name + scene.nodeCount.toString();
if ( ! scene.nodeToBoneMap[ root.name ] )
scene.nodeToBoneMap[ root.name ] = [];
scene.nodeToBoneMap[ root.name ].push( rootBone );
for ( var i in root.children ) {
var child = cloneTreeToBones( root.children[ i ], scene );
rootBone.add( child );
}
return rootBone;
}
function sortWeights( indexes, weights ) {
var pairs = [];
for ( var i = 0; i < indexes.length; i ++ ) {
pairs.push( {
i: indexes[ i ],
w: weights[ i ]
} );
}
pairs.sort( function ( a, b ) {
return b.w - a.w;
} );
while ( pairs.length < 4 ) {
pairs.push( {
i: 0,
w: 0
} );
}
if ( pairs.length > 4 )
pairs.length = 4;
var sum = 0;
for ( var i = 0; i < 4; i ++ ) {
sum += pairs[ i ].w * pairs[ i ].w;
}
sum = Math.sqrt( sum );
for ( var i = 0; i < 4; i ++ ) {
pairs[ i ].w = pairs[ i ].w / sum;
indexes[ i ] = pairs[ i ].i;
weights[ i ] = pairs[ i ].w;
}
}
function findMatchingBone( root, name ) {
if ( root.name.indexOf( "bone_" + name ) == 0 )
return root;
for ( var i in root.children ) {
var ret = findMatchingBone( root.children[ i ], name );
if ( ret )
return ret;
}
return undefined;
}
function aiMesh() {
this.mPrimitiveTypes = 0;
this.mNumVertices = 0;
this.mNumFaces = 0;
this.mNumBones = 0;
this.mMaterialIndex = 0;
this.mVertices = [];
this.mNormals = [];
this.mTangents = [];
this.mBitangents = [];
this.mColors = [
[]
];
this.mTextureCoords = [
[]
];
this.mFaces = [];
this.mBones = [];
this.hookupSkeletons = function ( scene ) {
if ( this.mBones.length == 0 ) return;
var allBones = [];
var offsetMatrix = [];
var skeletonRoot = scene.findNode( this.mBones[ 0 ].mName );
while ( skeletonRoot.mParent && skeletonRoot.mParent.isBone ) {
skeletonRoot = skeletonRoot.mParent;
}
var threeSkeletonRoot = skeletonRoot.toTHREE( scene );
var threeSkeletonRootBone = cloneTreeToBones( threeSkeletonRoot, scene );
this.threeNode.add( threeSkeletonRootBone );
for ( var i = 0; i < this.mBones.length; i ++ ) {
var bone = findMatchingBone( threeSkeletonRootBone, this.mBones[ i ].mName );
if ( bone ) {
var tbone = bone;
allBones.push( tbone );
//tbone.matrixAutoUpdate = false;
offsetMatrix.push( this.mBones[ i ].mOffsetMatrix.toTHREE() );
} else {
var skeletonRoot = scene.findNode( this.mBones[ i ].mName );
if ( ! skeletonRoot ) return;
var threeSkeletonRoot = skeletonRoot.toTHREE( scene );
var threeSkeletonRootBone = cloneTreeToBones( threeSkeletonRoot, scene );
this.threeNode.add( threeSkeletonRootBone );
var bone = findMatchingBone( threeSkeletonRootBone, this.mBones[ i ].mName );
var tbone = bone;
allBones.push( tbone );
//tbone.matrixAutoUpdate = false;
offsetMatrix.push( this.mBones[ i ].mOffsetMatrix.toTHREE() );
}
}
var skeleton = new Skeleton( allBones, offsetMatrix );
this.threeNode.bind( skeleton, new Matrix4() );
this.threeNode.material.skinning = true;
};
this.toTHREE = function ( scene ) {
if ( this.threeNode ) return this.threeNode;
var geometry = new BufferGeometry();
var mat;
if ( scene.mMaterials[ this.mMaterialIndex ] )
mat = scene.mMaterials[ this.mMaterialIndex ].toTHREE( scene );
else
mat = new MeshLambertMaterial();
geometry.setIndex( new BufferAttribute( new Uint32Array( this.mIndexArray ), 1 ) );
geometry.addAttribute( 'position', new BufferAttribute( this.mVertexBuffer, 3 ) );
if ( this.mNormalBuffer && this.mNormalBuffer.length > 0 )
geometry.addAttribute( 'normal', new BufferAttribute( this.mNormalBuffer, 3 ) );
if ( this.mColorBuffer && this.mColorBuffer.length > 0 )
geometry.addAttribute( 'color', new BufferAttribute( this.mColorBuffer, 4 ) );
if ( this.mTexCoordsBuffers[ 0 ] && this.mTexCoordsBuffers[ 0 ].length > 0 )
geometry.addAttribute( 'uv', new BufferAttribute( new Float32Array( this.mTexCoordsBuffers[ 0 ] ), 2 ) );
if ( this.mTexCoordsBuffers[ 1 ] && this.mTexCoordsBuffers[ 1 ].length > 0 )
geometry.addAttribute( 'uv1', new BufferAttribute( new Float32Array( this.mTexCoordsBuffers[ 1 ] ), 2 ) );
if ( this.mTangentBuffer && this.mTangentBuffer.length > 0 )
geometry.addAttribute( 'tangents', new BufferAttribute( this.mTangentBuffer, 3 ) );
if ( this.mBitangentBuffer && this.mBitangentBuffer.length > 0 )
geometry.addAttribute( 'bitangents', new BufferAttribute( this.mBitangentBuffer, 3 ) );
if ( this.mBones.length > 0 ) {
var weights = [];
var bones = [];
for ( var i = 0; i < this.mBones.length; i ++ ) {
for ( var j = 0; j < this.mBones[ i ].mWeights.length; j ++ ) {
var weight = this.mBones[ i ].mWeights[ j ];
if ( weight ) {
if ( ! weights[ weight.mVertexId ] ) weights[ weight.mVertexId ] = [];
if ( ! bones[ weight.mVertexId ] ) bones[ weight.mVertexId ] = [];
weights[ weight.mVertexId ].push( weight.mWeight );
bones[ weight.mVertexId ].push( parseInt( i ) );
}
}
}
for ( var i in bones ) {
sortWeights( bones[ i ], weights[ i ] );
}
var _weights = [];
var _bones = [];
for ( var i = 0; i < weights.length; i ++ ) {
for ( var j = 0; j < 4; j ++ ) {
if ( weights[ i ] && bones[ i ] ) {
_weights.push( weights[ i ][ j ] );
_bones.push( bones[ i ][ j ] );
} else {
_weights.push( 0 );
_bones.push( 0 );
}
}
}
geometry.addAttribute( 'skinWeight', new BufferAttribute( new Float32Array( _weights ), BONESPERVERT ) );
geometry.addAttribute( 'skinIndex', new BufferAttribute( new Float32Array( _bones ), BONESPERVERT ) );
}
var mesh;
if ( this.mBones.length == 0 )
mesh = new Mesh( geometry, mat );
if ( this.mBones.length > 0 ) {
mesh = new SkinnedMesh( geometry, mat );
mesh.normalizeSkinWeights();
}
this.threeNode = mesh;
//mesh.matrixAutoUpdate = false;
return mesh;
};
}
function aiFace() {
this.mNumIndices = 0;
this.mIndices = [];
}
function aiVector3D() {
this.x = 0;
this.y = 0;
this.z = 0;
this.toTHREE = function () {
return new Vector3( this.x, this.y, this.z );
};
}
function aiColor3D() {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = 0;
this.toTHREE = function () {
return new Color( this.r, this.g, this.b );
};
}
function aiQuaternion() {
this.x = 0;
this.y = 0;
this.z = 0;
this.w = 0;
this.toTHREE = function () {
return new Quaternion( this.x, this.y, this.z, this.w );
};
}
function aiVertexWeight() {
this.mVertexId = 0;
this.mWeight = 0;
}
function aiString() {
this.data = [];
this.toString = function () {
var str = '';
this.data.forEach( function ( i ) {
str += ( String.fromCharCode( i ) );
} );
return str.replace( /[^\x20-\x7E]+/g, '' );
};
}
function aiVectorKey() {
this.mTime = 0;
this.mValue = null;
}
function aiQuatKey() {
this.mTime = 0;
this.mValue = null;
}
function aiNode() {
this.mName = '';
this.mTransformation = [];
this.mNumChildren = 0;
this.mNumMeshes = 0;
this.mMeshes = [];
this.mChildren = [];
this.toTHREE = function ( scene ) {
if ( this.threeNode ) return this.threeNode;
var o = new Object3D();
o.name = this.mName;
o.matrix = this.mTransformation.toTHREE();
for ( var i = 0; i < this.mChildren.length; i ++ ) {
o.add( this.mChildren[ i ].toTHREE( scene ) );
}
for ( var i = 0; i < this.mMeshes.length; i ++ ) {
o.add( scene.mMeshes[ this.mMeshes[ i ] ].toTHREE( scene ) );
}
this.threeNode = o;
//o.matrixAutoUpdate = false;
o.matrix.decompose( o.position, o.quaternion, o.scale );
return o;
};
}
function aiBone() {
this.mName = '';
this.mNumWeights = 0;
this.mOffsetMatrix = 0;
}
function aiMaterialProperty() {
this.mKey = "";
this.mSemantic = 0;
this.mIndex = 0;
this.mData = [];
this.mDataLength = 0;
this.mType = 0;
this.dataAsColor = function () {
var array = ( new Uint8Array( this.mData ) ).buffer;
var reader = new DataView( array );
var r = reader.getFloat32( 0, true );
var g = reader.getFloat32( 4, true );
var b = reader.getFloat32( 8, true );
//var a = reader.getFloat32(12, true);
return new Color( r, g, b );
};
this.dataAsFloat = function () {
var array = ( new Uint8Array( this.mData ) ).buffer;
var reader = new DataView( array );
var r = reader.getFloat32( 0, true );
return r;
};
this.dataAsBool = function () {
var array = ( new Uint8Array( this.mData ) ).buffer;
var reader = new DataView( array );
var r = reader.getFloat32( 0, true );
return !! r;
};
this.dataAsString = function () {
var s = new aiString();
s.data = this.mData;
return s.toString();
};
this.dataAsMap = function () {
var s = new aiString();
s.data = this.mData;
var path = s.toString();
path = path.replace( /\\/g, '/' );
if ( path.indexOf( '/' ) != - 1 ) {
path = path.substr( path.lastIndexOf( '/' ) + 1 );
}
return textureLoader.load( path );
};
}
var namePropMapping = {
"?mat.name": "name",
"$mat.shadingm": "shading",
"$mat.twosided": "twoSided",
"$mat.wireframe": "wireframe",
"$clr.ambient": "ambient",
"$clr.diffuse": "color",
"$clr.specular": "specular",
"$clr.emissive": "emissive",
"$clr.transparent": "transparent",
"$clr.reflective": "reflect",
"$mat.shininess": "shininess",
"$mat.reflectivity": "reflectivity",
"$mat.refracti": "refraction",
"$tex.file": "map"
};
var nameTypeMapping = {
"?mat.name": "string",
"$mat.shadingm": "bool",
"$mat.twosided": "bool",
"$mat.wireframe": "bool",
"$clr.ambient": "color",
"$clr.diffuse": "color",
"$clr.specular": "color",
"$clr.emissive": "color",
"$clr.transparent": "color",
"$clr.reflective": "color",
"$mat.shininess": "float",
"$mat.reflectivity": "float",
"$mat.refracti": "float",
"$tex.file": "map"
};
function aiMaterial() {
this.mNumAllocated = 0;
this.mNumProperties = 0;
this.mProperties = [];
this.toTHREE = function () {
var mat = new MeshPhongMaterial();
for ( var i = 0; i < this.mProperties.length; i ++ ) {
if ( nameTypeMapping[ this.mProperties[ i ].mKey ] == 'float' )
mat[ namePropMapping[ this.mProperties[ i ].mKey ] ] = this.mProperties[ i ].dataAsFloat();
if ( nameTypeMapping[ this.mProperties[ i ].mKey ] == 'color' )
mat[ namePropMapping[ this.mProperties[ i ].mKey ] ] = this.mProperties[ i ].dataAsColor();
if ( nameTypeMapping[ this.mProperties[ i ].mKey ] == 'bool' )
mat[ namePropMapping[ this.mProperties[ i ].mKey ] ] = this.mProperties[ i ].dataAsBool();
if ( nameTypeMapping[ this.mProperties[ i ].mKey ] == 'string' )
mat[ namePropMapping[ this.mProperties[ i ].mKey ] ] = this.mProperties[ i ].dataAsString();
if ( nameTypeMapping[ this.mProperties[ i ].mKey ] == 'map' ) {
var prop = this.mProperties[ i ];
if ( prop.mSemantic == aiTextureType_DIFFUSE )
mat.map = this.mProperties[ i ].dataAsMap();
if ( prop.mSemantic == aiTextureType_NORMALS )
mat.normalMap = this.mProperties[ i ].dataAsMap();
if ( prop.mSemantic == aiTextureType_LIGHTMAP )
mat.lightMap = this.mProperties[ i ].dataAsMap();
if ( prop.mSemantic == aiTextureType_OPACITY )
mat.alphaMap = this.mProperties[ i ].dataAsMap();
}
}
mat.ambient.r = .53;
mat.ambient.g = .53;
mat.ambient.b = .53;
mat.color.r = 1;
mat.color.g = 1;
mat.color.b = 1;
return mat;
};
}
function veclerp( v1, v2, l ) {
var v = new Vector3();
var lm1 = 1 - l;
v.x = v1.x * l + v2.x * lm1;
v.y = v1.y * l + v2.y * lm1;
v.z = v1.z * l + v2.z * lm1;
return v;
}
function quatlerp( q1, q2, l ) {
return q1.clone().slerp( q2, 1 - l );
}
function sampleTrack( keys, time, lne, lerp ) {
if ( keys.length == 1 ) return keys[ 0 ].mValue.toTHREE();
var dist = Infinity;
var key = null;
var nextKey = null;
for ( var i = 0; i < keys.length; i ++ ) {
var timeDist = Math.abs( keys[ i ].mTime - time );
if ( timeDist < dist && keys[ i ].mTime <= time ) {
dist = timeDist;
key = keys[ i ];
nextKey = keys[ i + 1 ];
}
}
if ( ! key ) {
return null;
} else if ( nextKey ) {
var dT = nextKey.mTime - key.mTime;
var T = key.mTime - time;
var l = T / dT;
return lerp( key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l );
} else {
nextKey = keys[ 0 ].clone();
nextKey.mTime += lne;
var dT = nextKey.mTime - key.mTime;
var T = key.mTime - time;
var l = T / dT;
return lerp( key.mValue.toTHREE(), nextKey.mValue.toTHREE(), l );
}
}
function aiNodeAnim() {
this.mNodeName = "";
this.mNumPositionKeys = 0;
this.mNumRotationKeys = 0;
this.mNumScalingKeys = 0;
this.mPositionKeys = [];
this.mRotationKeys = [];
this.mScalingKeys = [];
this.mPreState = "";
this.mPostState = "";
this.init = function ( tps ) {
if ( ! tps ) tps = 1;
function t( t ) {
t.mTime /= tps;
}
this.mPositionKeys.forEach( t );
this.mRotationKeys.forEach( t );
this.mScalingKeys.forEach( t );
};
this.sortKeys = function () {
function comp( a, b ) {
return a.mTime - b.mTime;
}
this.mPositionKeys.sort( comp );
this.mRotationKeys.sort( comp );
this.mScalingKeys.sort( comp );
};
this.getLength = function () {
return Math.max(
Math.max.apply( null, this.mPositionKeys.map( function ( a ) {
return a.mTime;
} ) ),
Math.max.apply( null, this.mRotationKeys.map( function ( a ) {
return a.mTime;
} ) ),
Math.max.apply( null, this.mScalingKeys.map( function ( a ) {
return a.mTime;
} ) )
);
};
this.toTHREE = function ( o ) {
this.sortKeys();
var length = this.getLength();
var track = new Virtulous.KeyFrameTrack();
for ( var i = 0; i < length; i += .05 ) {
var matrix = new Matrix4();
var time = i;
var pos = sampleTrack( this.mPositionKeys, time, length, veclerp );
var scale = sampleTrack( this.mScalingKeys, time, length, veclerp );
var rotation = sampleTrack( this.mRotationKeys, time, length, quatlerp );
matrix.compose( pos, rotation, scale );
var key = new Virtulous.KeyFrame( time, matrix );
track.addKey( key );
}
track.target = o.findNode( this.mNodeName ).toTHREE();
var tracks = [ track ];
if ( o.nodeToBoneMap[ this.mNodeName ] ) {
for ( var i = 0; i < o.nodeToBoneMap[ this.mNodeName ].length; i ++ ) {
var t2 = track.clone();
t2.target = o.nodeToBoneMap[ this.mNodeName ][ i ];
tracks.push( t2 );
}
}
return tracks;
};
}
function aiAnimation() {
this.mName = "";
this.mDuration = 0;
this.mTicksPerSecond = 0;
this.mNumChannels = 0;
this.mChannels = [];
this.toTHREE = function ( root ) {
var animationHandle = new Virtulous.Animation();
for ( var i in this.mChannels ) {
this.mChannels[ i ].init( this.mTicksPerSecond );
var tracks = this.mChannels[ i ].toTHREE( root );
for ( var j in tracks ) {
tracks[ j ].init();
animationHandle.addTrack( tracks[ j ] );
}
}
animationHandle.length = Math.max.apply( null, animationHandle.tracks.map( function ( e ) {
return e.length;
} ) );
return animationHandle;
};
}
function aiTexture() {
this.mWidth = 0;
this.mHeight = 0;
this.texAchFormatHint = [];
this.pcData = [];
}
function aiLight() {
this.mName = '';
this.mType = 0;
this.mAttenuationConstant = 0;
this.mAttenuationLinear = 0;
this.mAttenuationQuadratic = 0;
this.mAngleInnerCone = 0;
this.mAngleOuterCone = 0;
this.mColorDiffuse = null;
this.mColorSpecular = null;
this.mColorAmbient = null;
}
function aiCamera() {
this.mName = '';
this.mPosition = null;
this.mLookAt = null;
this.mUp = null;
this.mHorizontalFOV = 0;
this.mClipPlaneNear = 0;
this.mClipPlaneFar = 0;
this.mAspect = 0;
}
function aiScene() {
this.versionMajor = 0;
this.versionMinor = 0;
this.versionRevision = 0;
this.compileFlags = 0;
this.mFlags = 0;
this.mNumMeshes = 0;
this.mNumMaterials = 0;
this.mNumAnimations = 0;
this.mNumTextures = 0;
this.mNumLights = 0;
this.mNumCameras = 0;
this.mRootNode = null;
this.mMeshes = [];
this.mMaterials = [];
this.mAnimations = [];
this.mLights = [];
this.mCameras = [];
this.nodeToBoneMap = {};
this.findNode = function ( name, root ) {
if ( ! root ) {
root = this.mRootNode;
}
if ( root.mName == name ) {
return root;
}
for ( var i = 0; i < root.mChildren.length; i ++ ) {
var ret = this.findNode( name, root.mChildren[ i ] );
if ( ret ) return ret;
}
return null;
};
this.toTHREE = function () {
this.nodeCount = 0;
markBones( this );
var o = this.mRootNode.toTHREE( this );
for ( var i in this.mMeshes )
this.mMeshes[ i ].hookupSkeletons( this );
if ( this.mAnimations.length > 0 ) {
var a = this.mAnimations[ 0 ].toTHREE( this );
}
return { object: o, animation: a };
};
}
function aiMatrix4() {
this.elements = [
[],
[],
[],
[]
];
this.toTHREE = function () {
var m = new Matrix4();
for ( var i = 0; i < 4; ++ i ) {
for ( var i2 = 0; i2 < 4; ++ i2 ) {
m.elements[ i * 4 + i2 ] = this.elements[ i2 ][ i ];
}
}
return m;
};
}
var littleEndian = true;
function readFloat( dataview ) {
var val = dataview.getFloat32( dataview.readOffset, littleEndian );
dataview.readOffset += 4;
return val;
}
function Read_double( dataview ) {
var val = dataview.getFloat64( dataview.readOffset, littleEndian );
dataview.readOffset += 8;
return val;
}
function Read_uint8_t( dataview ) {
var val = dataview.getUint8( dataview.readOffset );
dataview.readOffset += 1;
return val;
}
function Read_uint16_t( dataview ) {
var val = dataview.getUint16( dataview.readOffset, littleEndian );
dataview.readOffset += 2;
return val;
}
function Read_unsigned_int( dataview ) {
var val = dataview.getUint32( dataview.readOffset, littleEndian );
dataview.readOffset += 4;
return val;
}
function Read_uint32_t( dataview ) {
var val = dataview.getUint32( dataview.readOffset, littleEndian );
dataview.readOffset += 4;
return val;
}
function Read_aiVector3D( stream ) {
var v = new aiVector3D();
v.x = readFloat( stream );
v.y = readFloat( stream );
v.z = readFloat( stream );
return v;
}
function Read_aiColor3D( stream ) {
var c = new aiColor3D();
c.r = readFloat( stream );
c.g = readFloat( stream );
c.b = readFloat( stream );
return c;
}
function Read_aiQuaternion( stream ) {
var v = new aiQuaternion();
v.w = readFloat( stream );
v.x = readFloat( stream );
v.y = readFloat( stream );
v.z = readFloat( stream );
return v;
}
function Read_aiString( stream ) {
var s = new aiString();
var stringlengthbytes = Read_unsigned_int( stream );
stream.ReadBytes( s.data, 1, stringlengthbytes );
return s.toString();
}
function Read_aiVertexWeight( stream ) {
var w = new aiVertexWeight();
w.mVertexId = Read_unsigned_int( stream );
w.mWeight = readFloat( stream );
return w;
}
function Read_aiMatrix4x4( stream ) {
var m = new aiMatrix4();
for ( var i = 0; i < 4; ++ i ) {
for ( var i2 = 0; i2 < 4; ++ i2 ) {
m.elements[ i ][ i2 ] = readFloat( stream );
}
}
return m;
}
function Read_aiVectorKey( stream ) {
var v = new aiVectorKey();
v.mTime = Read_double( stream );
v.mValue = Read_aiVector3D( stream );
return v;
}
function Read_aiQuatKey( stream ) {
var v = new aiQuatKey();
v.mTime = Read_double( stream );
v.mValue = Read_aiQuaternion( stream );
return v;
}
function ReadArray_aiVertexWeight( stream, data, size ) {
for ( var i = 0; i < size; i ++ ) data[ i ] = Read_aiVertexWeight( stream );
}
function ReadArray_aiVectorKey( stream, data, size ) {
for ( var i = 0; i < size; i ++ ) data[ i ] = Read_aiVectorKey( stream );
}
function ReadArray_aiQuatKey( stream, data, size ) {
for ( var i = 0; i < size; i ++ ) data[ i ] = Read_aiQuatKey( stream );
}
function ReadBounds( stream, T /*p*/, n ) {
// not sure what to do here, the data isn't really useful.
return stream.Seek( sizeof( T ) * n, aiOrigin_CUR );
}
function ai_assert( bool ) {
if ( ! bool )
throw ( "asset failed" );
}
function ReadBinaryNode( stream, parent, depth ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AINODE );
/*uint32_t size =*/
Read_uint32_t( stream );
var node = new aiNode();
node.mParent = parent;
node.mDepth = depth;
node.mName = Read_aiString( stream );
node.mTransformation = Read_aiMatrix4x4( stream );
node.mNumChildren = Read_unsigned_int( stream );
node.mNumMeshes = Read_unsigned_int( stream );
if ( node.mNumMeshes ) {
node.mMeshes = [];
for ( var i = 0; i < node.mNumMeshes; ++ i ) {
node.mMeshes[ i ] = Read_unsigned_int( stream );
}
}
if ( node.mNumChildren ) {
node.mChildren = [];
for ( var i = 0; i < node.mNumChildren; ++ i ) {
var node2 = ReadBinaryNode( stream, node, depth ++ );
node.mChildren[ i ] = node2;
}
}
return node;
}
// -----------------------------------------------------------------------------------
function ReadBinaryBone( stream, b ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AIBONE );
/*uint32_t size =*/
Read_uint32_t( stream );
b.mName = Read_aiString( stream );
b.mNumWeights = Read_unsigned_int( stream );
b.mOffsetMatrix = Read_aiMatrix4x4( stream );
// for the moment we write dumb min/max values for the bones, too.
// maybe I'll add a better, hash-like solution later
if ( shortened ) {
ReadBounds( stream, b.mWeights, b.mNumWeights );
} else {
// else write as usual
b.mWeights = [];
ReadArray_aiVertexWeight( stream, b.mWeights, b.mNumWeights );
}
return b;
}
function ReadBinaryMesh( stream, mesh ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AIMESH );
/*uint32_t size =*/
Read_uint32_t( stream );
mesh.mPrimitiveTypes = Read_unsigned_int( stream );
mesh.mNumVertices = Read_unsigned_int( stream );
mesh.mNumFaces = Read_unsigned_int( stream );
mesh.mNumBones = Read_unsigned_int( stream );
mesh.mMaterialIndex = Read_unsigned_int( stream );
mesh.mNumUVComponents = [];
// first of all, write bits for all existent vertex components
var c = Read_unsigned_int( stream );
if ( c & ASSBIN_MESH_HAS_POSITIONS ) {
if ( shortened ) {
ReadBounds( stream, mesh.mVertices, mesh.mNumVertices );
} else {
// else write as usual
mesh.mVertices = [];
mesh.mVertexBuffer = stream.subArray32( stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4 );
stream.Seek( mesh.mNumVertices * 3 * 4, aiOrigin_CUR );
}
}
if ( c & ASSBIN_MESH_HAS_NORMALS ) {
if ( shortened ) {
ReadBounds( stream, mesh.mNormals, mesh.mNumVertices );
} else {
// else write as usual
mesh.mNormals = [];
mesh.mNormalBuffer = stream.subArray32( stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4 );
stream.Seek( mesh.mNumVertices * 3 * 4, aiOrigin_CUR );
}
}
if ( c & ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS ) {
if ( shortened ) {
ReadBounds( stream, mesh.mTangents, mesh.mNumVertices );
ReadBounds( stream, mesh.mBitangents, mesh.mNumVertices );
} else {
// else write as usual
mesh.mTangents = [];
mesh.mTangentBuffer = stream.subArray32( stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4 );
stream.Seek( mesh.mNumVertices * 3 * 4, aiOrigin_CUR );
mesh.mBitangents = [];
mesh.mBitangentBuffer = stream.subArray32( stream.readOffset, stream.readOffset + mesh.mNumVertices * 3 * 4 );
stream.Seek( mesh.mNumVertices * 3 * 4, aiOrigin_CUR );
}
}
for ( var n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++ n ) {
if ( ! ( c & ASSBIN_MESH_HAS_COLOR( n ) ) ) break;
if ( shortened ) {
ReadBounds( stream, mesh.mColors[ n ], mesh.mNumVertices );
} else {
// else write as usual
mesh.mColors[ n ] = [];
mesh.mColorBuffer = stream.subArray32( stream.readOffset, stream.readOffset + mesh.mNumVertices * 4 * 4 );
stream.Seek( mesh.mNumVertices * 4 * 4, aiOrigin_CUR );
}
}
mesh.mTexCoordsBuffers = [];
for ( var n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++ n ) {
if ( ! ( c & ASSBIN_MESH_HAS_TEXCOORD( n ) ) ) break;
// write number of UV components
mesh.mNumUVComponents[ n ] = Read_unsigned_int( stream );
if ( shortened ) {
ReadBounds( stream, mesh.mTextureCoords[ n ], mesh.mNumVertices );
} else {
// else write as usual
mesh.mTextureCoords[ n ] = [];
//note that assbin always writes 3d texcoords
mesh.mTexCoordsBuffers[ n ] = [];
for ( var uv = 0; uv < mesh.mNumVertices; uv ++ ) {
mesh.mTexCoordsBuffers[ n ].push( readFloat( stream ) );
mesh.mTexCoordsBuffers[ n ].push( readFloat( stream ) );
readFloat( stream );
}
}
}
// write faces. There are no floating-point calculations involved
// in these, so we can write a simple hash over the face data
// to the dump file. We generate a single 32 Bit hash for 512 faces
// using Assimp's standard hashing function.
if ( shortened ) {
Read_unsigned_int( stream );
} else {
// else write as usual
// if there are less than 2^16 vertices, we can simply use 16 bit integers ...
mesh.mFaces = [];
mesh.mIndexArray = [];
for ( var i = 0; i < mesh.mNumFaces; ++ i ) {
var f = mesh.mFaces[ i ] = new aiFace();
// BOOST_STATIC_ASSERT(AI_MAX_FACE_INDICES <= 0xffff);
f.mNumIndices = Read_uint16_t( stream );
f.mIndices = [];
for ( var a = 0; a < f.mNumIndices; ++ a ) {
if ( mesh.mNumVertices < ( 1 << 16 ) ) {
f.mIndices[ a ] = Read_uint16_t( stream );
} else {
f.mIndices[ a ] = Read_unsigned_int( stream );
}
}
if ( f.mNumIndices === 3 ) {
mesh.mIndexArray.push( f.mIndices[ 0 ] );
mesh.mIndexArray.push( f.mIndices[ 1 ] );
mesh.mIndexArray.push( f.mIndices[ 2 ] );
} else if ( f.mNumIndices === 4 ) {
mesh.mIndexArray.push( f.mIndices[ 0 ] );
mesh.mIndexArray.push( f.mIndices[ 1 ] );
mesh.mIndexArray.push( f.mIndices[ 2 ] );
mesh.mIndexArray.push( f.mIndices[ 2 ] );
mesh.mIndexArray.push( f.mIndices[ 3 ] );
mesh.mIndexArray.push( f.mIndices[ 0 ] );
} else {
throw ( new Error( "Sorry, can't currently triangulate polys. Use the triangulate preprocessor in Assimp." ) );
}
}
}
// write bones
if ( mesh.mNumBones ) {
mesh.mBones = [];
for ( var a = 0; a < mesh.mNumBones; ++ a ) {
mesh.mBones[ a ] = new aiBone();
ReadBinaryBone( stream, mesh.mBones[ a ] );
}
}
}
function ReadBinaryMaterialProperty( stream, prop ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AIMATERIALPROPERTY );
/*uint32_t size =*/
Read_uint32_t( stream );
prop.mKey = Read_aiString( stream );
prop.mSemantic = Read_unsigned_int( stream );
prop.mIndex = Read_unsigned_int( stream );
prop.mDataLength = Read_unsigned_int( stream );
prop.mType = Read_unsigned_int( stream );
prop.mData = [];
stream.ReadBytes( prop.mData, 1, prop.mDataLength );
}
// -----------------------------------------------------------------------------------
function ReadBinaryMaterial( stream, mat ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AIMATERIAL );
/*uint32_t size =*/
Read_uint32_t( stream );
mat.mNumAllocated = mat.mNumProperties = Read_unsigned_int( stream );
if ( mat.mNumProperties ) {
if ( mat.mProperties ) {
delete mat.mProperties;
}
mat.mProperties = [];
for ( var i = 0; i < mat.mNumProperties; ++ i ) {
mat.mProperties[ i ] = new aiMaterialProperty();
ReadBinaryMaterialProperty( stream, mat.mProperties[ i ] );
}
}
}
// -----------------------------------------------------------------------------------
function ReadBinaryNodeAnim( stream, nd ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AINODEANIM );
/*uint32_t size =*/
Read_uint32_t( stream );
nd.mNodeName = Read_aiString( stream );
nd.mNumPositionKeys = Read_unsigned_int( stream );
nd.mNumRotationKeys = Read_unsigned_int( stream );
nd.mNumScalingKeys = Read_unsigned_int( stream );
nd.mPreState = Read_unsigned_int( stream );
nd.mPostState = Read_unsigned_int( stream );
if ( nd.mNumPositionKeys ) {
if ( shortened ) {
ReadBounds( stream, nd.mPositionKeys, nd.mNumPositionKeys );
} else {
// else write as usual
nd.mPositionKeys = [];
ReadArray_aiVectorKey( stream, nd.mPositionKeys, nd.mNumPositionKeys );
}
}
if ( nd.mNumRotationKeys ) {
if ( shortened ) {
ReadBounds( stream, nd.mRotationKeys, nd.mNumRotationKeys );
} else {
// else write as usual
nd.mRotationKeys = [];
ReadArray_aiQuatKey( stream, nd.mRotationKeys, nd.mNumRotationKeys );
}
}
if ( nd.mNumScalingKeys ) {
if ( shortened ) {
ReadBounds( stream, nd.mScalingKeys, nd.mNumScalingKeys );
} else {
// else write as usual
nd.mScalingKeys = [];
ReadArray_aiVectorKey( stream, nd.mScalingKeys, nd.mNumScalingKeys );
}
}
}
// -----------------------------------------------------------------------------------
function ReadBinaryAnim( stream, anim ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AIANIMATION );
/*uint32_t size =*/
Read_uint32_t( stream );
anim.mName = Read_aiString( stream );
anim.mDuration = Read_double( stream );
anim.mTicksPerSecond = Read_double( stream );
anim.mNumChannels = Read_unsigned_int( stream );
if ( anim.mNumChannels ) {
anim.mChannels = [];
for ( var a = 0; a < anim.mNumChannels; ++ a ) {
anim.mChannels[ a ] = new aiNodeAnim();
ReadBinaryNodeAnim( stream, anim.mChannels[ a ] );
}
}
}
function ReadBinaryTexture( stream, tex ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AITEXTURE );
/*uint32_t size =*/
Read_uint32_t( stream );
tex.mWidth = Read_unsigned_int( stream );
tex.mHeight = Read_unsigned_int( stream );
stream.ReadBytes( tex.achFormatHint, 1, 4 );
if ( ! shortened ) {
if ( ! tex.mHeight ) {
tex.pcData = [];
stream.ReadBytes( tex.pcData, 1, tex.mWidth );
} else {
tex.pcData = [];
stream.ReadBytes( tex.pcData, 1, tex.mWidth * tex.mHeight * 4 );
}
}
}
// -----------------------------------------------------------------------------------
function ReadBinaryLight( stream, l ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AILIGHT );
/*uint32_t size =*/
Read_uint32_t( stream );
l.mName = Read_aiString( stream );
l.mType = Read_unsigned_int( stream );
if ( l.mType != aiLightSource_DIRECTIONAL ) {
l.mAttenuationConstant = readFloat( stream );
l.mAttenuationLinear = readFloat( stream );
l.mAttenuationQuadratic = readFloat( stream );
}
l.mColorDiffuse = Read_aiColor3D( stream );
l.mColorSpecular = Read_aiColor3D( stream );
l.mColorAmbient = Read_aiColor3D( stream );
if ( l.mType == aiLightSource_SPOT ) {
l.mAngleInnerCone = readFloat( stream );
l.mAngleOuterCone = readFloat( stream );
}
}
// -----------------------------------------------------------------------------------
function ReadBinaryCamera( stream, cam ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AICAMERA );
/*uint32_t size =*/
Read_uint32_t( stream );
cam.mName = Read_aiString( stream );
cam.mPosition = Read_aiVector3D( stream );
cam.mLookAt = Read_aiVector3D( stream );
cam.mUp = Read_aiVector3D( stream );
cam.mHorizontalFOV = readFloat( stream );
cam.mClipPlaneNear = readFloat( stream );
cam.mClipPlaneFar = readFloat( stream );
cam.mAspect = readFloat( stream );
}
function ReadBinaryScene( stream, scene ) {
var chunkID = Read_uint32_t( stream );
ai_assert( chunkID == ASSBIN_CHUNK_AISCENE );
/*uint32_t size =*/
Read_uint32_t( stream );
scene.mFlags = Read_unsigned_int( stream );
scene.mNumMeshes = Read_unsigned_int( stream );
scene.mNumMaterials = Read_unsigned_int( stream );
scene.mNumAnimations = Read_unsigned_int( stream );
scene.mNumTextures = Read_unsigned_int( stream );
scene.mNumLights = Read_unsigned_int( stream );
scene.mNumCameras = Read_unsigned_int( stream );
// Read node graph
scene.mRootNode = new aiNode();
scene.mRootNode = ReadBinaryNode( stream, null, 0 );
// Read all meshes
if ( scene.mNumMeshes ) {
scene.mMeshes = [];
for ( var i = 0; i < scene.mNumMeshes; ++ i ) {
scene.mMeshes[ i ] = new aiMesh();
ReadBinaryMesh( stream, scene.mMeshes[ i ] );
}
}
// Read materials
if ( scene.mNumMaterials ) {
scene.mMaterials = [];
for ( var i = 0; i < scene.mNumMaterials; ++ i ) {
scene.mMaterials[ i ] = new aiMaterial();
ReadBinaryMaterial( stream, scene.mMaterials[ i ] );
}
}
// Read all animations
if ( scene.mNumAnimations ) {
scene.mAnimations = [];
for ( var i = 0; i < scene.mNumAnimations; ++ i ) {
scene.mAnimations[ i ] = new aiAnimation();
ReadBinaryAnim( stream, scene.mAnimations[ i ] );
}
}
// Read all textures
if ( scene.mNumTextures ) {
scene.mTextures = [];
for ( var i = 0; i < scene.mNumTextures; ++ i ) {
scene.mTextures[ i ] = new aiTexture();
ReadBinaryTexture( stream, scene.mTextures[ i ] );
}
}
// Read lights
if ( scene.mNumLights ) {
scene.mLights = [];
for ( var i = 0; i < scene.mNumLights; ++ i ) {
scene.mLights[ i ] = new aiLight();
ReadBinaryLight( stream, scene.mLights[ i ] );
}
}
// Read cameras
if ( scene.mNumCameras ) {
scene.mCameras = [];
for ( var i = 0; i < scene.mNumCameras; ++ i ) {
scene.mCameras[ i ] = new aiCamera();
ReadBinaryCamera( stream, scene.mCameras[ i ] );
}
}
}
var aiOrigin_CUR = 0;
var aiOrigin_BEG = 1;
function extendStream( stream ) {
stream.readOffset = 0;
stream.Seek = function ( off, ori ) {
if ( ori == aiOrigin_CUR ) {
stream.readOffset += off;
}
if ( ori == aiOrigin_BEG ) {
stream.readOffset = off;
}
};
stream.ReadBytes = function ( buff, size, n ) {
var bytes = size * n;
for ( var i = 0; i < bytes; i ++ )
buff[ i ] = Read_uint8_t( this );
};
stream.subArray32 = function ( start, end ) {
var buff = this.buffer;
var newbuff = buff.slice( start, end );
return new Float32Array( newbuff );
};
stream.subArrayUint16 = function ( start, end ) {
var buff = this.buffer;
var newbuff = buff.slice( start, end );
return new Uint16Array( newbuff );
};
stream.subArrayUint8 = function ( start, end ) {
var buff = this.buffer;
var newbuff = buff.slice( start, end );
return new Uint8Array( newbuff );
};
stream.subArrayUint32 = function ( start, end ) {
var buff = this.buffer;
var newbuff = buff.slice( start, end );
return new Uint32Array( newbuff );
};
}
var shortened, compressed;
function InternReadFile( pFiledata ) {
var pScene = new aiScene();
var stream = new DataView( pFiledata );
extendStream( stream );
stream.Seek( 44, aiOrigin_CUR ); // signature
/*unsigned int versionMajor =*/
pScene.versionMajor = Read_unsigned_int( stream );
/*unsigned int versionMinor =*/
pScene.versionMinor = Read_unsigned_int( stream );
/*unsigned int versionRevision =*/
pScene.versionRevision = Read_unsigned_int( stream );
/*unsigned int compileFlags =*/
pScene.compileFlags = Read_unsigned_int( stream );
shortened = Read_uint16_t( stream ) > 0;
compressed = Read_uint16_t( stream ) > 0;
if ( shortened )
throw "Shortened binaries are not supported!";
stream.Seek( 256, aiOrigin_CUR ); // original filename
stream.Seek( 128, aiOrigin_CUR ); // options
stream.Seek( 64, aiOrigin_CUR ); // padding
if ( compressed ) {
var uncompressedSize = Read_uint32_t( stream );
var compressedSize = stream.FileSize() - stream.Tell();
var compressedData = [];
stream.Read( compressedData, 1, compressedSize );
var uncompressedData = [];
uncompress( uncompressedData, uncompressedSize, compressedData, compressedSize );
var buff = new ArrayBuffer( uncompressedData );
ReadBinaryScene( buff, pScene );
} else {
ReadBinaryScene( stream, pScene );
}
return pScene.toTHREE();
}
return InternReadFile( buffer );
}
};
export { AssimpLoader };
|
var uncurryThis = require('../internals/function-uncurry-this');
module.exports = uncurryThis({}.isPrototypeOf);
|
export { default } from './src/button.vue';
|
/**
* Background
* ==========
*
* Intercept and allow CORS request for all 'arraybuffer' requests on video sources.
*
* API:
* - https://developer.chrome.com/extensions/webRequest
*/
/**
* Open sonarvio site on browser action
*/
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.executeScript({
code: 'window.open("http://sonarvio.com")'
})
})
var accessControlRequestHeaders
/**
* Handle outgoing requests
*/
chrome.webRequest.onBeforeSendHeaders.addListener(function requestListener (details) {
console.log('request, ', details);
if (isSupportedType(details.url)) {
if (details.method === 'OPTIONS') {
for (var header of details.requestHeaders) {
if (header.name === 'Access-Control-Request-Headers') {
accessControlRequestHeaders = header.value
// console.log('HEADER', header);
break
}
}
}
}
return {
requestHeaders: details.requestHeaders
}
}, {
urls: ["*://*/*"]
}, ['blocking', 'requestHeaders'])
/**
* Handle incoming responses
*/
chrome.webRequest.onHeadersReceived.addListener(function responseListener (details) {
var headers = details.responseHeaders
if (
isSupportedType(details.url) &&
['OPTIONS', 'HEAD', 'GET'].indexOf(details.method) > -1
) {
var set = false
// check if header is provided (not for its own origin)
for (var header of headers) {
if (header.name === 'Access-Control-Allow-Origin') {
set = true
header.value = '*'
break
}
}
// if not already provided add CORS header
if (!set) {
headers.push({
name: 'Access-Control-Allow-Origin',
value: '*'
})
}
// used - set during the request phase
if (accessControlRequestHeaders) {
headers.push({
name: 'Access-Control-Allow-Headers',
value: accessControlRequestHeaders
})
}
// optional -> check if access-control-allow is not set, then set
// define the methods of HEAD, GET, OPTIONS
// details.responseHeaders.push({
// name: 'Access-Control-Allow-Methods',
// value: 'HEAD, GET, OPTIONS'
// })
// declare accessible properties
headers.push({
name: 'Access-Control-Expose-Headers',
value: 'Accept-Ranges, Content-Encoding, Content-Range, Content-Length'
})
}
return {
responseHeaders: headers
}
}, {
urls: ["*://*/*"]
}, ['blocking', 'responseHeaders'])
/**
* Check file type
*
* @param {string} url -
*/
function isSupportedType (url) {
var extension = url.substr(url.lastIndexOf('.') + 1).toLowerCase()
return ['mp4', 'webm'].indexOf(extension) > -1
}
|
/*! jQuery UI - v1.10.4 - 2014-05-18
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional.eo={closeText:"Fermi",prevText:"<Anta",nextText:"Sekv>",currentText:"Nuna",monthNames:["Januaro","Februaro","Marto","Aprilo","Majo","Junio","Julio","Aŭgusto","Septembro","Oktobro","Novembro","Decembro"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aŭg","Sep","Okt","Nov","Dec"],dayNames:["Dimanĉo","Lundo","Mardo","Merkredo","Ĵaŭdo","Vendredo","Sabato"],dayNamesShort:["Dim","Lun","Mar","Mer","Ĵaŭ","Ven","Sab"],dayNamesMin:["Di","Lu","Ma","Me","Ĵa","Ve","Sa"],weekHeader:"Sb",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.eo)}); |
import getMuiTheme from 'styles/getMuiTheme';
const MSIE9_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)';
describe('prepareStyles', () => {
describe('prefixer', () => {
it('should prefix for all when userAgent is all', () => {
const muiTheme = getMuiTheme({}, {
userAgent: 'all',
});
const stylePrepared = muiTheme.prepareStyles({
transform: 'rotate(90)',
});
expect(stylePrepared).to.deep.equal({
transform: 'rotate(90)',
muiPrepared: true,
WebkitTransform: 'rotate(90)',
MozTransform: 'rotate(90)',
msTransform: 'rotate(90)',
});
});
it('should prefix for the userAgent when we provid a valid one', () => {
const muiTheme = getMuiTheme({}, {
userAgent: MSIE9_USER_AGENT,
});
const stylePrepared = muiTheme.prepareStyles({
transform: 'rotate(90)',
});
expect(stylePrepared).to.deep.equal({
muiPrepared: true,
msTransform: 'rotate(90)',
});
});
it('should not prefix when userAgent is false', () => {
const muiTheme = getMuiTheme({}, {
userAgent: false,
});
const stylePrepared = muiTheme.prepareStyles({
transform: 'rotate(90)',
});
expect(stylePrepared).to.deep.equal({
transform: 'rotate(90)',
muiPrepared: true,
});
});
});
});
|
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _three = require('three');
var THREE = _interopRequireWildcard(_three);
var _GeometryWithShapesDescriptor = require('./GeometryWithShapesDescriptor');
var _GeometryWithShapesDescriptor2 = _interopRequireDefault(_GeometryWithShapesDescriptor);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ShapeGeometryDescriptor = function (_GeometryWithShapesDe) {
_inherits(ShapeGeometryDescriptor, _GeometryWithShapesDe);
function ShapeGeometryDescriptor() {
_classCallCheck(this, ShapeGeometryDescriptor);
return _possibleConstructorReturn(this, (ShapeGeometryDescriptor.__proto__ || Object.getPrototypeOf(ShapeGeometryDescriptor)).apply(this, arguments));
}
_createClass(ShapeGeometryDescriptor, [{
key: 'refreshGeometry',
// noinspection JSMethodCanBeStatic
value: function refreshGeometry(threeObject) {
var shapes = threeObject.userData._shapeCache.filter(function (shape) {
return !!shape;
}).concat(threeObject.userData._shapesFromProps);
if (threeObject.userData._options.hasOwnProperty('curveSegments')) {
threeObject.fromGeometry(new THREE.ShapeGeometry(shapes, threeObject.userData._options.curveSegments));
} else {
threeObject.fromGeometry(new THREE.ShapeGeometry(shapes));
}
}
}]);
return ShapeGeometryDescriptor;
}(_GeometryWithShapesDescriptor2.default);
module.exports = ShapeGeometryDescriptor; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.